1

我正在尝试创建一个应用程序来侦听下载并在听到它时执行操作。这里的关键是我希望应用程序即使在它被最小化时也能做到这一点(比如当用户从浏览器下载时)。以下代码似乎没有使接收器跳闸:

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

         BroadcastReceiver receiver = new BroadcastReceiver() {
                @Override
                public void onReceive(Context context, Intent intent) {
                    System.out.println("did download");

                    String action = intent.getAction();
                    if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
                        String downloadPath = intent.getStringExtra(DownloadManager.COLUMN_URI);
                        System.out.println(downloadPath);
                    }

                }
            };

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


    }



}

有谁知道怎么了?

4

2 回答 2

0

只需在清单中声明广播接收器。更多动态注册和静态注册的区别,请看BroadcastReceiver

于 2013-09-11T15:23:55.827 回答
0

你几乎在那里只是将你移动BroadcastReceiver到一个单独的文件。用收到的 String 做你想做的事downloadPath。在此示例中,我将其保存到SharedPreferences.

public class MyBroadcastReceiver extends BroadcastReceiver{
    @Override
    public void onReceive(final Context context, Intent intent) {

        SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = settings.edit();

        String action = intent.getAction();
        if (DownloadManager.ACTION_DOWNLOAD_COMPLETE.equals(action)) {
            String downloadPath = intent.getStringExtra(DownloadManager.COLUMN_URI);
            editor.putString("downloadPath", downloadPath);
            editor.commit();
        }
    }
}

在您的清单中添加并编辑action

<receiver android:name=".MyBroadcastReceiver " >
    <intent-filter>
        <action android:name="PUT YOUR ACTION HERE DownloadManager.ACTION_DOWNLOAD_COMPLETE" />
    </intent-filter>
</receiver>
于 2013-09-11T15:54:30.270 回答