繁体   English   中英

Android:用户单击按钮后,每10秒钟获取一次当前的前台活动

[英]Android: Get current foreground activity every 10 seconds once user clicks button

我已经阅读了Android文档(此处为Android新手),但通常会有很多文章和问题,涉及如何获取当前的前台活动(例如hereherehere )以及如何获取每X分钟/秒运行的命令(例如, 此处此处此处此处 ),但是我似乎无法设法在两次按钮单击之间将两者结合起来。

该任务的目的是,一旦用户单击“ 开始”按钮,就会每隔10秒通过Toast将当前活动显示在屏幕上。 用户单击“ 停止”后 ,将弹出Toast停止。

我设法通过使用以下代码使当前活动每10秒显示一次:

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);

其中, SimpleService是一个Service ,其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(); 

但是,当我尝试在onClick函数之间放置可爱的10秒跑步程序时,此行在getService下给我一个错误:

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

The method getService(Context, int, Intent, int) in the type PendingIntent is not applicable to the arguments (new View.OnClickListener(){}, int, Intent, int)

如果尝试将ActivityManager放入Runnable和其他方法中,则会得到相同的结果,但是如果该函数位于ClickListener ,它们将永远无法工作(总是相同的错误)。

我该怎么办? 在用户单击开始之后,如何才能使Toast在当前前台活动中每10秒出现一次,而在用户单击停止时又停止它?

谢谢

而不是在

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

为活动创建私人成员,例如:

private Context myContext;

在onCreate实例化它:

myContext= getApplicationContext();

然后在getService中使用以下上下文:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM