简体   繁体   中英

How to create service Detaction call always running after killed app over api 26 in android studio java

i am using this code and this code running if app active in screen and if closed the code is not running
how to fix this like truecaller app is running in background if killed app

    package com.islamelwakeel.detectcall;

    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.telephony.TelephonyManager;
    import android.util.Log;
    import android.view.Gravity;
    import android.widget.Toast;

    public class CallReceiver extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
    if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){
        showToast(context,"Call started...");
    }
    else if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_IDLE)){
                showToast(context,"Call ended...");
            }
            else if(intent.getStringExtra(TelephonyManager.EXTRA_STATE).equals(TelephonyManager.EXTRA_STATE_RINGING)){
                showToast(context,"Incoming call...");
                Log.d("call","Incoming call...");
            }
        }

        void showToast(Context context,String message){
            Toast toast=Toast.makeText(context,message,Toast.LENGTH_LONG);
            toast.setGravity(Gravity.CENTER,0,0);
            toast.show();
        }
    }

My service was also killed. I tried many methods, but I discovered one method that worked. I used a service that receives calls from the system to check if my service is still running. If it doesn't work, start it. New Service. For example, NotificationListenerService will have it. There will be some events all the time. And I can write code to restart my service there

Ex.

@Override
public void onNotificationPosted(StatusBarNotification sbn) {
   if(!isMyserviceRunning){
      startService();
   }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM