安卓 - 在活动(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、芷芷休闲有没有辅助教程...
2分钟细说!宝宝浙江开挂功能a... 2分钟细说!宝宝浙江开挂功能app,宝宝浙江都是是有开挂app(有辅助挂教学)小薇(辅助器软件下载)...
揭秘关于!棋牌游辅助功能攻略,... 揭秘关于!棋牌游辅助功能攻略,棋牌游竟然真的有辅助攻略(有辅助挂攻略)1.棋牌游 选牌创建新账号,点...
实测揭晓!七月游戏透视功能ap... 实测揭晓!七月游戏透视功能app,七月游戏确实是有透视app(有辅助挂猫腻)1、完成七月游戏辅助器v...
玩家必看科普!如意棋牌辅助器功... 玩家必看科普!如意棋牌辅助器功能工具,如意棋牌其实是真的有辅助器工具(有辅助挂详细)如意棋牌能透视中...
最新技巧!鼎盛棋牌开挂功能插件... 最新技巧!鼎盛棋牌开挂功能插件,鼎盛棋牌总是是有开挂插件(有辅助挂神器)1、在鼎盛棋牌插件功能辅助器...
揭秘一下!微友约局开挂功能教程... 揭秘一下!微友约局开挂功能教程,微友约局总是有开挂教程(真实有辅助挂)1、揭秘一下!微友约局开挂功能...