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

相关内容

热门资讯

正版作弊器宝剑联盟作弊器多功能... 正版作弊器宝剑联盟作弊器多功能AI工具,宝剑联盟其实有作弊器工具1、每一步都需要思考,不同水平的挑战...
WPK下载妙招!aapoker... WPK下载妙招!aapoker能控制牌吗,红龙扑克ai多功能透视神器1、首先打开aapoker能控制...
正版作弊器新毫互娱麻将作弊器多... 正版作弊器新毫互娱麻将作弊器多功能AI插件,新毫互娱麻将一直真的是有作弊器插件1、超多福利:超高返利...
WPK下载项目!德州私人局脚本... WPK下载项目!德州私人局脚本,红龙PoKerai多功能辅助器神器1、WPK下载项目!德州私人局脚本...
正版开挂新玉海楼茶苑开挂多功能... 正版开挂新玉海楼茶苑开挂多功能AI教程,新玉海楼茶苑原来是有开挂教程1、完成新玉海楼茶苑有辅助插件,...
WPK私人局方式!德扑圈有透视... WPK私人局方式!德扑圈有透视吗,智星菠萝德州ai多功能辅助器app1、德扑圈有透视吗模拟器是什么优...
正版透视挂边锋辽宁麻将透视挂多... 您好,边锋辽宁麻将这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很多玩家在...
WPK工具窍要!德扑之星辅助器... 您好,德扑之星辅助器app这款游戏可以开挂的,确实是有挂的,需要了解加去威信【136704302】很...
正版作弊器朋友安徽麻将作弊器多... 正版作弊器朋友安徽麻将作弊器多功能AI技巧,朋友安徽麻将果然有作弊器技巧朋友安徽麻将透视方法中分为三...
WPK真假策略!德州辅助工具到... WPK真假策略!德州辅助工具到底怎么样,aapokerai多功能透视挂攻略进入游戏-大厅左侧-新手福...