ANDROID : Reboot android device when my service killed/crashed - android

I have seen the default behaviour of many services, that they are restarted when killed by system or user.
Is it possible that if my service is killed or crashed the android device is rebooted instead of my service itself being restarted.
If so, then have android provided some mechanism that we can use to achieve the above.

First of all, it is really very bad pattern to reboot device on service destroy.
Anyways, you can achieve this using below code
public class demoService extends Service
{
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e(TAG, "onStartCommand");
}
#Override
public void onDestroy() {
super.onDestroy();
// this won't restart your phone instead it will ask for action
Intent i = new Intent("android.intent.action.ACTION_REQUEST_SHUTDOWN");
i.putExtra("android.intent.extra.KEY_CONFIRM", true);
startActivity(i);
}
}

Related

Reasons why a service could be stopped in android

If I have an app that does not have any activities, just one BOOT_COMPLETED broadcast receiver and the simplest service. The receiver will just start the service and the service will just ran the following code:
public class ScreenStateService extends Service {
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_STICKY;
}
#Override
public void onCreate() {
super.onCreate();
}
}
As as I understand, the service would ran until the end of time or until one of the following scenarios occurr:
Low memory: The system is running low on memory so it decides to stop the service.
ANR
The user manually stops the application or disables it.
In 1 and 2 the system would start the service again, after memory is no longer low or after the error is handled. In the case of 3 it wont be started again.
The question is: is the above right? Are there any other cases where the service would be stopped by an outside source? Please specify if it would be started again automatically if there are any.

keeping a service running after shutting down the app

i'm trying to create an app that communicates with my localhost and search in a database.
I already make the connection and find the data, but i need to stay connected and send a notification if there's any changes in the table, but I can't figure it out how to keep the connection even when I close the app, because it closes everything, even the service.
The service doesn't stay open.
This is my Class:
public class SensorService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this,"Starting",Toast.LENGTH_SHORT).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
boolean bandera = true;
Toast.makeText(this, "Checking data...", Toast.LENGTH_SHORT).show();
return START_STICKY;
}
#Override
public void onTaskRemoved(Intent rootIntent) {
super.onTaskRemoved(rootIntent);
stopService(new Intent(this,SensorService.class));
startService(new Intent(this,SensorService.class));
}
#Override
public void onDestroy() {
startService(new Intent(this,SensorService.class));
}
}
Every time I close the app, the service execute one more time and no more.
If you want the service to continue running after the app is closed, you need to call the startForeground(int, Notification) method from within the service. Android limits you to running longer running services in the background only as long as a notification is displayed to the user letting them know that a service is running (like a music player or a downloading service).
This is an intentional design constraint to ensure developers do not start services in the background that run indefinitely without the user being aware. Supply your own notification (can be anything) and you should be able to run the service in the background.
For more detailed information on this method, read it at: startForeground(int, Notification)
You can use onTaskRemoved and restart the service if needed.
#Override
public void onTaskRemoved(Intent rootIntent){
super.onTaskRemoved(rootIntent);
//restart your service
}
Please note that if you use onTaskRemoved, start your service as not sticky so it won't be restarted.
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
return START_NOT_STICKY;
}

Stepcounter in Phonegap - Background service

I am developing a Phonegap application which, among other things, has a step counter (which uses the accelerometer). Obviously, i need the app to count the steps even if the screen is locked. I have used a background service, acquired partial wake lock, but for some reason the service is still killed when i lock the screen. This is the code for the background service:
public class StepCounterService extends Service {
private ELStepCounter mStepCounter;
public static final String TAG = "STEP_COUNTER_SERVICE";
private void publishResult(int steps){
Intent intent = new Intent(TAG);
intent.putExtra("Steps", steps);
sendBroadcast(intent);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
ELStepCounter.startInstance(StepCounterService.this);
mStepCounter = ELStepCounter.getsInstance();
PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
WakeLock wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,
"StepCounterService");
wakeLock.acquire();
mStepCounter.setmStepDetectionListener(new StepCounterInterface() {
#Override
public void onStepDetected(final long steps) {
// TODO Auto-generated method stub
Toast.makeText(StepCounterService.this, steps + " steps", Toast.LENGTH_SHORT).show();
publishResult((int) steps);
}
#Override
public void error(int errorCode) {
// TODO Auto-generated method stub
}
});
return Service.START_STICKY;
}
}
Thanks in advance
I appreciate this answer comes very late. I am sending it just in case it is useful for future reference. I am not an expert on PhoneGap, however I have some experience with Android phones and I guess you may have been testing with one of them. In several Android phones the accelerometer is turned off when the screen is turned off. Not all of them. See a list of models at http://www.saltwebsites.com/2012/android-accelerometers-screen-off
I have asked a question on StackOverflow about that because it looks like Google Fit is kind of overcoming the limitation but I found no answer (see Step Counter in Android: always on?)
I hope it helps

