EDIT
You can find the answer to this question in the comments !
POST
In my app, I have timers to remind the user of some task he's supposed to do. When time is up, a notification is sent. When the user clicks on this notification, I would like my app to be put in foreground if it's not already the case. I insist on the
'app' because I have found many posts that show how to put an Activity
in foreground, which is not the case here.
Here is the code of the Broadcastreceiver that is called when I would like to send the notification and bring my app to foreground:
public class TimerBroadcast extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
int ID = 333;
final NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setSmallIcon(R.drawable.clock_alarm2);
builder.setContentTitle("Time is up");
builder.setContentText("SLIMS");
builder.setOnlyAlertOnce(false);
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
builder.setSound(uri);
builder.setVibrate(new long[] { 0, 200, 3000 });
ActivityManager activityManager = (ActivityManager) context.getSystemService(Activity.ACTIVITY_SERVICE);
// get the info from the currently running task
List<ActivityManager.RunningTaskInfo> taskInfo = activityManager.getRunningTasks(100);
for (int i = 0; i < taskInfo.size(); i++) {
String componentName = taskInfo.get(i).topActivity.getClassName();
if (componentName.contains("com.genohm.android")) {
Intent intentActivity = new Intent();
intentActivity.setComponent(taskInfo.get(i).topActivity);
intentActivity.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, intentActivity, PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(contentIntent);
}
}
final Notification notification = builder.build();
notification.flags |= Notification.FLAG_INSISTENT;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
NotificationManager mNM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
mNM.notify(ID, notification);
}
}
This code works perfectly. The problem is that I'm using the method getRunningTasks() whose use seems to be strongly discouraged by Google.
Such uses are not supported, and will likely break in the future.
But actually it's the only way I found so far. Does anyone know if some workaround exists for this kind of practice ?