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

相关内容

热门资讯

一次性透视!aapoker破解... 一次性透视!aapoker破解侠是真的“推荐开挂辅助器”1、aapoker破解侠是真的系统规律教程、...
第一次性发现!指尖四川辅助脚本... 第一次性发现!指尖四川辅助脚本“解谜开挂辅助插件”亲,关键说明,指尖四川辅助脚本赛季回归,指尖四川辅...
六次性领会!指尖四川辅助脚本视... 六次性领会!指尖四川辅助脚本视频“揭幕开挂辅助教程”1、上手简单,内置详细流程视频教学,新手小白可以...
9次性普及!掌电竞技辅助器“解... 9次性普及!掌电竞技辅助器“解密开挂辅助插件”一、掌电竞技辅助器AI软件牌型概率发牌机制”必胜“技巧...
第8次性掌握!赣牌圈修改器“推... 第8次性掌握!赣牌圈修改器“推荐开挂辅助app”1、上手简单,内置详细流程视频教学,新手小白可以快速...
三次性了解!大菠萝789辅助“... 三次性了解!大菠萝789辅助“解迷开挂辅助神器”1、首先打开大菠萝789辅助最新版本,在大菠萝789...
第二次性私人局!欢聚水鱼神器“... 第二次性私人局!欢聚水鱼神器“曝光开挂辅助器”1、超多福利:超高返利,海量正版游戏,欢聚水鱼神器系统...
3次性理解!闲逸辅助软件“专业... 3次性理解!闲逸辅助软件“专业开挂辅助插件”闲逸辅助软件辅助器中分为三种模型:闲逸辅助软件软件透明挂...
第五次性掌握!皮皮游戏辅助工具... 第五次性掌握!皮皮游戏辅助工具“揭露开挂辅助教程”在进入皮皮游戏辅助工具辅助挂后,参与本局比赛的八名...
1次性晓得!沧海十三水私人局辅... 1次性晓得!沧海十三水私人局辅助器“分享开挂辅助器”沧海十三水私人局辅助器是一种具有地方特色的麻将游...