安卓 - 在活动(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");
}

相关内容

热门资讯

程序员教你作弊器攻略!欢乐赣游... 程序员教你作弊器攻略!欢乐赣游GZ多功能作弊器攻略,欢乐赣游GZ原来存在有作弊器攻略1、起透看视 欢...
大家学习交流作弊器工具!天天黄... 大家学习交流作弊器工具!天天黄冈麻将多功能作弊器工具,天天黄冈麻将原来有作弊器工具1、超多福利:超高...
揭秘攻略作弊器插件!亲邻麻将多... 揭秘攻略作弊器插件!亲邻麻将多功能作弊器插件,亲邻麻将原来有作弊器插件1.亲邻麻将 选牌创建新账号,...
玩家攻略推荐透视器方法!三鑫联... 玩家攻略推荐透视器方法!三鑫联盟多功能透视器方法,三鑫联盟一贯存在有透视器方法1、不需要AI权限,帮...
我来教教你透视器工具!桓仁奥云... 我来教教你透视器工具!桓仁奥云麻将多功能透视器工具,桓仁奥云麻将一贯存在有透视器工具1)桓仁奥云麻将...
我来教教大家透视挂插件!朱雀吴... 我来教教大家透视挂插件!朱雀吴江三缺一多功能透视挂插件,朱雀吴江三缺一总是有透视挂插件1、下载好朱雀...
推荐一款透视器软件!小闲巴渝棋... 推荐一款透视器软件!小闲巴渝棋牌多功能透视器软件,小闲巴渝棋牌一直是有透视器软件所有人都在同一条线上...
科普攻略开挂方法!喜乐多功能开... 科普攻略开挂方法!喜乐多功能开挂方法,喜乐其实存在有开挂方法1、用户打开应用后不用登录就可以直接使用...
今日公布透视器攻略!天天芜湖麻... 今日公布透视器攻略!天天芜湖麻将多功能透视器攻略,天天芜湖麻将都是有透视器攻略1、每一步都需要思考,...
一分钟了解透视器插件!桃乐甘肃... 一分钟了解透视器插件!桃乐甘肃麻将多功能透视器插件,桃乐甘肃麻将果然真的有透视器插件1、每一步都需要...