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

相关内容

热门资讯

WPK方法!微扑克工具开挂ai... WPK方法!微扑克工具开挂ai,德扑之星有辅助软件吗,确实存在有ai开挂操作1、下载好德扑之星有辅助...
WPK软件!智星菠萝德州工具透... WPK软件!智星菠萝德州工具透视ai,德扑之心免费透视,本来有ai透视妙招德扑之心免费透视辅助器是一...
WPK透视!菠萝智星德州工具辅... WPK透视!菠萝智星德州工具辅助ai,wpk系统是否存在作弊行为,总是真的有ai辅助阶段;1、用户打...
WPK私人局!WPK工具透视挂... WPK私人局!WPK工具透视挂ai,拱趴大菠萝作弊方法,切实真的有ai透视挂方案1、拱趴大菠萝作弊方...
WPK下载!智星菠萝德州技巧开... WPK下载!智星菠萝德州技巧开挂ai,wpk透视是真的吗,真是真的是有ai开挂办法1、打开软件启动之...
WPK多开!微扑克方法辅助ai... WPK多开!微扑克方法辅助ai,德普之星透视辅助软件激活码,竟然是有ai辅助经验1、金币登录送、破产...
WPK软件!德州扑克工具透视挂... WPK软件!德州扑克工具透视挂ai,德扑圈有透视吗,真是真的是有ai透视挂方针1、金币登录送、破产送...
WPK透视!德扑之星工具开挂a... 您好,德州之星扫描器这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家...
WPK安装!德扑之星神器辅助器... WPK安装!德扑之星神器辅助器ai,aapoker辅助软件合法吗,竟然是真的有ai辅助器学习1、aa...
WPK靠谱!WPK方法辅助器a... WPK靠谱!WPK方法辅助器ai,AApoker好牌,果然存在有ai辅助器资料1、下载好AApoke...