2017-08-30 91 views
1

我試圖讓一個intentservice像我一樣在一個文件中完美保存位置服務。android studio intentservice沒有在應用程序之外運行

當文件出現在目錄中時,服務會彈出通知。 這很好地在一個活動內工作,但不關閉時。

這裏是我的代碼:

public class NotifyService extends IntentService { 



public NotifyService() { 
    super("NotifyService"); 
} 

@Override 
protected void onHandleIntent(Intent intent) { 
      File alerte = new File(Environment.getExternalStorageDirectory() + 
      File.separator +"SmartCollecte"+File.separator+ "ALERTE"+File.separator+ "IN"+File.separator+"alerte"); 
    if(alerte.exists()){ 
     createNotification(); 
    } 
    else{} 

} 




@TargetApi(Build.VERSION_CODES.JELLY_BEAN) 
public void createNotification() { 

    Intent intent = new Intent(this, NotificationReceiverActivity.class); 
    PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), intent, 0); 


    Notification noti = new Notification.Builder(this) 
      .setContentTitle("nouvelle collecte " + "[email protected]") 
      .setContentText("une nouvelle collecte est disponible").setSmallIcon(R.drawable.notification) 
      .setContentIntent(pIntent) 
      .setSmallIcon(R.drawable.notification) 
      .build(); 
    NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); 

    noti.flags |= Notification.FLAG_AUTO_CANCEL; 

    notificationManager.notify(0, noti); 

} 

}

我不能找到我缺少的是什麼... 感謝您的幫助

+0

我的是什麼版本你 –

+0

測試的Android仍然在5.1現在 – filoman

+0

你怎麼火的意圖服務? – Vyacheslav

回答

0

此解決方案僅適用於preor 26(Android O)SDK:

你必須啓動你的意向服務使用WakefulBroadcastReceiver 使用這種方式,你可以男人使用alarmmanager使您的服務老化,防止被系統殺死(喚醒鎖定)並刪除依賴關係。

此外,我會建議使用相同的,以實現你的想法。

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

+0

這似乎是正確的方式做我想做的!感謝維亞切斯拉夫我發現了一個很好的例子來使用報警管理器:https://www.mindstick.com/Articles/1627/alarmmanager-with-broadcastreceiver-in-android – filoman

+0

@filoman接受答案,如果它是有用的 – Vyacheslav

相關問題