2017-08-30 37 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

相关问题