Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android service stops when I exit from application

I have an application with a service. Service is started by app in the main activity on create method. My problem occurs when I exit from application: service stops and sometimes restarts immediately, sometimes restarts lately. I tested in version 4.1.2 and version 2.3.6. service does not again in version 2.3.6. Is my approach wrong? Between the stop and restart times, the call that must blocked can come. Is there any way to not stop the service when app is exited? Note: I cannot use a remote service.

i added startForeground to service but the same problem. when i exit application the service stopped and not restart version 2.3.3 even i see notification.But phoneStateListener takes null value How can i ensure when i exit application, the service does not stop

 //application main metod
@Override
protected void onCreate(Bundle savedInstanceState) {              
//.....

    startService(new Intent(getApplicationContext(), MyPhoneStateListener.class));
}




 @Override
 public int onStartCommand(Intent intent, int flags, int startId)
 {
    setCallListener();    
    setNoti();
    return START_STICKY;
 }

 private void setCallListener()
 {
        try
        {
            if (phoneStateListener==null)
            {

              phoneStateListener = new StateListener();
              telephonymanager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
                 telephonymanager.listen(phoneStateListener,PhoneStateListener.LISTEN_CALL_STATE);
            }
        }
        catch(Exception ex)
        { 

        }
    }

private void setNoti() {

    Notification notification= new Notification(R.drawable.ic_launcher,  getResources().getString(R.string.app_name), System.currentTimeMillis());

    Intent main = new Intent(this, MainActivity.class);

    main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);

    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, main,  PendingIntent.FLAG_UPDATE_CURRENT);

    notification.setLatestEventInfo(this, getResources().getString(R.string.app_name), getResources().getStringArray(R.array.blockstate)[Sabitler.ShieldState].toString(), pendingIntent);

    notification.flags |= Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_NO_CLEAR;

    startForeground(123456, notification);  
}

i change the where setting callstatelistener from service to broadcast as Dhawal Sodha advised but in this case blocking unwanted call get slow. i think on broadcast TelephonyManager initializes every calling. Broadcast code below. When i use service, when main activity is exited service stopped in version 2.3.3. Any idea ? Broadcast or service ? How can make broadcast faster? every calling variables and object initialize again in broadcast.

public class PhoneStateBroadcastReceiver extends BroadcastReceiver{

    MyCustomStateListener myCustomStateListener;
    TelephonyManager telephonymanager;
    @Override
    public void onReceive(Context context, Intent intent) 
    {
        try
        {
            //Log.e("receiver1",String.valueOf(System.currentTimeMillis()));

            telephonymanager = (TelephonyManager) context.getSystemService(context.TELEPHONY_SERVICE);
            myCustomStateListener = new MyCustomStateListener(context,telephonymanager);
            telephonymanager.listen(myCustomStateListener, PhoneStateListener.LISTEN_CALL_STATE);
            //Log.e("receiver2",String.valueOf(System.currentTimeMillis()));
            telephonymanager.listen(myCustomStateListener, PhoneStateListener.LISTEN_NONE);
        }
        catch(Exception ex)
        { 
            Toast.makeText(context,"setCallListener:"+ex.toString(), Toast.LENGTH_SHORT).show();
        }
    }   
}
like image 306
user2331641 Avatar asked Apr 29 '13 10:04

user2331641


2 Answers

Are you starting the Service with startService? If so, when you end your activity, the service is not bound to anything and can be stopped by the system.

If you want to run a background Service regardless of your activities, use startForeground and provide a constant notification.

See the Service reference: http://developer.android.com/reference/android/app/Service.html

UPDATE

Finishing your app with System.exit(0)? Of course your service stops, that kills your process. You should never exit an application like that - just finish() your activity.

like image 108
SirKnigget Avatar answered Nov 17 '22 06:11

SirKnigget


Add this code in your onStartCommand() method

  showToast("onStart");

  Intent intent = new Intent(this, NotStickyActivity.class);
  intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
  PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);

  Notification noti = new Notification.Builder(getApplicationContext())
              .setContentTitle("Pratikk")
              .setContentText("Subject")
              .setSmallIcon(R.drawable.ic_launcher)
              .setContentIntent(pendingIntent)
              .build();

  startForeground(1234, noti);     

  return Service.START_STICKY;

It will not stops your service.

like image 34
Pratikk Avatar answered Nov 17 '22 06:11

Pratikk