安卓 - 在活动(Activity)和后台服务(Background Service)之间进行通信的最佳方式
创始人
2024-09-01 15:01:00
0次

在安卓中,可以使用广播(Broadcast)和绑定服务(Bound Service)来实现活动和后台服务之间的通信。下面是使用广播和绑定服务的代码示例:

  1. 使用广播实现通信: 在活动中发送广播:
Intent intent = new Intent("com.example.MY_ACTION");
intent.putExtra("message", "Hello from Activity");
sendBroadcast(intent);

在后台服务中注册广播接收器:

private BroadcastReceiver receiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        String message = intent.getStringExtra("message");
        // 处理接收到的消息
    }
};

@Override
public void onCreate() {
    super.onCreate();
    IntentFilter filter = new IntentFilter("com.example.MY_ACTION");
    registerReceiver(receiver, filter);
}

@Override
public void onDestroy() {
    super.onDestroy();
    unregisterReceiver(receiver);
}
  1. 使用绑定服务实现通信: 在活动中绑定服务:
private MyService myService;
private boolean isBound = false;

private ServiceConnection serviceConnection = new ServiceConnection() {
    @Override
    public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
        MyService.MyBinder binder = (MyService.MyBinder) iBinder;
        myService = binder.getService();
        isBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName componentName) {
        isBound = false;
    }
};

@Override
protected void onStart() {
    super.onStart();
    Intent intent = new Intent(this, MyService.class);
    bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);
}

@Override
protected void onStop() {
    super.onStop();
    if (isBound) {
        unbindService(serviceConnection);
        isBound = false;
    }
}

在后台服务中创建绑定服务:

public class MyService extends Service {
    private final IBinder binder = new MyBinder();

    public class MyBinder extends Binder {
        MyService getService() {
            return MyService.this;
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return binder;
    }

    // 在后台服务中定义方法供活动调用
    public void sendMessage(String message) {
        // 处理接收到的消息
    }
}

在活动中调用后台服务的方法:

if (isBound) {
    myService.sendMessage("Hello from Activity");
}

相关内容

热门资讯

科普攻略透视挂!久久大厅辅助透... 科普攻略透视挂!久久大厅辅助透视挂,中至常熟麻将真的有外挂,一贯有人有挂1、金币登录送、破产送、升级...
迎来新发展透视挂!寓教娱乐辅助... 迎来新发展透视挂!寓教娱乐辅助透视挂,天天温岭麻将存在有外挂,切实有挂透明挂1、实时寓教娱乐透视辅助...
技巧知识分享透视挂!哥哥斗地主... 技巧知识分享透视挂!哥哥斗地主辅助透视挂,都城麻将真的有外挂,果然有挂头条1、打开软件启动之后找到中...
热点推荐透视挂!极速暗宝辅助透... 热点推荐透视挂!极速暗宝辅助透视挂,开心廉江麻将是真的有外挂,都是有挂规律1)极速暗宝辅助插件:进一...
大神推荐开挂!随意玩辅助透视挂... 大神推荐开挂!随意玩辅助透视挂,灵飞承德麻将确实有外挂,真是有挂攻略暗藏猫腻,小编详细说明随意玩破解...
我来教大家辅助!云海辅助透视挂... 我来教大家辅助!云海辅助透视挂,原味麻将真的是有外挂,真是有挂攻略;1、在云海插件功能辅助器技巧中,...
据目击者称开挂!大胜跑得快辅助... 据目击者称开挂!大胜跑得快辅助透视挂,新上游真的有外挂,果然有挂方法1、大胜跑得快辅助软件下载优化,...
这一问题亟待解决开挂!追忆辅助... 这一问题亟待解决开挂!追忆辅助透视挂,土豆棋牌真的是有外挂,原来有挂存在1、全新机制【追忆ai辅助工...
每日必看教程辅助!同城游红十辅... 每日必看教程辅助!同城游红十辅助透视挂,中至常熟麻将真的是有外挂,都是有挂功能同城游红十破解侠是真的...
科技新动态透视挂!决胜奕福辅助... 科技新动态透视挂!决胜奕福辅助透视挂,happyworkbook存在有外挂,竟然果真有挂1、该软件可...