常规情况下,activity与service之间的通讯都是通过intent进行数据传递的
本文讲述通过LocalBroadcastManager实现其通讯。
LocalBroadcastManager 是 Android 提供的用于在应用内部发送广播的工具,它可以有效地在 Activity 和 Service 之间进行通信。使用 LocalBroadcastManager 可以高效地在同一个应用内的不同组件之间通信,且相比于系统广播,它的性能开销更小,并且不会被其他应用接收到。
step 1 添加依赖库
implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'
step 2 创建一个activity 接收广播
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
public class MyActivity extends AppCompatActivity {
private BroadcastReceiver mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// 处理接收到的广播
String data = intent.getStringExtra("extra_data");
Toast.makeText(context, data, Toast.LENGTH_SHORT).show();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 启动 Service
Intent serviceIntent = new Intent(this, MyService.class);
startService(serviceIntent);
}
@Override
protected void onStart() {
super.onStart();
// 注册广播接收器
LocalBroadcastManager.getInstance(this).registerReceiver(mReceiver,
new IntentFilter("MY_ACTION"));
}
@Override
protected void onStop() {
super.onStop();
// 注销广播接收器
LocalBroadcastManager.getInstance(this).unregisterReceiver(mReceiver);
}
}
step 3 创建一个service发送广播
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import androidx.localbroadcastmanager.content.LocalBroadcastManager;
public class MyService extends Service {
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 发送广播
Intent localIntent = new Intent("MY_ACTION");
localIntent.putExtra("extra_data", "Hello from Service");
LocalBroadcastManager.getInstance(this).sendBroadcast(localIntent);
return START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
网友评论