我如何在android中使用broadcastreceiver

时间:2010-08-06 11:31:47

标签: android android-emulator

我如何在android中使用broadcastreceiver,

请举例说明或参考。谢谢

1 个答案:

答案 0 :(得分:2)

看看这个:

  1. http://developer.android.com/reference/android/content/BroadcastReceiver.html
  2. http://developer.android.com/guide/topics/manifest/receiver-element.html
  3. 在AndroidManifest.xml文件中写下以下代码:

    <receiver android:name=".appwidget.ExampleBroadcastReceiver" android:enabled="false">
       <intent-filter>
          <action android:name="android.intent.ACTION_TIMEZONE_CHANGED" />
          <action android:name="android.intent.ACTION_TIME" />
       </intent-filter>
    </receiver>
    

    并按如下方式定义类:

    public class ExampleBroadcastReceiver extends BroadcastReceiver {
    
        @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("ExmampleBroadcastReceiver", "intent=" + intent);
    
            // For our example, we'll also update all of the widgets when the timezone
            // changes, or the user or network sets the time.
            String action = intent.getAction();
            if (action.equals(Intent.ACTION_TIMEZONE_CHANGED)
                    || action.equals(Intent.ACTION_TIME_CHANGED)) {
                AppWidgetManager gm = AppWidgetManager.getInstance(context);
                ArrayList<Integer> appWidgetIds = new ArrayList<Integer>();
                ArrayList<String> texts = new ArrayList<String>();
    
                ExampleAppWidgetConfigure.loadAllTitlePrefs(context, appWidgetIds, texts);
    
                final int N = appWidgetIds.size();
                for (int i=0; i<N; i++) {
                    ExampleAppWidgetProvider.updateAppWidget(context, 
                           gm, appWidgetIds.get(i), texts.get(i));
                }
            }
        }
    
    }
    

    并有一个WifiDemo示例, click Here