Android Question Backgroud services killed on some devices

FrankBerra

Active Member
Licensed User
Longtime User
Hello everyone!
I noticed that the services of my app get killed if the app is running in backgroud.
Problem happens on huawei phones but after searching online i found that the problem can happen also on other manufacturers.
So i found this thread: https://stackoverflow.com/questions...setting-on-huawei-phones-and-how-to-handle-it

my problem is that i am not skilled in Java and i need some help to port to B4A with In-Line Java. (I copied it to B4A but i get some errors during compilation:
B4X:
error: package android.support.v7.widget does not exist
import android.support.v7.widget.AppCompatCheckBox;
                                ^
Note: Some input files use or override a deprecated API.
Note: Recompile with -Xlint:deprecation for details.
Note: Some input files use unchecked or unsafe operations.
Note: Recompile with -Xlint:unchecked for details.
1 error

So my question is: is there someone that can make following code working in B4A? Thank you in advance!

B4X:
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.os.Build;
import android.support.v7.widget.AppCompatCheckBox;
import android.widget.CompoundButton;
import java.util.List;

public class Utils {

public static void startPowerSaverIntent(Context context) {
   SharedPreferences settings = context.getSharedPreferences("ProtectedApps", Context.MODE_PRIVATE);
   boolean skipMessage = settings.getBoolean("skipProtectedAppCheck", false);
   if (!skipMessage) {
       final SharedPreferences.Editor editor = settings.edit();
       boolean foundCorrectIntent = false;
       for (Intent intent : Constants.POWERMANAGER_INTENTS) {
           if (isCallable(context, intent)) {
               foundCorrectIntent = true;
               final AppCompatCheckBox dontShowAgain = new AppCompatCheckBox(context);
               dontShowAgain.setText("Do not show again");
               dontShowAgain.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                   @Override
                   public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                       editor.putBoolean("skipProtectedAppCheck", isChecked);
                       editor.apply();
                   }
               });

               new AlertDialog.Builder(context)
                       .setTitle(Build.MANUFACTURER + " Protected Apps")
                       .setMessage(String.format("%s requires to be enabled in 'Protected Apps' to function properly.%n", context.getString(R.string.app_name)))
                       .setView(dontShowAgain)
                       .setPositiveButton("Go to settings", new DialogInterface.OnClickListener() {
                           public void onClick(DialogInterface dialog, int which) {
                               context.startActivity(intent);
                           }
                       })
                       .setNegativeButton(android.R.string.cancel, null)
                       .show();
               break;
           }
       }
       if (!foundCorrectIntent) {
           editor.putBoolean("skipProtectedAppCheck", true);
           editor.apply();
       }
   }
}

private static boolean isCallable(Context context, Intent intent) {
   List<ResolveInfo> list = context.getPackageManager().queryIntentActivities(intent,
           PackageManager.MATCH_DEFAULT_ONLY);
   return list.size() > 0;
}
}



import android.content.ComponentName;
import android.content.Intent;
import java.util.Arrays;
import java.util.List;

public class Constants {

public static List<Intent> POWERMANAGER_INTENTS = Arrays.asList(
       new Intent().setComponent(new ComponentName("com.miui.securitycenter", "com.miui.permcenter.autostart.AutoStartManagementActivity")),
       new Intent().setComponent(new ComponentName("com.letv.android.letvsafe", "com.letv.android.letvsafe.AutobootManageActivity")),
       new Intent().setComponent(new ComponentName("com.huawei.systemmanager", "com.huawei.systemmanager.optimize.process.ProtectActivity")),
       new Intent().setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.permission.startup.StartupAppListActivity")),
       new Intent().setComponent(new ComponentName("com.coloros.safecenter", "com.coloros.safecenter.startupapp.StartupAppListActivity")),
       new Intent().setComponent(new ComponentName("com.oppo.safe", "com.oppo.safe.permission.startup.StartupAppListActivity")),
       new Intent().setComponent(new ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.AddWhiteListActivity")),
       new Intent().setComponent(new ComponentName("com.iqoo.secure", "com.iqoo.secure.ui.phoneoptimize.BgStartUpManager")),
       new Intent().setComponent(new ComponentName("com.vivo.permissionmanager", "com.vivo.permissionmanager.activity.BgStartUpManagerActivity")),
       new Intent().setComponent(new ComponentName("com.asus.mobilemanager", "com.asus.mobilemanager.entry.FunctionActivity")).setData(android.net.Uri.parse("mobilemanager://function/entry/AutoStart"))
);
}
 

DonManfred

Expert
Licensed User
Longtime User
try this example. Don´t know if it works.
It does not show any dialog or so. It just do the test and return the intent if found...
 

Attachments

