Luke Villanueva
Luke Villanueva

Reputation: 2070

Application is being killed while on background

My application sends gps updates to a API. I need my application to run in background all the time. But unfortunately, my application always end at some point while on background. I have read that when the cpu usage of the application is low, the application is will be killed automatically. I don't want this to happen. I already included a partial wake lock on my onCreate method in my application using this code:

 powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
 wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");

Then on pause:

protected void onPause()
 {
     super.onPause();
     onBackground = true;
     wakeLock.acquire();
     Log.w("OnPause", "OnPause");
 }

I really don't know how to prevent my application being killed. I also tried using full wake lock but it is deprecated. Any ideas on how will I keep my application alive on background? I never want my application to be killed while on background. Thanks!

Upvotes: 0

Views: 1305

Answers (2)

dipali
dipali

Reputation: 11188

public class BGService extends Service {

    private PowerManager powerManager;
    private WakeLock wakeLock;

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();

        powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
                "MyWakeLock");
        wakeLock.acquire();
    }

call and start service in your main activity

public class SendSMSActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.demo);
        startService(new Intent(this, BGService.class));
    }

}

Upvotes: 0

flx
flx

Reputation: 14226

You can not.

Just make sure, you persist anything that should survive after being killed.

For anything that should run in background, even if the app is not shown to the user:
Use a Service and set it into foreground mode.

Upvotes: 3

Related Questions