安卓 - 在活动(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智能... 一分钟了解透视!金麒麟ai智能透视软件,金麒麟有挂么攻略(原来有挂解密)1、进入到金麒麟是否有挂之后...
大神推荐辅助挂!圣光区ai智能... 大神推荐辅助挂!圣光区ai智能辅助挂app,圣光区辅助工具资料(总是有挂技术);1、完成圣光区辅助器...
大家学习交流开挂!新超凡大厅a... 大家学习交流开挂!新超凡大厅ai智能开挂插件,新超凡大厅透视软件下载指引(一直有挂技术)1、进入游戏...
一分钟揭秘透视挂!尖尖互娱ai... 一分钟揭秘透视挂!尖尖互娱ai智能透视挂教程,尖尖互娱是不是有挂方针(确实发现有挂)一分钟揭秘透视挂...
分享实测辅助挂!新辣椒互娱ai... 分享实测辅助挂!新辣椒互娱ai智能辅助挂技巧,新辣椒互娱透视方法手筋(果然有挂辅助)1、游戏颠覆性的...
今日辅助器!乐乐大厅ai智能辅... 今日辅助器!乐乐大厅ai智能辅助器app,乐乐大厅确实真的有挂诀窍(原来有挂教学)亲,关键说明,乐乐...
科普常识透视挂!轩辕大厅ai智... 科普常识透视挂!轩辕大厅ai智能透视挂教程,轩辕大厅有没有透视挂教程书(切实有挂技术)1、让任何用户...
每日必备透视挂!毛豆大厅ai智... 每日必备透视挂!毛豆大厅ai智能透视挂攻略,毛豆大厅开挂工具妙招(都是有挂技术)1、游戏颠覆性的策略...
一分钟秒懂透视!百万牛ai智能... 一分钟秒懂透视!百万牛ai智能透视技巧,百万牛透视开挂教材(都是发现有挂)百万牛脚本下载中分为三种模...
必知教程辅助器!星狗揽月ai智... 必知教程辅助器!星狗揽月ai智能辅助器app,星狗揽月透视方法方案(一贯有挂技术)所有人都在同一条线...