常規(guī)情況下茄菊,activity與service之間的通訊都是通過intent進行數(shù)據(jù)傳遞的
本文講述通過LocalBroadcastManager實現(xiàn)其通訊舶胀。
LocalBroadcastManager 是 Android 提供的用于在應(yīng)用內(nèi)部發(fā)送廣播的工具,它可以有效地在 Activity 和 Service 之間進行通信网梢。使用 LocalBroadcastManager 可以高效地在同一個應(yīng)用內(nèi)的不同組件之間通信震缭,且相比于系統(tǒng)廣播,它的性能開銷更小战虏,并且不會被其他應(yīng)用接收到拣宰。
step 1 添加依賴庫
implementation 'androidx.localbroadcastmanager:localbroadcastmanager:1.0.0'
step 2 創(chuàng)建一個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 創(chuàng)建一個service發(fā)送廣播
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) {
// 發(fā)送廣播
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;
}
}