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

相关内容

热门资讯

一分钟揭秘!天天互娱网络科技,... 一分钟揭秘!天天互娱网络科技,wepoker代打辅助机器人,详细教程(有挂秘诀);一分钟揭秘!天天互...
一分钟了解!乐酷副厅辅助,闲逸... 一分钟了解!乐酷副厅辅助,闲逸亲友圈辅助下载(果然是真的有挂)1、在闲逸亲友圈辅助下载插件功能辅助器...
今日焦点!方片十三张外挂,聚星... 【福星临门,好运相随】;今日焦点!方片十三张外挂,聚星ai辅助工具激活码,新2025版(有挂秘笈);...
分享开挂内幕!闲逸辅助软件下载... 分享开挂内幕!闲逸辅助软件下载苹果,天天爱柳州麻将辅助器(竟然有挂)1、闲逸辅助软件下载苹果免费脚本...
终于知道!九酷众游辅助,hhp... 您好,九酷众游辅助这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在这款...
玩家必备攻略!微乐小程序微乐房... 玩家必备攻略!微乐小程序微乐房间怎么开挂,波特互娱辅助(本来是有挂)1、微乐小程序微乐房间怎么开挂辅...
科技通报!哈狗智能辅助,hhp... 科技通报!哈狗智能辅助,hhpoker真的有透视吗,解密教程(有挂分享);1、这是跨平台的哈狗智能辅...
玩家必看科普!闲逸碰胡辅助器,... 玩家必看科普!闲逸碰胡辅助器,边锋透视器(总是真的是有挂)1、超多福利:超高返利,海量正版游戏,闲逸...
重磅来袭!开心赢三张自建房有挂... 您好:开心赢三张自建房有挂吗这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用...
每日必看!道游互娱透视辅助截图... 每日必看!道游互娱透视辅助截图,老友广东辅助工具(竟然是有挂)所有人都在同一条线上,像星星一样排成一...