android中如何发送一个广播

长平狐 发布于 2013/12/25 17:20
阅读 7K+
收藏 0

1.首先要声明广播

private BroadcastReceiver mBroadcastReceiver = new BroadcastReceiver()
{
	@Override
	public void onReceive(Context context, Intent intent) //onReceive函数不能做耗时的事情,参考值:10s以内
	{
		Log.d("scott", "on receive action="+intent.getAction());
		String action = intent.getAction();
		if (action.equals("com.scott.sayhi"))
		{
			showDialog("on receive action="+intent.getAction());
		}
	}
};

2.其次要注册广播,有两种方式:xml注册和代码注册


xml注册:

<receiver android:name="com.scott.sayhi.MyBroadcastReceiver" >
<intent-filter>
<action android:name="com.scott.sayhi" />
</intent-filter>
</receiver>


代码注册:

IntentFilter filter = new IntentFilter();
filter.addAction("com.scott.sayhi");
MyActivity.this.registerReceiver(mBroadcastReceiver, filter);

上述2个步骤就可以了。


3.发送广播

Intent intent = new Intent();
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.setAction("com.scott.sayhi");
MyActivity.this.sendBroadcast(intent);

4.收听开机广播

intent-filter设置如下即可

<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<category android:name="android.intent.category.HOME" />
</intent-filter>



原文链接:http://blog.csdn.net/singwhatiwanna/article/details/9066513
加载中
返回顶部
顶部