服务停止应用程序最近清除

服务停止应用程序最近清除

问题描述:

我正在创建一个服务,在后台执行一些工作,此服务在我从最近打开的应用程序中清除我的应用程序时停止。即使我清除了应用程序,我也希望我的服务能够在后台运行。我正在用小米Mi4i设备测试我的应用程序。服务停止应用程序最近清除

这是我的服务类

公共类LocalNotificationService延伸服务{

private int i = 1; 
public static final String TAG = LocalNotificationService.class.getSimpleName(); 
private static long UPDATE_INTERVAL = 1 * 5 * 1000; //default 
private static Timer timer = new Timer(); 
private static final String TIME_FORMAT_LOCAL_NOTIFICATION = "HH:mm"; 
private boolean isNotificationFired = false; 



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

@Override 
public void onCreate() { 
    super.onCreate(); 
    _startService(); 
    startForeground(1,new Notification()); 
    Log.v(TAG, "service created...."); 

} 


private void _startService() { 

    timer.scheduleAtFixedRate(

      new TimerTask() { 

       public void run() { 

        doServiceWork(); 
       } 
      }, 1000, UPDATE_INTERVAL); 
} 


private void doServiceWork() { 

    Log.v(TAG, "service working...."); 

    try { 

     new AsyncTask<Void, Void, Void>() { 

      @Override 
      protected Void doInBackground(Void... params) { 

       String dateString = null; 

       try { 

        String format = "yyyy-MM-dd"; 
        final SimpleDateFormat sdf = new SimpleDateFormat(format); 
        dateString = sdf.format(new Date()) + "T00:00:00"; 
        Log.v(TAG, dateString); 

       } catch (Exception e) { 

        e.printStackTrace(); 

       } 


       List<AppointmentModel> list = new RushSearch().whereEqual("Date", dateString).find(AppointmentModel.class); 

       if (list != null & list.size() > 0) { 

        for (AppointmentModel model : list) { 

         try { 

          if (model.Status.equalsIgnoreCase("Confirmed")) { 

           SimpleDateFormat sdf = new SimpleDateFormat(LocalNotificationService.TIME_FORMAT_LOCAL_NOTIFICATION); 
           Date currentTime = sdf.parse(sdf.format(Calendar.getInstance().getTime())); 
           String From = DateAndTimeUtil.getTimeLocale_HHmm(model.FromTime); 
           Date FromTime = sdf.parse(From); 

           long difference = currentTime.getTime() - FromTime.getTime(); 
           int days = (int) (difference/(1000 * 60 * 60 * 24)); 
           int hours = (int) ((difference - (1000 * 60 * 60 * 24 * days))/(1000 * 60 * 60)); 
           int min = (int) (difference - (1000 * 60 * 60 * 24 * days) - (1000 * 60 * 60 * hours))/(1000 * 60); 
           hours = (hours < 0 ? -hours : hours); 

           Log.v("======= days", " :: " + days); 
           Log.v("======= hours", " :: " + hours); 
           Log.v("======= min", " :: " + min); 


           switch (min){ 

            case -15: { 

             if(!isNotificationFired){ 

              Bundle bundle = new Bundle(); 
              bundle.putString(ArkaaNotificationHandler.NOTIFICATION_KEY_FROM, "Appointment Reminder"); 
              bundle.putString(ArkaaNotificationHandler.NOTIFICATION_KEY_TITLE, "Appointment Reminder"); 
              bundle.putString(ArkaaNotificationHandler.NOTIFICATION_KEY_MESSAGE, "You Have Appointment With " + model.Doctor.Name + "At " + DateAndTimeUtil.getTimeLocale_HHmmaa(From)); 
              bundle.putString(ArkaaNotificationHandler.NOTIFICATION_KEY_COLLAPSE_KEY, ""); 
              ArkaaNotificationHandler.getInstance(LocalNotificationService.this).createSimpleNotification(LocalNotificationService.this, bundle); 
              isNotificationFired = true; 

             } 
             break; 
            } 

            case -5: { 

             if(!isNotificationFired){ 

              Bundle bundle = new Bundle(); 
              bundle.putString(ArkaaNotificationHandler.NOTIFICATION_KEY_FROM, ""); 
              bundle.putString(ArkaaNotificationHandler.NOTIFICATION_KEY_COLLAPSE_KEY, ""); 
              bundle.putString(ArkaaNotificationHandler.NOTIFICATION_KEY_MESSAGE, "You Have Appointment With" + model.Doctor.Name + "At" + DateAndTimeUtil.getTimeLocale_HHmmaa(From)); 

              if(NetworkUtils.getNetworkClass(ArkaaApplicationClass.getInstance().getBaseContext()).equalsIgnoreCase("2G")){ 
               bundle.putString(ArkaaNotificationHandler.NOTIFICATION_KEY_TITLE, "For Better Call Experience Please Switch To High BandWidth Network "); 
              }else{ 
               bundle.putString(ArkaaNotificationHandler.NOTIFICATION_KEY_TITLE, "Appointment Reminder"); 
              } 
              ArkaaNotificationHandler.getInstance(LocalNotificationService.this).createSimpleNotification(LocalNotificationService.this, bundle); 
              isNotificationFired = true; 

             } 
            } 
            case -4: 
            case -14: 
             isNotificationFired = false; 
             break; 
           } 
          } 
         } catch (Exception e) { 

          e.printStackTrace(); 

         } 
        } 
       } 
       return null; 
      } 
     }.execute(); 
    } catch (Exception e) { 

     Log.v(TAG, e.toString()); 

    } 
} 

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

@Override 
public void onTaskRemoved(Intent rootIntent) { 
    stopSelf(); 
} 


private void _shutdownService() { 

    if (timer != null) timer.cancel(); 
    Log.i(getClass().getSimpleName(), "Timer stopped..."); 

} 

@Override 
public void onDestroy() { 
    super.onDestroy(); 

    _shutdownService(); 

    Log.v(TAG, "service destroyed....."); 

    // if (MAIN_ACTIVITY != null) Log.d(getClass().getSimpleName(), "FileScannerService stopped"); 
} 

}

+0

您需要使用前景的服务http://*.com/questions/24839655/how-to-use-startforeground/24839801#24839801 –

+0

这个已经完成,但仍是问题是一样的。 – vickyVick

+0

尝试在'onStartCommand(...)''onStartCommand(...)'函数中返回'START_STICKY' –

您的活动,请执行以下操作来启动服务。例如,在的onCreate():

Intent intent = new Intent(this, MyService.class); 
startService(intent); 

在你的服务,请在的onCreate()如下:

int NOTIFICATION_ID = 2707; 
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this); 

    Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); 

    builder.setSmallIcon(android.R.drawable.ic_menu_info_details) 
     .setContentTitle("MyAppName") 
     .setContentText("the service is running!") 
     .setTicker("the service is running!") 
     .setOnlyAlertOnce(true) 
     .setOngoing(true) 
     .setSound(alarmSound); 

    Notification notification = builder.build(); 

    startForeground(NOTIFICATION_ID, notification); 
+0

已完成此操作,请参阅上面的代码 – vickyVick

+0

您的通知似乎没有将setOngoing设置为true。 –

+0

仍然面临问题 – vickyVick

只是隐藏stopSelf();和_shutdownService();或尝试WakefulBroadcastReceiver方法

https://developer.android.com/reference/android/support/v4/content/WakefulBroadcastReceiver.html