我正在尝试创建一个监听下载并在听到后执行操作的应用程序。这里的关键是我希望应用程序即使在最小化时也是如此(例如当用户从浏览器下载时)。以下代码似乎没有绊倒接收器:
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));
}
}
任何人都知道什么是错的?
答案 0 :(得分:0)
只需在清单中声明广播接收器即可。有关动态寄存器和静态寄存器之间差异的更多信息,请参阅BroadcastReceiver
答案 1 :(得分:0)
您几乎只需将BroadcastReceiver
移至单独的文件即可。使用收到的字符串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>