转载请注明出处:http://blog.csdn.net/u011569040/article/details/45966779
一打开MainActivity就发送一个粘滞广播,它在空中等待接收;点击按钮,跳转到第二个Activity,在这个Activity里面注册了一个广播接收者,收到了粘滞广播,并打印出来。
需要注册权限:
<uses-permission android:name="android.permission.BROADCAST_STICKY"/>
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);
}
});
}
}
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);
}
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);
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.sxt.day07_07"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
android:minSdkVersion="8"
android:targetSdkVersion="18" />
<uses-permission android:name="android.permission.BROADCAST_STICKY"/>
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name="com.sxt.day07_07.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name="com.sxt.day07_07.SecondActivity"
android:label="@string/title_activity_second" >
</activity>
</application>
</manifest>