Search code examples
androidbroadcastreceiveralarmmanager

Android. How to keep an application running after the system is going to kill it. Or how not to let the system to kill it


Android. How to keep an application running after the system is going to kill it?
Or how not to let the system to kill it?

I need to support the application in the foreground. That is, open the app every 30 seconds, regardless of whether it is minimized or closed.

While the application is running (it is displayed in the list of cached) method is called OnReceive. If the application is unloaded from memory, it no longer triggers Activity

use AlarmManager, BroadcastReceiver

Activity1.OnCreate

...
Intent intent = new Intent(this, typeof(MyAppReciever));
PendingIntent sender = PendingIntent.GetBroadcast(this, 0, intent,PendingIntentFlags.UpdateCurrent);
AlarmManager am = (AlarmManager)GetSystemService(AlarmService);
am.SetRepeating(AlarmType.ElapsedRealtimeWakeup, SystemClock.ElapsedRealtime()+30000,30000,sender);

BroadcastReceiver

[BroadcastReceiver]
[IntentFilter(new[] { Intent.ActionPowerConnected })]
public class MyAppReciever : BroadcastReceiver
{
    public override void OnReceive(Context context, Intent intent)
    {
        Intent intent1 = new Intent(context, typeof(Activity1));
        intent1.AddFlags(ActivityFlags.NewTask);
        context.StartActivity(intent1);
    }
}

manifest

    ....
    <uses-permission android:name="android.permission.WAKE_LOCK" />
  <receiver android:name="AndroidApplicationTest.MyAppReciever">
        <intent-filter>
                <action android:name="android.intent.action.POWER_CONNECTED" />
                <action android:name="android.intent.action.ACTION_POWER_CONNECTED" />
        </intent-filter>
  </receiver>

UPD #1

Let's simplify the example. For example , I want the application to be opened periodically ( shows the current Activity). Procedure is as follows: run the application by double clicking on the icon , then minimize by home-button. The application appears in the "working apps" (in the cache ) . Begin to actively use the phone , my application is gradually replaced and disappears from the "working apps" Say an hour after the first run , I want the application to reopen the (initial Activity). I hope that AlarmManager rise OnReceive event in which spelled Activity open the main application.

what am I doing wrong?


Solution

  • Problem with your Pending Intent. Use same action and category to match your Receiver intent filter to wake up your Receiver.