0

У меня есть приложение в Android-приложении, и я хочу запускать в фоновом режиме непрерывно, даже приложение убито из диспетчера задач. Мой текущий код работает хорошо для версий до леллипа. в lollipop это не сработало (в lollipop оно останавливается от диспетчера задач). Как решить это.Android Background Service stop in lollipop whille swipe from task Manager

Класс обслуживания

public class MyService extends Service { 

    int total_time = 1000 * 60 * 60 * 24; // total one day you can change 
    int peroid_time = 10000; // one hour time is assumed to make request 

@Override 
    public void onCreate() { 

    } 

    /** The service is starting, due to a call to startService() */ 
    @Override 
    public int onStartCommand(Intent intent, int flags, int startId) { 


     new CountDownTimer(total_time, peroid_time) { 


      public void onTick(long millisUntilFinished) { 
       // make request to web and get reponse and show notification. 
       MakingWebRequest(); 

       Toast.makeText(MyService.this, " Tesitng the data", Toast.LENGTH_LONG).show(); 
      } 


      public void onFinish() { 

       Toast.makeText(MyService.this, " ending............", Toast.LENGTH_LONG).show(); 
       // 
      } 
     }.start(); 
     // Let it continue running until it is stopped. 
     Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show(); 
     return START_STICKY; 

    } 

    public void MakingWebRequest() { 

           NotificationManager notif = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
           NotificationCompat.Builder builder = new NotificationCompat.Builder(MyService.this); 
           Notification notify ; 
           PendingIntent pending = PendingIntent.getActivity(getApplicationContext(), 0, new Intent(), 0); 

           notify = builder.setContentIntent(pending) 
             .setStyle(new NotificationCompat.BigTextStyle().bigText(message1)) 
             .setSmallIcon(R.drawable.push).setTicker(excep).setWhen(System.currentTimeMillis()) 
             .setAutoCancel(true).setContentTitle(message1) 
             .setContentText(message1).build(); 
//    notif.notify(NOTIFICATION, notify); 
//        notif.notify(0, notify); 
            startForeground(1, notify); 

     } 



    } 

    /** A client is binding to the service with bindService() */ 
    @Override 
    public IBinder onBind(Intent intent) { 
     return mBinder; 
    } 

    /** Called when all clients have unbound with unbindService() */ 
    @Override 
    public boolean onUnbind(Intent intent) { 
     return mAllowRebind; 
    } 

    /** Called when a client is binding to the service with bindService()*/ 
    @Override 
    public void onRebind(Intent intent) { 

    } 

Основная деятельность

Intent serviceIntent = new Intent(this, MyService.class); 
     serviceIntent.setPackage(this.getPackageName()); 
     startService(serviceIntent); 
+0

Вы хотите что-то делать один раз в час? Для этого вам не требуется непрерывное обслуживание. Вы совершаете службу каждый час. Google GcmNetworkManager и PeriodicTask. –

+0

Я не хочу, чтобы gcm как вещи. PLZ остался на моем коде и логике. Просто, как предотвратить остановку приложения. – Adi

+0

Вы не можете этого предотвратить. Я предлагаю вам альтернативу, которая также является лучшей практикой. GCM! = GcmNetworkManager. GcmNetworkManager = JobScheduler, который именно то, что вам нужно. Он периодически запускает задачу, когда сеть доступна (если вы ее настроили). Да, иногда нам приходится переписывать код. –

ответ