使用DownloadManager从Activity将数据传递到BroadcastReceiver [英] Pass data to BroadcastReceiver from Activity using DownloadManager
问题描述
我正在尝试将对象传递给BroadcastReceiver,该对象将在下载完成后执行某些操作.如何从我的活动中访问BroadcastReceiver的onReceive方法中的Intent对象?现在,我在活动中有此提示:
I am trying to pass an object to a BroadcastReceiver which will do something when a download is finished. How do I access the Intent object in the BroadcastReceiver's onReceive method from my activity? Right now I have this in my activity:
DownloadManager manager = (DownloadManager) getSystemService(Context.DOWNLOAD_SERVICE);
long id = manager.enqueue(request);
并且我的BroadcastReceiver中有这个文件,它在下载完成后会执行以下操作:
and I have this in my BroadcastReceiver that does stuff when the download is complete:
DownloadManager mgr = (DownloadManager)context.getSystemService(Context.DOWNLOAD_SERVICE);
一切正常,下载完成后,我的BroadcastReceiver会执行我想要的操作.但是现在我想将一个对象从我的活动传递到BroadcastReceiver.通常,我只是创建一个Intent并将对象添加到Intent中.但是,我没有在代码中创建Intent,因为BroadcastReceiver使用Context.DOWNLOAD_SERVICE响应下载.
It all works fine, my BroadcastReceiver does what I want when the download completes. But now I want to pass an object from my activity to the BroadcastReceiver. Usually, I would just create an Intent and add the object to the Intent. But, I haven't created an Intent in my code because the BroadcastReceiver responds to the download using the Context.DOWNLOAD_SERVICE.
在我的BroadcastReceiver中,我想从onReceive()方法中的Intent对象获取数据:
In my BroadcastReceiver, I want to get data from the Intent object in the onReceive() method here:
@Override
public void onReceive(Context context, Intent intent)
{
intent.getParcelableExtra("object");
}
如何从活动中将数据传递到此Intent对象?我该如何访问?我尝试使用getIntent().putExtra("object", object)
,但是它似乎不同于BroadcastReceiver的onReceive方法中使用的Intent,因为我得到了nullPointerException
How do I pass data into this Intent object from my activity? How do I access it? I tried using getIntent().putExtra("object", object)
but it seems to be a different Intent than the one used in the BroadcastReceiver's onReceive method because I get a nullPointerException
这是我在AndroidManifest.xml中的相关代码
<receiver
android:name="com.android.devon.appfrenzy.DownloadReceiver"
android:exported="true" >
<intent-filter>
<action android:name="android.intent.action.DOWNLOAD_COMPLETE" />
</intent-filter>
</receiver>
推荐答案
在执行下载之前,将值保存在SharedPreference中
Before download is executed, save the value in SharedPreference
editor.putInt(MainActivity.CERIS_LAST_DW_ID_KATALOG, m_intIdKatalog);
editor.commit();
然后在onReceive中从共享首选项"中获取值
Then in onReceive get the value from Shared Preference
@Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
SharedPreferences mCeris;
mCeris = arg0.getSharedPreferences(MainActivity.CERIS_PREFERENCES,
Context.MODE_PRIVATE);
int m_intIdKatalog = mCeris.getInt(MainActivity.CERIS_LAST_DW_ID_KATALOG, 0);
}
这篇关于使用DownloadManager从Activity将数据传递到BroadcastReceiver的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!