I have an application with a service. The service is launched by the application in the main activity using the creation method. My problem arises when I exit the application: the service stops and sometimes restarts immediately, sometimes restarts recently. I tested version 4.1.2 and version 2.3.6. service is not returned in version 2.3.6. Is my approach wrong? Between the stop and restart times, a call may occur that must be blocked. Is there a way to not stop the service when exiting the application? Note. I can not use the remote service.
I added startForeground for maintenance, but the same problem. when I exit the application, the service is stopped and does not restart version 2.3.3, even I see a notification. But PhoneStateListener is null. How can I ensure that when I exit the 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 am changing where the callstatelistener parameter is from the broadcast service, as reported by Dhawal Sodha, but in this case, blocking the unwanted call is slowed down. I think that in the broadcast TelephonyManager initializes every call. Broadcast code below. When I use the services, when the main action is completed, the service is stopped in version 2.3.3. Any ideas? Broadcast or service? How to make broadcast faster? all calling variables and the object are initialized again in the translation.
public class PhoneStateBroadcastReceiver extends BroadcastReceiver{ MyCustomStateListener myCustomStateListener; TelephonyManager telephonymanager; @Override public void onReceive(Context context, Intent intent) { try {