安卓 - 在活动(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、下载安装好赣牌圈科技,进入游戏主...
最新技巧!!微信道游拼十辅助器... 最新技巧!!微信道游拼十辅助器,蜜瓜大厅可以装挂吗,2024教程(有挂细节);无需打开直接搜索加(薇...
让我来分享经验!宝宝吃吃吃游戏... 让我来分享经验!宝宝吃吃吃游戏辅助,兴动互娱辅助器多少钱,系统教程(真是有挂);无需打开直接搜索加薇...
普及知识!多乐小程序破解版修改... 普及知识!多乐小程序破解版修改器,贪吃蛇辅助器,透明挂教程(有挂头条)1、下载安装好多乐小程序破解版...
程序员教你!山城九九辅助,泸州... 您好:泸州大二新手攻略这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很多用户的牌...
今日科普!丹东约战麻将辅助器,... 今日科普!丹东约战麻将辅助器,多乐辅助器,揭秘教程(有挂规律)1、下载安装好丹东约战麻将辅助器,进入...
重磅来袭!约局吧黑科技辅助器,... 重磅来袭!约局吧黑科技辅助器,途游手游辅助,可靠教程(有挂教学)1、下载安装好约局吧黑科技辅助器,进...
玩家必看分享!嘟咪互动修改器,... 玩家必看分享!嘟咪互动修改器,新超凡软件辅助,透视教程(有挂教程)1、下载安装好嘟咪互动修改器,进入...
教程辅助!好运南通长牌辅助,樱... 教程辅助!好运南通长牌辅助,樱花之盛辅助软件,介绍教程(有挂秘笈);无需打开直接搜索加薇136704...
记者发布!聚财app辅助,宝宝... 记者发布!聚财app辅助,宝宝游戏辅助,必赢教程(有人有挂)1、下载安装好宝宝游戏辅助,进入游戏主界...