Android如何在用户杀死应用程序时继续运行后台服务?

时间:2018-04-11 12:47:44

标签: java android

我想要一个始终在后台运行的后台服务?它在某些手机上运行,​​但没有在VIVO,OPPO MIUI等定制的OS手机上运行?这些定制的OS手机上的服务被杀死 我的代码如下 -

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);

}}

我写了一个广播接收器,它每秒都会唤醒我的服务,但它无法正常工作。我的广播接收器如下 -

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);
        }
    }
}}

我已经使用Alarm Manager启动了我的服务并且每隔5秒设置一次警报,我的MainActivity.java文件代码如下---

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();
}}

先谢谢。

1 个答案:

答案 0 :(得分:0)

即使手机进入睡眠模式,为了保持您的服务和所有应用程序正常运行,您的服务也必须致电startForeground()并显示不可忽略的通知。 获取部分唤醒锁也很方便。

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());