广播作为android的四大组件之一,适用的地方还是很多,多用来特定条件情况下的通知。例如,开机,闹铃,电池电量过低等等。但还可以自定义广播,用来两个应用程序的通知。
曾经写的开机自启动的博客(通过接受系统广播):Android 开机自启动示例程序
这篇博客源码下载:点击
1、实现界面
2、发送广播的应用程序代码
broadcastsend这个apk的代码很简单,有个按钮点击触发。发送广播就行了。
package com.example.broadcastsend; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.app.Activity; import android.content.Intent; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); findViewById(R.id.button1).setOnClickListener(new OnClickListener() { @Override public void onClick(View v) { //发送广播 String broadcastIntent = "com.customs.broadcast";//自己自定义 Intent intent = new Intent(broadcastIntent); MainActivity.this.sendBroadcast(intent); } }); } }这个发送的程序当中,在AndroidManifest.xml里面不用添加什么。
3、接受广播的应用程序代码
broadcastreceiver这个apk里面的代码,肯定要重写广播接受的类,就是继承BroadcastReceiver,重写onReceive这个方法就行了。
package com.example.broadcastreceiver; import android.app.AlertDialog; import android.content.BroadcastReceiver; import android.content.Context; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.view.WindowManager; public class CustomBroadReceiver extends BroadcastReceiver{ private static final String ACTION = "com.customs.broadcast"; @Override public void onReceive(Context context, Intent intent) { //广播接受 if (intent.getAction().equals(ACTION)){ AlertDialog.Builder builder = new AlertDialog.Builder(context); builder.setTitle("提示") .setMessage("收到BroadcastSend应用程序的广播") .setPositiveButton("确定", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }) .setNegativeButton("取消", new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { } }); AlertDialog dialog = (AlertDialog) builder.create(); dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT); dialog.show(); } } }
然后在AndroidManifest.xml里面添加注册
<!-- 广播接收 --> <receiver android:name="com.example.broadcastreceiver.CustomBroadReceiver"> <intent-filter> <action android:name="com.customs.broadcast" /> </intent-filter> </receiver>
到这里基本就结束了,是不是很简单。跨应用程序的广播接受。
4、注意事项
有没有注意到,我在广播接受里面,写了一个弹出对话框。这个有点特殊,一般是弹不出来对话框。是通过hander传递到具体界面显示的或者其它消息通知。
但我这里可以实现直接弹出对话框提示。因为我添加了两样东西。
a、对话框设置
dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);b、AndroidManifest.xml里面添加权限
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
曾经写的开机自启动的博客(通过接受系统广播):Android 开机自启动示例程序
这篇博客源码下载:点击