简体   繁体   中英

Android How to keep Running the background service when app is killed by user?

I want a background service that keeps running always in a background? It is running on some phone but not running on customised OS phones like VIVO, OPPO MIUI etc? Service is Killed on these customised OS phone.
My Code is given below --

public class MyService extends Service
{

private static final String TAG = "MyService";


@Override
public void onStart(Intent intent, int startId)
{
    // TODO Auto-generated method stub
    super.onStart(intent, startId);
}

@Override
public boolean onUnbind(Intent intent) {
    return super.onUnbind(intent);
}


@Override
public void onCreate()
{
    super.onCreate();
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
    //call to onTaskRemoved
    onTaskRemoved(intent);
    //return super.onStartCommand(intent, flags, startId);
    Toast.makeText(this, "Service Started!", Toast.LENGTH_SHORT).show();

    return START_STICKY;
}

@Nullable
@Override
public IBinder onBind(Intent intent)
{
    return null;
}

@Override
public void onDestroy()
{

    super.onDestroy();
    int i = 1;
    Intent intent = new Intent(this, MyBroadCastReceiver.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(
            this.getApplicationContext(), 234324243, intent, 0);
    AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(ALARM_SERVICE);

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 5);

    if (alarmManager != null)
    {
        alarmManager.setRepeating(
                AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(),
                60000,
                pendingIntent);
    }

}
@Override public void onTaskRemoved(Intent rootIntent)
{
    Log.e("onTaskRemoved", "Called!");
    int i = 1;
    Intent intent = new Intent(this, MyBroadCastReceiver.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    PendingIntent pendingIntent = PendingIntent.getBroadcast(
            this.getApplicationContext(), 234324243, intent, 0);
    AlarmManager alarmManager = (AlarmManager) getApplicationContext().getSystemService(ALARM_SERVICE);
    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.HOUR_OF_DAY, 0);
    calendar.set(Calendar.MINUTE, 0);
    calendar.set(Calendar.SECOND, 5);

    if (alarmManager != null)
    {
        alarmManager.setRepeating(
                AlarmManager.RTC_WAKEUP,
                calendar.getTimeInMillis(),
                AlarmManager.INTERVAL_FIFTEEN_MINUTES,
                pendingIntent);
    }


    super.onTaskRemoved(rootIntent);

}}

I have written a Broadcast Receiver that wake ups my service for every second but it is not working. My Broadcast Receiver as follows-

public class MyBroadCastReceiver extends BroadcastReceiver
{

@Override
public void onReceive(Context context, Intent intent)
{
    Log.e("MyBroadCastReceiver", "onReceive");

    //if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction()))
    {
        if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.O)
        {
            FirebaseJobDispatcher dispatcher = new FirebaseJobDispatcher(new GooglePlayDriver(context));
            Job myJob = dispatcher.newJobBuilder()
                    .setService(MyJobService.class)
                    .setTag("myFCMJob")
                    .build();
            dispatcher.mustSchedule(myJob);
        }
        else
        {
            Intent service = new Intent(context, MyService.class);
            context.startService(service);
        }
    }
}}

I have started my service using Alarm Manager and have set the Alarm for every 5 seconds, my MainActivity.java file code is as below ---

public class MainActivity extends AppCompatActivity
{

Button btnStopService;

@Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    btnStopService = findViewById(R.id.btnStopService);

    //get FirebaseToken
    getToken();

    //start Service
    startService();
    //setReceiver();

    btnStopService.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(MainActivity.this, MyService.class);
            stopService(intent);
        }
    });

}


private void getToken()
{
    FirebaseId firebaseId=new FirebaseId();
    String token_firebase=firebaseId.getFireBaseToken();
}


private void startService()
{

    Intent myIntent = new Intent(this, MyService.class);
    PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
    Log.e("TAG", "++++++++++222222++++++++");
    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
    //Calendar calendar = Calendar.getInstance();
    // calendar.setTimeInMillis(System.currentTimeMillis());
    //calendar.add(Calendar.SECOND, 10);

    Calendar alarmStartTime = Calendar.getInstance();
    Calendar now = Calendar.getInstance();
    alarmStartTime.set(Calendar.HOUR_OF_DAY, 0);
    alarmStartTime.set(Calendar.MINUTE, 0);
    alarmStartTime.set(Calendar.SECOND, 5);
    if (now.after(alarmStartTime)) {
        Log.d("Hey","Added a day");
        //alarmStartTime.add(Calendar.DATE, 1);
    }

    if (alarmManager != null) {
        alarmManager.set(
                AlarmManager.RTC_WAKEUP,
                alarmStartTime.getTimeInMillis(),
                pendingIntent);
    }

    Toast.makeText(this, "Start Alarm", Toast.LENGTH_LONG).show();
}}

Thanks in Advance.

To keep your service and all your application running even if the phone goes into sleep mode, your service has to call startForeground() and show a non dismissable notification. It is also convenient to acquire a partial WAKE LOCK.

on your onStartCommand()

 NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, Constants.CHANNEL_NOTIFY_ID)
                    .setContentTitle("the content title")
                    .setContentText("the content text")
                    .setSmallIcon(R.drawable.myicon)                      
                    .setOngoing(true); 
               // you can add other options Builder has


            startForeground(1234, mBuilder.build());

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