Home > Mobile >  how my program stays awake all the time in the background in android studio
how my program stays awake all the time in the background in android studio

Time:03-28

I am developing a program that like caller id. I have to keep it always awake also runing background.

Which permissions or flags that i need?

Also how can i get permission battery optimizaion close for my app

Thanks

CodePudding user response:

for checking/disabling battery optimisation use below methods

public static boolean isBatteryOptimisationEnabled(Context context) {
    if (Build.VERSION.SDK_INT >= 23) {
        PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
        return pm != null && !pm.isIgnoringBatteryOptimizations(context.getPackageName());
    }
    return false;
}

@TargetApi(23)
private static void gotoBatteryOptimisationSettings(Context context) {
    Intent intent = new Intent();
    String packageName = context.getPackageName();
    PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
    if (pm == null || pm.isIgnoringBatteryOptimizations(packageName))
        intent.setAction(Settings.ACTION_IGNORE_BATTERY_OPTIMIZATION_SETTINGS);
    else {
        intent.setAction(Settings.ACTION_REQUEST_IGNORE_BATTERY_OPTIMIZATIONS);
        intent.setData(Uri.parse("package:"   packageName));
    }
    context.startActivity(intent);
}

and for keeping your app running whole the time you have to implement your logic in ForegroundService

CodePudding user response:

You never can keep alive background services for always. if you want to make sure services always keep running you should use foreground service.

BUT

for your specific usage, you should use broadcast receivers to observe user calls.see this

  • Related