gpt4 book ai didi

android - onReceive 只工作一次android

转载 作者:塔克拉玛干 更新时间:2023-11-02 23:23:58 26 4
gpt4 key购买 nike

我正在使用此代码来检测屏幕何时被锁定并调用 toast,每次屏幕被锁定时它都会工作。但是,每当我离开应用程序时,它就会停止工作。它仅在应用程序打开时有效。

public class BatterySaverLiteReceiver extends BroadcastReceiver {

@Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) {
Log.i("Check", "Screen went OFF");
Toast.makeText(context, "screen OFF", Toast.LENGTH_LONG).show();

task(context);
} else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) {
Log.i("Check", "Screen went ON");
Toast.makeText(context, "screen ON", Toast.LENGTH_LONG).show();
}
}

private void task(Context context) {
// Process Killer and display all package names in toast
ActivityManager actvityManager = (ActivityManager) context
.getApplicationContext().getSystemService(
context.getApplicationContext().ACTIVITY_SERVICE);
List<RunningAppProcessInfo> procInfos = actvityManager
.getRunningAppProcesses();
for (int pnum = 0; pnum < procInfos.size(); pnum++) {
actvityManager
.killBackgroundProcesses(procInfos.get(pnum).processName);
}
}
}

这就是我注册接收器的方式

IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
mReceiver = new BatterySaverLiteReceiver();
registerReceiver(mReceiver, filter);

list

   <receiver android:name=".BatterySaverUltraReceiver" >
<intent-filter>
<action android:name="android.intent.action.SCREEN_OFF" />
<action android:name="android.intent.action.SCREEN_ON" />
</intent-filter>
</receiver>

我从 here 得到了这段代码

最佳答案

我认为您正在终止所有进程,包括您在 task() 方法中的进程。从 killBackgroundProcesses() 过滤掉后台服务的进程。

RunningAppProcessInfo 获取进程名称,并将其与您应用的进程名称进行比较。默认情况下,进程名称将等于包名称。

private void task(Context context) {
ActivityManager actvityManager = (ActivityManager) context
.getApplicationContext().getSystemService(
context.getApplicationContext().ACTIVITY_SERVICE);
List<ActivityManager.RunningAppProcessInfo> procInfos = actvityManager
.getRunningAppProcesses();
for (int pnum = 0; pnum < procInfos.size(); pnum++) {
ActivityManager.RunningAppProcessInfo info = procInfos.get(pnum);

if (info.pid != android.os.Process.myPid()) {
actvityManager.killBackgroundProcesses(info.processName);
}
}
}

关于android - onReceive 只工作一次android,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34548291/

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