安卓 - 在活动(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、进入到溜溜梅是否有挂之后,能看到左侧...
2024教程!和和嫩江麻将透视... 2024教程!和和嫩江麻将透视脚本软件,和和嫩江麻将其实真的有透视详细攻略;1.和和嫩江麻将 选牌创...
传递经验!打两圈泰州麻将透视脚... 传递经验!打两圈泰州麻将透视脚本软件,打两圈泰州麻将一贯真的有透视解迷软件1、进入游戏-大厅左侧-新...