Application is being killed while on background - android

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!

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.

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

Related

How to keep CPU running while closing screen?

There is a time-consuming task (a Thread) in Fragment. It works fine. But, when I close the screen, I see the CPU not work so that the task cannot work fine.
I have use PowerManager in Activity, but not work Fragment too.
Also add <uses-permission android:name="android.permission.WAKE_LOCK" />
#Override
protected void onResume() {
super.onResume();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "CPUKeepRunning");
wakeLock.acquire();
}
#Override
protected void onDestroy() {
super.onDestroy();
if (wakeLock != null && wakeLock.isHeld()) {
wakeLock.release();
wakeLock = null;
}
}
I have saw the CPU
Run your code through a Service, if you're running it in an Activity it will stop once the activity goes in the background. Use Services instead.
http://developer.android.com/training/run-background-service/create-service.html
http://developer.android.com/guide/components/services.html

Correct pattern for BroadcastReceiver getting wakelock to start an Activity?

What's the right way to acquire a wakelock in a BroadcastReceiver, and hold it until an activity is started - this is what I have:
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
PowerManager pm = (PowerManager)
context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK,
"tag");
wl.acquire();
Intent intent = new Intent(context, MyActivity.class);
context.startActivity(intent);
}
}
public class MyActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PowerManager pm = (PowerManager)
context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(
PowerManager.PARTIAL_WAKE_LOCK,
"tag");
wl.release();
// I want to keep the screen on now.
getWindow().addFlags(WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
}
}
// The broadcastreceiver is fired via AlarmManager:
AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setExact(AlarmManager.RTC_WAKEUP, someTime, pendingIntent);
Additionally, what happens if the broadcast receiver gets fired simultaneously - I assume the wakelock manager is synchronized and this won't be a problem?
Thank you
Once a lock is acquired you have to keep this instance of lock and release exactly that instance once work is done. You can check source code of WakefulBroadcastReceiver.java to get better idea of how this can be implemented and used.
Additionally, it's not a very good idea to start activity from a broadcast receiver. Imagine you play a game and in the middle of a level your phone starts an activity. I don't think you will like it. You should rather post a notification that user can open activity later, when user wants it.

Check whether onPause state of activity is called due to screen lock

If my app is running and I press lock screen button, it will put the app in background.What is the method to check whether onPause() is called by screen lock?.Thanks in advance.
All you have to do is check if the screen is on or not.
#Override
protected void onPause() {
super.onPause();
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
boolean screenOn;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
screenOn = pm.isInteractive();
} else {
screenOn = pm.isScreenOn();
}
if (screenOn) {
// Screen is still on, so do your thing here
}
}
You Can Simply Know It By Using This Method
#Override
public void onPause() {
super.onPause(); // Always call the superclass method first
System.out.println("On Pause called");
}
For Keeping The Device Awake while lock screen. Documentation.
Ok in your case you would need Wake_Lock
To use a wake lock, the first step is to add the WAKE_LOCK permission to your application's manifest file:
<uses-permission android:name="android.permission.WAKE_LOCK" />
If your app includes a broadcast receiver that uses a service to do some work, you can manage your wake lock through a WakefulBroadcastReceiver, as described in Using a WakefulBroadcastReceiver. This is the preferred approach. If your app doesn't follow that pattern, here is how you set a wake lock directly:
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
Wakelock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"MyWakelockTag");
wakeLock.acquire();
To release the wake lock, call wakelock.release(). This releases your claim to the CPU. It's important to release a wake lock as soon as your app is finished using it to avoid draining the battery.
DO this after setting powermanager.
boolean screenOn;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT_WATCH) {
screenOn = powerManager.isInteractive();
} else {
screenOn = powerManager.isScreenOn();
}
if (screenOn) {
// Screen is still on, so do your thing here
}
You just want to know when onPause is called? You could override the super function and add logging to the function:
#Override
public void onPause() {
super.onPause();
System.out.println("On Pause called");
}

How to wake up Android Wear when it is in sleep mode?

When Android Wear goes to sleep mode (screen dimmed), some parts of my code are not executed. I use Timer in background service to trigger some actions, such as sending data from wear to mobile, but the data is not sent. It is sent when I tap the screen to wake it up.
I also try to use Timer trigger a notification with vibration when the screen is off, but it doesn't appear until I tap the screen.
In debug mode (either Bluetooth or USB), data sending and notification work fine.
I suspect this is because when Android Wear is in sleep mode, its CPU works at minimum level because the Timer is still running, but not for GoogleApiClient, IntentService, or Notification.
I have tried many ways to wake CPU up such as AlarmManager, PowerManager, Wakelock, but it did not work for Android Wear.
Anyone has encountered this problem? What is the solution?
I'm using PowerManger to wakeup my wearable device each time i receive message from handled device.
Do not forget to release PowerManager.WakeLock
public abstract class WatchFaceActivity extends Activity {
private PowerManager.WakeLock mWakeLock;
private Handler mWakeLockHandler;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_clock_watch_face);
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
mWakeLock = powerManager.newWakeLock((PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.FULL_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "MyWakelockTag");
mWakeLockHandler = new Handler();
IntentFilter messageFilter = new IntentFilter("message-forwarded-from-data-layer");
MessageReceiver messageReceiver = new MessageReceiver();
LocalBroadcastManager.getInstance(this).registerReceiver(messageReceiver, messageFilter);
}
public class MessageReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
if (!mWakeLock.isHeld()) {
mWakeLock.acquire();
}
mWakeLockHandler.removeCallbacksAndMessages(null);
mWakeLockHandler.postDelayed(mReleaseRunnable, 5000);
}
}
private Runnable mReleaseRunnable = new Runnable() {
#Override
public void run() {
mWakeLock.release();
}
};
#Override
protected void onDestroy() {
super.onDestroy();
mWakeLockHandler.removeCallbacksAndMessages(null);
mWakeLock.release();
}
}
And allow WAKE_UP permission in your Manifest.
<uses-permission android:name="android.permission.WAKE_LOCK" />
You should use AlarmManager along with WakefulBroadcastReceiver and startWakefulService(). See this working solution.
You may find answers for your further questions in chat history on that post here.This is the only solution worked for our app.
#SeaDog is successful in making http calls when device in deep sleep mode with this solution. Try it.

WakeLock not releasing and Screen isn't turning off

I've using alarm manager to call an activity and I'm using the wake locker class onRecive() to wake the phone and then calling WakeLocker.release() after the Activity is over but the screen still stays on...
Receive.class:
public class MyScheduledReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
WakeLocker.acquire(context);
Activity.class
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
WakeLocker.release();
finish();
}
I've put it in the onPause(), onStop() everywhere... the thing won't release and the screen won't turn off automatically after my app closes...
Make sure you request permission
<uses-permission android:name="android.permission.WAKE_LOCK" />
You are starting the wakelock in a broadcastreceiver and stopping it in an activity.
You are referencing 2 different instances of a wakelock. You should start the activity from the onreceive and in onresume acquire the wake lock, then still release in the onpause if that is where you want it to happen.
You should never start anything that is supposed to be around for awhile within a broadcastreceiver, because the receiver is destroyed as soon as possible.
Try this
PowerManager pm;
PowerManager.WakeLock wakeLock;
pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK,
"x2_wakelook");
wakeLock.acquire();
wakeLock.release();

Categories

Resources