I have onUpdate(…) metod of MyAppWidgetProvider class with the code:
...
Intent launchAppIntent = new Intent(context, SearchActivity.class);
PendingIntent launchAppPendingIntent = PendingIntent.getActivity(context, 0, launchAppIntent, 0);
remoteView.setOnClickPendingIntent(R.id.logo, launchAppPendingIntent);
...
It works fine. New SearchActivity starts by clicking on widget. Now, I want to start on click not the SearchActivity, but an activity from the top of the stack of my task. For this purpose I change above code to:
ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(30);
for (ActivityManager.RunningTaskInfo task:tasks) {
if (task.baseActivity.getShortClassName().equals(".MainActivity")) {
try {
Intent launchAppIntent = new Intent(context, Class.forName(task.topActivity.getClassName()));
PendingIntent launchAppPendingIntent = PendingIntent.getActivity(context, 0, launchAppIntent, 0);
remoteView.setOnClickPendingIntent(R.id.logo, launchAppPendingIntent);
} catch (ClassNotFoundException ex) {
Logger.getLogger(CashWidgetProvider.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
that doesn’t work. Foreground activity in task stack doesn’t appear on monitor. Moreover, I don’t get any messages in log running this code.
However, the same code works fine being placed in some method of the class, inherited from Activity.
ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(30);
for (ActivityManager.RunningTaskInfo task:tasks) {
System.out.println(task.baseActivity.getShortClassName());
if (task.baseActivity.getShortClassName().equals(".MainActivity")) {
try {
Intent launchAppIntent = new Intent(this, Class.forName(task.topActivity.getClassName()));
startActivity(launchAppIntent);
} catch (ClassNotFoundException ex) {
Logger.getLogger(AbstractActivity.class.getName()).log(Level.SEVERE, null, ex);
}
}
}
How can I get it working for AppWidget!?
The problem appears due to misunderstanding of widget lifecycle, as usual… To get it working I have to create MyService class inherited from Service overriding onStart method with code:
and call above MyService from AppWidgetProvider class by means of the code:
Don’t forget to add this new service in AndroidManifest.xml under section
P.S. Probably, it would be better to use BroadcastReceiver instead of Service.