I've read from the Android documentation (Android newbie here), but generally a lot of articles and questions on how to get current foreground activities (eg. here, here, and here) and how to get commands running every X minutes/seconds (eg. here, here, here, and here), but I can't seem to manage to combine the two in between button clicks.
The purpose of this task is, once the user clicks a Start button, the current activity is displayed on screen, through a Toast
, every 10 seconds. Once the user clicks Stop, the Toast
s stop popping up.
I managed to get the current activity be displayed every 10 seconds by using the following code:
Calendar cal = Calendar.getInstance();
Intent i = new Intent(context, SimpleService.class);
PendingIntent pintent = PendingIntent.getService(this, 0, i, 0);
AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
// Start every 10 seconds
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 10*1000, pintent);
where SimpleService
is a Service
that contains the following code in its onStartCommand
Context context = getApplicationContext();
ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
// get the info from the currently running task
List< ActivityManager.RunningTaskInfo > taskInfo = am.getRunningTasks(1);
String curAct = taskInfo.get(0).topActivity.getPackageName();
Toast.makeText(context, curAct, Toast.LENGTH_LONG).show();
However, the moment I try to put my lovely 10-second runner in between onClick
functions, this line gives me an error under getService
:
PendingIntent pintent = PendingIntent.getService(this, 0, i, 0);
Saying The method getService(Context, int, Intent, int) in the type PendingIntent is not applicable to the arguments (new View.OnClickListener(){}, int, Intent, int)
.
I get the same thing if I try to put the ActivityManager
in Runnable
s and other methods, but they never work if the function is in the ClickListener
(always same error).
What should I do? How could I get the Toast
s to appear every 10 seconds with the current foreground activity after the user clicks the start, and stop it after the user clicks the stop?
Thank you