How to implement asynchronous HTTP mail request in android?
I want to implement the following simple pattern in my android application:
- Activity A starts activity B
- In activity B, the user fills out a simple form F, then submits
- Activity B then starts AsyncTask C, which sends F to the url and returns immediately to Activity A
- In activity A, the user continues to work as usual, while C continues to work. But as soon as C is completed, the user should be notified, in particular if the result was unsuccessful.
I have a problem with steps 3 and 4. Since C starts with B, how can I get A's notification? Hmm, not sure if this is clear to everyone except me ...
Anyway, right now I am stuck with a solution where step 3 looks like this:
3. Activity B returns the contents of the form to activity A. Then AsyncTask C is triggered to publish the form and continue as usual.
But it just seems like there is no need for A to also need to process the form, that should just be the responsibility of B. Any other ideas or solutions out there?
source to share
Why don't you B get the information it needs to complete the task and then pass it back to A? OnPreExecute () and onPostExecute () happen on the main thread of Activity A.
Nothing, I just saw it in your description. But yes - B handles the whole thing - just passes the data in the URL.
source to share
I would use a broadcast receiver. http://d.android.com/reference/android/content/BroadcastReceiver.html
In action B
Intent broadcastIntent = new Intent("com.yourapppackage.BROADCAST");
broadcastIntent.putExtra("myExtras", myExtras.extra); // Put your results in here
sendBroadcast(broadcastIntent);
Fire it out of your AsyncTask's onPostExecute.
In your app manifest, add an activity filter to your activity. Entry http://developer.android.com/guide/topics/manifest/intent-filter-element.html
<activity android:name=".A"
>
<intent-filter>
<action android:name="com.yourapppackage.BROADCAST" />
</intent-filter>
</activity>
Register BroadcastReceiver in Activity A http://developer.android.com/reference/android/content/BroadcastReceiver.html
// Set up a handler and a broadcast reciever
private final Handler mHandler = new Handler();
private final BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// Handle reciever
String mAction = intent.getAction();
if(mAction.equals("com.yourapppackage.BROADCAST")) {
// Do something with the results - intent.getExtras();
}
}
}
// Register a reciever
IntentFilter myRecieverIntentFilter = new IntentFilter();
myRecieverIntentFilter.addAction("com.yourapppackage.BROADCAST");
this.registerReceiver(mIntentReceiver, myRecieverIntentFilter, null, mHandler);
source to share