gpt4 book ai didi

java - Android:一旦用户点击按钮,每 10 秒获取当前的前台 Activity

转载 作者:行者123 更新时间:2023-11-30 03:11:04 24 4
gpt4 key购买 nike

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

此任务的目的是,一旦用户单击开始 按钮,当前 Activity 就会通过 Toast 每 10 秒显示在屏幕上。一旦用户单击停止Toast 就会停止弹出。

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

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

但是,当我尝试将我可爱的 ​​10 秒运行者放在 onClick 函数之间时,这行代码在 getService 下给我一个错误:

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

PendingIntent 类型中的方法 getService(Context, int, Intent, int) 不适用于参数 (new View.OnClickListener(){}, int, Intent, int)

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

我该怎么办?我怎样才能让 Toast 在用户单击开始后与当前的前台 Activity 每 10 秒出现一次,并在用户单击停止后停止?

谢谢

最佳答案

而不是在

中使用它
PendingIntent.getService(this, 0, i, 0);

为这样的上下文创建您的 Activity 的私有(private)成员:

private Context myContext;

在 onCreate 中实例化它:

myContext= getApplicationContext();

然后在 getService 中使用这个上下文:

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

关于java - Android:一旦用户点击按钮,每 10 秒获取当前的前台 Activity ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20970309/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com