How do I set a broadcast receiver

狂风中的少年 提交于 2019-12-13 12:24:04

问题


I want to set a broadcast receiver to run some function when it gets the broadcast message, in this example, I want to catch the download's manager intent:

DownloadManager.ACTION_DOWNLOAD_COMPLETE

I looked at the Android API examples and haven't found a way to do this


回答1:


You should read this first:

http://developer.android.com/reference/android/content/BroadcastReceiver.html

Then look here for examples.

Android Samples: http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/appwidget/ExampleBroadcastReceiver.html

Blog post: http://www.androidcompetencycenter.com/2009/01/basics-of-android-part-ii-intent-receivers/




回答2:


Try this:

BroadcastReceiver receiver = new BroadcastReceiver() {

  @Override
  public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    if (action.equals(DownloadManager.ACTION_DOWNLOAD_COMPLETE) ){
      // do something
    }
  }

 registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));



回答3:


You can create a class that inherits from BroadcastReceiver:

public class MyDownloadCompleteReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
    }
}

And then register this class in your application manifest like so:

    <receiver android:enabled="true" 
                android:name="MyDownloadCompleteReceiver"
                android:label="downloadCompleteReceiver">
        <intent-filter>
            <action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
        </intent-filter>
    </receiver>


来源:https://stackoverflow.com/questions/6121615/how-do-i-set-a-broadcast-receiver

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!