How do I set a broadcast receiver

2020-08-07 10:57发布

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

3条回答
不美不萌又怎样
3楼-- · 2020-08-07 11:23

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>
查看更多
闹够了就滚
4楼-- · 2020-08-07 11:36

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));
查看更多
登录 后发表回答