Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
522 views
in Technique[技术] by (71.8m points)

android - Pass data to BroadcastReceiver from Activity using DownloadManager

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);

and I have this in my BroadcastReceiver that does stuff when the download is complete:

DownloadManager mgr = (DownloadManager)context.getSystemService(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.

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");
}

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

Edit: here is my relevant code in 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>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Before download is executed, save the value in SharedPreference

editor.putInt(MainActivity.CERIS_LAST_DW_ID_KATALOG, m_intIdKatalog);
editor.commit();

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);   
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...