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

相关内容

热门资讯

三分钟了解!吉祥麻将斗地主可以... 《三分钟了解!吉祥麻将斗地主可以让系统发好牌(辅助挂)一直真的是有挂(专业辅助科技教程)-哔哩哔哩》...
第2分钟了解!大赢家跑得快辅助... 第2分钟了解!大赢家跑得快辅助工具(辅助挂)一贯真的是有挂(专业辅助揭秘教程)-哔哩哔哩;大赢家跑得...
第九分钟了解!丫丫湘西麻将有挂... 第九分钟了解!丫丫湘西麻将有挂(辅助挂)确实真的是有挂(专业辅助德州教程)-哔哩哔哩;详细丫丫湘西麻...
四分钟了解!江西中至麻将有挂的... 四分钟了解!江西中至麻将有挂的(辅助挂)一贯真的有挂(专业辅助透明挂教程)-哔哩哔哩;最新版2026...
6分钟了解!八闽十三张有外挂(... 6分钟了解!八闽十三张有外挂(辅助挂)都是是有挂(专业辅助可靠技巧)-哔哩哔哩;1、完成八闽十三张有...
两分钟了解!丽水茶苑有辅助器(... 您好,丽水茶苑有辅助器这款游戏可以开挂的,确实是有挂的,需要了解加微【136704302】很多玩家在...
7分钟了解!福建十三水辅助软件... 7分钟了解!福建十三水辅助软件大全(辅助挂)起初是有挂(专业辅助必备教程)-哔哩哔哩;是一款可以让一...
第二分钟了解!手机陕西麻将辅牌... 您好:手机陕西麻将辅牌器可以下载这款游戏可以开挂的,确实是有挂的,很多玩家在这款游戏中打牌都会发现很...
两分钟了解!乐逍遥跑胡子软件(... 两分钟了解!乐逍遥跑胡子软件(辅助挂)都是真的有挂(专业辅助必备教程)-哔哩哔哩;1、很好的乐逍遥跑...
八分钟了解!爱来掌中宝510k... 八分钟了解!爱来掌中宝510k有挂(辅助挂)原先真的有挂(专业辅助攻略教程)-哔哩哔哩;爱来掌中宝5...