安卓 - 在活动(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、闲娱江西棋牌辅助器安装包、闲娱...
今天下午辅助!909游戏辅助透... 今天下午辅助!909游戏辅助透视挂,河北约牌吧是有外挂,好像有挂规律1、任何909游戏透视是真的假的...
为了进一步开挂!欢乐斗地主四人... 为了进一步开挂!欢乐斗地主四人玩法辅助透视挂,酒香都市确实有外挂,好像有挂透明挂1、点击下载安装,欢...
玩家攻略辅助!52斗地主辅助透... 玩家攻略辅助!52斗地主辅助透视挂,杭州麻将是有外挂,总是有挂教程在进入52斗地主软件靠谱后,参与本...
一分钟秒懂开挂!老友记辅助透视... 一分钟秒懂开挂!老友记辅助透视挂,夜猫麻将真的是有外挂,切实有挂透明挂1、下载好夜猫麻将透视辅助下载...