当前位置: 动力学知识库 > 问答 > 编程问答 >

java - Android: Get current foreground activity every 10 seconds once user clicks button

问题描述:

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

网友答案:

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);
分享给朋友:
您可能感兴趣的文章:
随机阅读: