MainActivity如下:
package cc.com; import android.os.Bundle; import android.app.Activity; import android.content.Context; import android.content.Intent; /** * Demo描述: * 粘性广播(StickyBroadcast)使用示例 * 粘性广播也叫等待广播. * * 使用场景: * 发送一个粘性广播(StickyBroadcast),但是现在并没有一个广播接收者来接收该广播发出的数据. * 而是在某个时间后,才注册一个receiver,但是也能收到之前StickyBroadcast发出的广播. * 这点就和平常用的普通广播很不一样了. * * 在该示例中: * 1 发出一个粘性广播(StickyBroadcast) * 2 5秒后再启动一个Activity * 3 在新启动的Activity中注册receiver接收StickyBroadcast发出的数据 * * 参考资料: * 1 http://blog.csdn.net/lamp_zy/article/details/9324979 * 2 http://blog.csdn.net/woaieillen/article/details/7376391 * * 注意权限: * <uses-permission android:name="android.permission.BROADCAST_STICKY"/> */ public class MainActivity extends Activity { private Context mContext; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); mContext=this; sendStickyBroadcastTest(); startAnotherActivity(); } //发送粘性广播 private void sendStickyBroadcastTest() { Intent intent=new Intent(); intent.setAction("cc.vv"); intent.putExtra("time", String.valueOf(System.currentTimeMillis())); sendStickyBroadcast(intent); } // 启动其他Activity private void startAnotherActivity() { new Thread() { public void run() { try { Thread.sleep(1000*5); Intent intent=new Intent(mContext, AnotherActivity.class); mContext.startActivity(intent); } catch (Exception e) { // TODO: handle exception } } }.start(); } }
AnotherActivity如下:
package cc.com; import android.os.Bundle; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; public class AnotherActivity extends Activity { private BroadcastReceiver mBroadcastReceiver=null; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.another); registBroadcastReceiver(); } //注册广播接收者 private void registBroadcastReceiver(){ mBroadcastReceiver=new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { System.out.println("收到了StickyBroadcast发出的数据"); String time=intent.getStringExtra("time"); System.out.println("发送广播的时间:"+time); System.out.println("当前的时间:"+System.currentTimeMillis()); } }; IntentFilter intentFilter=new IntentFilter(); intentFilter.addAction("cc.vv"); registerReceiver(mBroadcastReceiver, intentFilter); } @Override protected void onDestroy() { super.onDestroy(); if (mBroadcastReceiver!=null) { unregisterReceiver(mBroadcastReceiver); } } }
PS:两个界面布局简单得令人发指,所以不再贴出。
PPS:在电量变化的时候系统也会发出sticky广播;参考资料:http://blog.csdn.net/jaysong2012/article/details/45601001
时间: 2024-10-25 11:08:24