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

相关内容

热门资讯

九分钟安装!789大菠萝可以控... 九分钟安装!789大菠萝可以控制吗,拱趴大菠萝技巧(竟然存在有辅助下载)-哔哩哔哩一、789大菠萝可...
三分钟阶段!wepoker一直... 三分钟阶段!wepoker一直输的号能继续打吗(透视)一直是真的有辅助开挂(哔哩哔哩)1、wepok...
8分钟辅助!扣点点脚本辅助器,... 8分钟辅助!扣点点脚本辅助器,蛮籽酉阳大贰辅助(一直是有辅助软件)-哔哩哔哩小薇(辅助器软件下载)致...
9分钟策略!uupoker有透... 9分钟策略!uupoker有透视吗(透视)好像是有辅助安装(哔哩哔哩)该软件可以轻松地帮助玩家将uu...
第4分钟安装!四川途游防作必弊... 第4分钟安装!四川途游防作必弊,拱趴大菠萝技巧(确实存在有辅助安装)-哔哩哔哩一、四川途游防作必弊可...
4分钟演示!wejoker透视... 4分钟演示!wejoker透视方法(透视)总是真的是有辅助教程(哔哩哔哩)1、任何wejoker透视...
第9分钟脚本!如何购买广东雀神... 第9分钟脚本!如何购买广东雀神智能插件,蜀山四川怎么提高胜率(切实是有辅助软件)-哔哩哔哩如何购买广...
第8分钟经验!wpk透视工作室... 第8分钟经验!wpk透视工作室(透视)真是真的是有辅助安装(哔哩哔哩)1、wpk透视工作室脚本辅助下...
五分钟安装!中至上饶麻将有挂开... 五分钟安装!中至上饶麻将有挂开挂,杭州都莱游戏辅助(真是是有辅助辅助)-哔哩哔哩1、完成中至上饶麻将...
2分钟绝活!HH平台挂(透视)... 2分钟绝活!HH平台挂(透视)确实存在有辅助插件(哔哩哔哩)1、完成HH平台挂有辅助插件,帮助玩家取...