  • PowerSaverHelperV0.01.zip
    2.8 KB · Views: 201
  • PowerSaverEx.zip
    7.3 KB · Views: 225
Upvote 0

FrankBerra

Active Member
Licensed User
Longtime User
...your example crashes with the following error:

B4X:
main_activity_create (java line: 348)
java.lang.RuntimeException: Object should first be initialized (Intent).
    at anywheresoftware.b4a.AbsObjectWrapper.getObject(AbsObjectWrapper.java:50)
    at anywheresoftware.b4a.objects.IntentWrapper.getAction(IntentWrapper.java:56)
    at b4a.example.main._activity_create(main.java:348)
    at java.lang.reflect.Method.invoke(Native Method)
    at anywheresoftware.b4a.BA.raiseEvent2(BA.java:191)
    at b4a.example.main.afterFirstLayout(main.java:104)
    at b4a.example.main.access$000(main.java:17)
    at b4a.example.main$WaitForLayout.run(main.java:82)
    at android.os.Handler.handleCallback(Handler.java:789)
    at android.os.Handler.dispatchMessage(Handler.java:98)
    at android.os.Looper.loop(Looper.java:164)
    at android.app.ActivityThread.main(ActivityThread.java:6798)
    at java.lang.reflect.Method.invoke(Native Method)
    at com.android.internal.os.Zygote$MethodAndArgsCaller.run(Zygote.java:240)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:767)
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
so the initialisation returns null? In this case it could not find any Intent

Try change the code to
B4X:
    Dim in As Intent = psh.Initialize("")
    If in <> Null And in.IsInitialized Then
        Log("The Intent is: "&in.Action)
    Else
        Log("No Intent found")
    End If
Does it log "No Intent found" now?
 
Last edited:
Upvote 0

FrankBerra

Active Member
Licensed User
Longtime User
so the initialisation returns null? In this case it could not find any Intent

Try change the code to
B4X:
    Dim in As Intent = psh.Initialize("")
    If in <> Null And in.IsInitialized Then
        Log("The Intent is: "&in.Action)
    Else
        Log("No Intent found")
    End If
Does it log "No Intent found" now?

Now doesn't show any error, thank you!

Now if intent is foud i want to open OS settings to disable OS battery saver for my app. This is what i am doing:
B4X:
Sub EnergySaver_Click
    Dim In As Intent = psh.Initialize("")

    If (In.IsInitialized) And (In <> Null) Then
        StartActivity(In.Action)
    Else
        ToastMessageShow("No intent found"), True)
    End If
End Sub

On a Huawei phone the toastmessage isn't displayed but also no settings page are opened. How can i open OS settings when i click on the button?
Thanks in advance!
 
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
On a Huawei phone the toastmessage isn't displayed but also no settings page are opened
in.Action was only used to check in the logs...

Try it with
B4X:
Sub EnergySaver_Click
    Dim In As Intent = psh.Initialize("")

    If (In.IsInitialized) And (In <> Null) Then
        StartActivity(In)
    Else
        ToastMessageShow("No intent found"), True)
    End If
End Sub
 
Upvote 0

FrankBerra

Active Member
Licensed User
Longtime User
in.Action was only used to check in the logs...

Try it with
B4X:
Sub EnergySaver_Click
    Dim In As Intent = psh.Initialize("")

    If (In.IsInitialized) And (In <> Null) Then
        StartActivity(In)
    Else
        ToastMessageShow("No intent found"), True)
    End If
End Sub

Now it works!...but it opens the wrong settings. (On a huawei phone of a friend opens "Close apps on lock screen", without any option to change)
I think your library can be useful for other people so i suggest you to keep it developing.
In my opinion you should add an option to set the list of powermanager_intents programmatically so in that way a programmer can add it's own intent to adapt also to new future devices/operating systems

For example here there are more intents listed: https://stackoverflow.com/a/48641229

Thanks for your help with this trouble!
 
Last edited:
Upvote 0

DonManfred

Expert
Licensed User
Longtime User
try to use in buttonclick
B4X:
    Dim in As Intent
    in.Initialize(in.ACTION_EDIT,"")
    in.SetComponent("com.huawei.systemmanager.optimize.process.ProtectActivity")
    StartActivity(in)

or

B4X:
    Dim in As Intent
    in.Initialize(in.ACTION_VIEW,"")
    in.SetComponent("com.huawei.systemmanager.optimize.process.ProtectActivity")
    StartActivity(in)

PD: Needs b4a 8.8+
 
Upvote 0

FrankBerra

Active Member
Licensed User
Longtime User
try to use in buttonclick
B4X:
    Dim in As Intent
    in.Initialize(in.ACTION_EDIT,"")
    in.SetComponent("com.huawei.systemmanager.optimize.process.ProtectActivity")
    StartActivity(in)

or

B4X:
    Dim in As Intent
    in.Initialize(in.ACTION_VIEW,"")
    in.SetComponent("com.huawei.systemmanager.optimize.process.ProtectActivity")
    StartActivity(in)

PD: Needs b4a 8.8+
Ok i will wait for update of B4A, anyway how can i check if intent is present? (For example i want to show an alert window only on devices that supports that intents)
 
Upvote 0
Top