Android BroadcastReceiver的基本用法
如下图所示,点击menu右面的broadcast会发送一条广播,广播接受者接受信息后,打印一些调试信息。
下面看代码:
布局文件layout/main.xml
<?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:id="@+id/text1" android:layout_width="fill_parent" android:layout_height="wrap_content" android:text="Your debug will appear here" /> </LinearLayout>
menu/main_menu.xml
<menu xmlns:android="http://schemas.android.com/apk/res/android"> <group android:id="@+id/menuGroup_Main"> <item android:id="@+id/menu_clear" android:title="clear" /> <item android:id="@+id/menu_send_broadcast" android:title="broadcast" /> </group> </menu>
MainActivity
package com.xiyang.android.broadcast; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.util.Log; import android.view.Menu; import android.view.MenuInflater; import android.view.MenuItem; import android.widget.TextView; public class MainActivity extends Activity { private static final String tag = "TestReceiver"; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } @Override public boolean onCreateOptionsMenu(Menu menu){ super.onCreateOptionsMenu(menu); MenuInflater inflater = getMenuInflater(); //from activity inflater.inflate(R.menu.main_menu, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item){ appendMenuItemText(item); if (item.getItemId() == R.id.menu_clear){ this.emptyText(); return true; } if (item.getItemId() == R.id.menu_send_broadcast){ this.testSendBroadcast(); return true; } return true; } private TextView getTextView(){ return (TextView)this.findViewById(R.id.text1); } private void appendMenuItemText(MenuItem menuItem){ String title = menuItem.getTitle().toString(); TextView tv = getTextView(); tv.setText(tv.getText() + "\n" + title); } private void emptyText(){ TextView tv = getTextView(); tv.setText(""); } private void testSendBroadcast() { //Print out what your running thread id is Utils.logThreadSignature(tag); //Create an intent with an action Intent broadcastIntent = new Intent("com.androidbook.intents.testbc"); //load up the intent with a message //you want to broadcast broadcastIntent.putExtra("message", "Hello world"); //send out the broadcast //there may be multiple receivers receiving it this.sendBroadcast(broadcastIntent); //Log a message after sending the broadcast //This message should appear first in the log file //before the log messages from the broadcast //because they all run on the same thread Log.d(tag,"after send broadcast from main menu"); } }
广播接收者
package com.xiyang.android.broadcast; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.util.Log; public class TestReceiver extends BroadcastReceiver { private static final String tag = "TestReceiver"; @Override public void onReceive(Context context, Intent intent) { Utils.logThreadSignature(tag); Log.d("TestReceiver", "intent=" + intent); String message = intent.getStringExtra("message"); Log.d(tag, message); } }
一个工具类
package com.xiyang.android.broadcast; import android.util.Log; public class Utils { public static long getThreadId() { Thread t = Thread.currentThread(); return t.getId(); } public static String getThreadSignature() { Thread t = Thread.currentThread(); long l = t.getId(); String name = t.getName(); long p = t.getPriority(); String gname = t.getThreadGroup().getName(); return (name + ":(id)" + l + ":(priority)" + p + ":(group)" + gname); } public static void logThreadSignature(String tag) { Log.d(tag, getThreadSignature()); } public static void sleepForInSecs(int secs) { try { Thread.sleep(secs * 1000); } catch(InterruptedException x) { throw new RuntimeException("interrupted",x); } } }
清单文件注册服务
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.xiyang.android.broadcast" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="10" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".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> <receiver android:name=".TestReceiver"> <intent-filter> <action android:name="com.androidbook.intents.testbc"/> </intent-filter> </receiver> </application> </manifest>
说明:
1、在另外一个应用中发送广播,本程序中的广播接收者也能后获取广播,触发接收事件。
2、在本应用中,创建两个广播接收者,当在MainActivity中发送广播时,两个接收程序都能进行处理。比如再创建一个TestReceiver2.java,发送一条广播时,如下图所示:
3、从以上的日志也可以看出,广播接收程序都是在主线程上执行。
4、广播接收程序必须在10s内执行完毕。