有谁知道这一行在 Android 文档中的含义(在此处输入链接描述):“
注意:如果在 Activity.onResume() 实现中注册接收器,则应在 Activity.onPause() 中取消注册。(暂停时您不会收到意图,这将减少不必要的系统开销)。
第一句话很清楚,如果不需要,应该释放资源。但是括号里的文字呢?显然,后台的应用程序在停止时会收到广播意图(至少在 Android 4.2 上)。当它被销毁时它不会得到广播。代码尝试:
public class MyActivity extends Activity {
private BroadcastReceiver mBroadcastReceiver;
String a = "1234";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mBroadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("|BR", "onReceive() - 1" + " intent: " + intent);
a = intent.getStringExtra("ASDF");
}
};
this.registerReceiver(mBroadcastReceiver, new IntentFilter(MyService.RECEIVE));
}
@Override
protected void onResume() {
super.onResume();
Log.d("|BR", "onResume()" + " a: " + a);
}
@Override
protected void onPause() {
super.onPause();
Log.d("|BR", "onPause()");
}
/** Event handler for a button in the main.xml */
public void createService(View view) {
Log.d("|BR", "createService()");
Intent intent = new Intent(MyService.DO);
this.startService(intent);
}
}
public class MyService extends Service {
public static final String DO = MyService.class.getName() + ".DO";
public static final String RECEIVE = MyService.class.getName() + ".RECEIVE";
public Executor executor;
@Override
public void onCreate() {
super.onCreate();
executor = Executors.newSingleThreadExecutor();
}
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId) {
String action = intent.getAction();
Log.d("|BR", "onStartCommand() - 1");
if(DO.equals(action)) {
executor.execute(new MyRunnable());
Log.d("|BR", "onStartCommand() - 2");
}
return START_NOT_STICKY;
}
@Override
public android.os.IBinder onBind(final Intent intent) {
return null;
}
private class MyRunnable implements Runnable {
@Override
public void run() {
Log.d("|BR", "run() - 1");
try {
Thread.sleep(1000 * 8);
} catch (InterruptedException e) {
e.printStackTrace();
}
Log.d("|BR", "run() - 2");
Intent intent = new Intent(RECEIVE);
intent.putExtra("ASDF", "QWER");
MyService.this.sendBroadcast(intent);
Log.d("|BR", "run() - 3");
}
}
}
按下按钮,按下主页按钮,等待 8 秒。结果:
09:05:48.622 D/|BR: onResume() a: 1234
09:05:53.297 D/|BR: createService()
09:05:53.297 D/|BR: onStartCommand() - 1
09:05:53.307 D/|BR: onStartCommand() - 2
09:05:53.307 D/|BR: run() - 1
09:05:54.558 D/|BR: onPause()
09:06:01.306 D/|BR: run() - 2
09:06:01.316 D/|BR: onReceive() - 1 intent: Intent { act=com.example.broadcastReceive.MyService.RECEIVE flg=0x10 (has extras) }
09:06:01.316 D/|BR: run() - 3
09:06:14.139 D/|BR: onResume() a: QWER