1

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 Toasts 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 Runnables 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 Toasts 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

Community
  • 1
  • 1
SaiyanGirl
  • 16,376
  • 11
  • 41
  • 57

1 Answers1

1

Instead of using this in

PendingIntent.getService(this, 0, i, 0);

create a private member of your activity for context like this:

private Context myContext;

in onCreate instantiate it with:

myContext= getApplicationContext();

and then use this context in getService:

PendingIntent.getService(myContext, 0, i, 0);
gile
  • 368
  • 1
  • 7
  • 1
    Great! The reason is that reference to this is out of scope in new View.OnClickListener, so you need to remember it as a private member to the class – gile Jan 08 '14 at 08:25