Service stops when deploying android app (disapears from settings>>application>>RunningServices)

This is my situation: I have a service running and every time I deploy my app the service disappears from settings>>application>>runningService (therefore, the service is not running) how can I set it so that the service does not disappears?
I have tried to startForeground but it did not worked.
AndroidManifest:
<service
android:name=".service.PhoneCallInOutService"
android:enabled="true"
android:exported="false" >
</service>
This is how I start the service in my Activity:
chkCallsRecord.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
boolean isChecked = chkCallsRecord.isChecked();
updateBackgroundTasks(isChecked);
}
});
The method actually starting the service:
private void updateBackgroundTasks(boolean start) {
Intent serviceIntent = new Intent(getApplicationContext(),PhoneCallInOutService.class);
if (start) {
getApplicationContext().startService(serviceIntent);
} else {
getApplicationContext().stopService(serviceIntent);
}
}
And here is the service:
public class PhoneCallInOutService extends Service {
private TelephonyManager telephonyMgr;
private PhoneCallStateListener pcsListener;
private OutgoingCallReceiver ocReceiver;
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
// Listener
pcsListener = new PhoneCallStateListener(getApplicationContext(),appDto);
telephonyMgr = (TelephonyManager)getApplicationContext().getSystemService(Context.TELEPHONY_SERVICE);
telephonyMgr.listen(pcsListener, PhoneStateListener.LISTEN_CALL_STATE);
// Receiver
ocReceiver = new OutgoingCallReceiver(getApplication());
IntentFilter intentF = new IntentFilter(Intent.ACTION_NEW_OUTGOING_CALL);
getApplicationContext().registerReceiver(ocReceiver, intentF);
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
// Listener
telephonyMgr.listen(pcsListener, PhoneStateListener.LISTEN_NONE);
// Receiver
getApplicationContext().unregisterReceiver(ocReceiver);
}
#Override
public IBinder onBind(Intent arg0) {
return null;
}
}
Thank you very much in advance.
If by deploy you mean you try to launch new build of your app, then this is actually normal and expected behaviour. By deploying new build you replace old code (incl. service code) therefore it have to be killed first to avoid any crashes and other oddities. So your old iteration of app is completely killed. Then new app is installed and most often auto-launched. Your data create by the app usually stay, but it's also normal.
EDIT
For security reasons you are not allowed to re-launch itself after being updated. User has to to this. As for "he/she may assume the service is still there running, which is not true", use notification of type "On Going" to indicate running service

Android service keeps running indefinitely

I'm trying to create a service in android which i want to keep running in background indefinitely. So I tried to create one like :
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, mssg, Toast.LENGTH_SHORT).show();
}
public int onStartCommand(Intent intent, int flags,int startid) {
Toast.makeText(this, mssg, Toast.LENGTH_LONG).show();
Log.d("Start:", "Service running");
// my code here
return START_STICKY;
}
But when I run this code, the toast messages and logs are only shown once , so does it mean service runs only first time. If it is running again n again which API of it is being called repeatedly ?
Thanks,
shadow.
Running a Service indefinitely and running the same piece of code again and again are two very different things. The piece of code you provided will allow the service to be running the background as long as the Android system doesn't decide to stop it.
Not sure what functionality you are looking to implement, but i suggest you read up on what exactly a Service is used for and what your requirements are.
i suggest you change return START_STICKY;
with return START_NOT_STICKY;
as details given in documentation here.

Categories

Resources