粘滞广播:广播发送出去以后,广播接收者还没有创建,当广播接收者注册的时候就可以接收,如果不是粘滞广播则如果没有广播接收者就以后不能再接收了。
mainActivity:
package com.sxt.day07_07;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.View.OnClickListener;public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent=new Intent("com.sxt.day07_07.my_receiver"); sendStickyBroadcast(intent);//发送粘滞广播,一直停留等着接收者 setListener(); } private void setListener() { findViewById(R.id.btnStartSecondActivity).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { Intent intent2=new Intent(MainActivity.this, SecondActivity.class); startActivity(intent2);//启动SecondActivity } }); }}
SecondActivity
package com.sxt.day07_07;import android.os.Bundle;import android.app.Activity;import android.content.BroadcastReceiver;import android.content.Context;import android.content.Intent;import android.content.IntentFilter;import android.util.Log;import android.view.Menu;public class SecondActivity extends Activity { MyReceiver mReceiver; Intent mIntent; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_second); registerReceiver(); } private void registerReceiver() { mReceiver=new MyReceiver(); IntentFilter filter=new IntentFilter("com.sxt.day07_07.my_receiver"); registerReceiver(mReceiver, filter); } //内部类,只有SecondActivity启动了,MyReceiver才能注册接收广播。 class MyReceiver extends BroadcastReceiver{ @Override public void onReceive(Context context, Intent intent) { Log.i("main","MyReceiver.onReceive()"); mIntent=intent; } } @Override protected void onDestroy() { super.onDestroy(); removeStickyBroadcast(mIntent);//移出,移出以后就收不到广播了 unregisterReceiver(mReceiver);//移出接收者 }}
系统描述文件:
粘滞广播要申请权限
main页面:
second页面: