参考:http://yangguangfu.iteye.com/blog/1063732
BroadcastReceiver的实现不难,其实就是三部曲:注册,接收,发送。
但有一点较疑惑的是:当我启动 BroadcastReceiver 应用(必须有界面)后,此时如果我没进行内存清理,则可以进行监听。但是,当我启动 BroadcastReceiver (没有界面)时或 清理内存后, 广播接收就没效。不知道是什么原因导致的。。。
以下是代码:
广播接收器:
package com.example.broadcastTest; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; /** * Created by britzlieg on 14-5-21. */ public class MyReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { Log.v("MyTab","-->onReceive"); if("13553969709".equals(this.getResultData())) this.setResultData(null); //如果电话是5556,则清空,不让他拨打 } }
主程序代码:
package com.example.broadcastTest; import android.app.Activity; import android.os.Bundle; public class MyActivity extends Activity { /** * Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
主布局代码:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Hello World, MyActivity" /> </LinearLayout>
AndroidMainfest.xml
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.broadcastTest" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="15"/> <application android:label="@string/app_name" android:icon="@drawable/ic_launcher"> <activity android:name="MyActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN"/> <category android:name="android.intent.category.LAUNCHER"/> </intent-filter> </activity> <receiver android:name=".MyReceiver"> <intent-filter android:priority="1000"> <!-- 优先级设为1000,最高 --> <action android:name="android.intent.action.NEW_OUTGOING_CALL"/> <action android:name="android.intent.action.BOOT_COMPLETED"/> </intent-filter> </receiver> </application> <uses-permission android:name="android.permission.PROCESS_OUTGOING_CALLS"/> <!-- 外界拨打权限 --> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/> <!-- 接收开机广播 --> </manifest>