2
votes

I have an activity with an UDP socket on a port. If I press the Home button the activity goes in background, OnPause() and OnStop() methods are called. Now I want to resume my activity when I receive some UDP packet. Reading the other posts I understand I have to:

  1. declare the activity as android:launchMode="singleTask" (or singleInstance)
  2. Then, when I want to resume the activity:
Intent intent = new Intent(this.getApplicationContext(), myActivity.class);

intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_NEW_TASK);

startActivity(intent);

This solution does not work form me. The call to startActivity(intent) does not show my activity on foreground and onResume() is not called.

The following flags do the job but I don't want to clear the task and restart a new one.

intent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
1
your udp socket is in a service, right? - njzk2
The socket is in the service when the main activity is closed. When I create the main activity the socket is unbound in the service and the main activity binds it. - peregrinus

1 Answers

1
votes

In order to bring your own task to the foreground, you need to call startActivity() on a non-Activity Context, for example:

getApplicationContext().startActivity(intent);

Also, you don't need to use any special launch mode (singleTask or singleInstance) for this to work.

This is an Android bug that was fixed in Android 4.4. Since this question is from 2014, I will assume that OP was seeing this problem.

See How to resume Android Activity programmatically from background and the comment thread.