简体   繁体   English

onReceive只能运行一次android

[英]onReceive works only once android

I am using this code to detect when the screen gets locked and call a toast, it works every time the screen gets locked. 我正在使用此代码来检测屏幕何时被锁定并调用烤面包,每次屏幕锁定时它都能正常工作。 However, whenever i go out of the app, it stops working. 但是,每当我退出应用程序时,它就会停止工作。 it only works if the app is open. 它只适用于应用程序打开的情况。

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

thats how im registering my receiver 多数民众赞成如何注册我的接收器

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

manifest 表现

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

i got this code from here 我从这里得到了这个代码

I think you are killing all the processes including your process in task() method. 我认为你正在杀死所有进程,包括你在task()方法中的进程。 Filter out your background service's process from killBackgroundProcesses() . killBackgroundProcesses()过滤掉后台服务的进程。

Get the process name from RunningAppProcessInfo and compare it with your apps's process name. RunningAppProcessInfo获取进程名称,并将其与应用程序的进程名称进行比较。 By default, process name will be equal to package name. 默认情况下,进程名称将等于包名称。

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

I found a more efficient and reliable solution, i registered a notificationmanager which works every 5 seconds and calls the method in my main activity! 我找到了一个更有效,更可靠的解决方案,我注册了一个通知管理器,每5秒工作一次,并在我的主要活动中调用该方法!

MainActivity.java MainActivity.java

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // ENABLE MyReceiver SERVICE
        ComponentName receiver = new ComponentName(MainActivity.this,
                NotifyService.class);
        PackageManager pm = this.getPackageManager();
        pm.setComponentEnabledSetting(receiver,
                PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
        // Toast.makeText(this, "Enabled broadcast receiver",
        // Toast.LENGTH_SHORT)
        // .show();
        // --//

        Intent intent = new Intent(this, NotifyService.class);
        PendingIntent sender = PendingIntent.getBroadcast(this, 0, intent,
                PendingIntent.FLAG_CANCEL_CURRENT);

        AlarmManager am = (AlarmManager) this
                .getSystemService(Context.ALARM_SERVICE);
        long recurring = (1 * 1000 * 5); // in milliseconds
        am.setRepeating(AlarmManager.RTC, Calendar.getInstance()
                .getTimeInMillis(), recurring, sender);
    }

    public static void mehtodName(Context context) {
        KeyguardManager myKM = (KeyguardManager) context.getSystemService(Context.KEYGUARD_SERVICE);
           if( myKM.inKeyguardRestrictedInputMode() ) {
                // it is locked
               task(context);
           } else {
                //it is not locked
           }
    }

     private static 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);
            }
        }
    }

NotifyService.java NotifyService.java

public class NotifyService extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        MainActivity.mehtodName(context);
        // ... do what you need to do here...
    }

}

My Manifest 我的清单

 <receiver android:name="com.example.notifypro.NotifyService" >
 </receiver>

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

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