安卓 - 在活动(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、湖北卡五星辅助软件免费辅助多...
推荐一款!天天爱柳州麻将辅助器... 推荐一款!天天爱柳州麻将辅助器,乐达大连穷胡小鸡满天飞,详细插件(有挂教学)暗藏猫腻,小编详细说明乐...
玩家必看!欢聚水鱼辅助,免费挂... 玩家必看!欢聚水鱼辅助,免费挂机辅助工具,详细技巧(有挂秘诀)一、免费挂机辅助工具游戏安装教程牌型概...
技巧知识分享!潮汕激k辅助器,... 技巧知识分享!潮汕激k辅助器,九九山城插件程序,详细挂(有挂教学)一、九九山城插件程序游戏安装教程牌...
一分钟揭秘!丰城双剑新版最强高... 一分钟揭秘!丰城双剑新版最强高分攻略,小程序游戏修改器辅助,详细脚本(有挂实锤)1、完成丰城双剑新版...
必看攻略!天蝎辅助,钱塘十三水... 必看攻略!天蝎辅助,钱塘十三水辅助,详细攻略(有挂攻略)1、用户打开应用后不用登录就可以直接使用,点...
推荐一款!广东闲来有辅助软件,... 您好,广东闲来有辅助软件这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多...
发现一款!欢乐茶馆修改器,皮皮... 发现一款!欢乐茶馆修改器,皮皮跑胡子系统有鬼,详细软件(有挂秘诀)1、游戏颠覆性的策略玩法,独创攻略...
揭秘几款!吉祥填大坑有什么诀窍... 揭秘几款!吉祥填大坑有什么诀窍,天天微友插件,详细器(存在有挂)1、用户打开应用后不用登录就可以直接...