2017-03-26 107 views
3

嗨,我想更新在15分钟的时间间隔,特别是在15分钟的当前时间基础上在后台运行的服务。如何在每15分钟的当前时间每15分钟运行一次android服务?

服务:

public class UpdateService extends IntentService { 

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

    // will be called asynchronously by Android 
    @Override 
    protected void onHandleIntent(Intent intent) { 
     updateFragmentUI(); 
    } 


    private void updateFragmentUI() { 
     this.sendBroadcast(new Intent().setAction("UpdateChart")); 
    } 
} 
+0

可以使用[的jobscheduler](https://developer.android.com/reference/android/app/job/JobScheduler.html)对于API 21和上述 –

+0

看' evernote/android-job' – EpicPandaForce

回答

1

使用报警经理或招聘计划启动服务 看看这个链接..

How to start Service using Alarm Manager in Android?

为你我会建议使用setExact而不是setRepeating。 这里是代码...

AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
int ALARM_TYPE = AlarmManager.RTC_WAKEUP; 
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) 
    am.setExact(ALARM_TYPE, calendar.getTimeInMillis(), pendingIntent); 
else 
    am.set(ALARM_TYPE, calendar.getTimeInMillis(), pendingIntent); 

记住setExact不提供,所以你必须从你的服务再次设定每一次......和第一次重复功能,从您的活动有10分钟的延迟。并延迟15分钟服务(根据您的使用情况)。

+0

嗨,如果我在12:05 AM开始服务,它应该只更新12:15,然后每隔15分钟更新一次 –

+0

嗨,请检查我编辑过的答案。 – Techierj

0

我有同样的问题,我使用递归函数HandlerpostDelay

解决方案:

public class UpdateService extends Service { 

Handler handler = new Handler(); 

public UpdateService() { 
} 

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

@Override 
public void onCreate() { 
} 

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 

    handler.postDelayed(new Runnable() { 
    public void run() {  

        /* 
        * code will run every 15 minutes 
         */ 

        handler.postDelayed(this, 15 * 60 * 1000); //now is every 15 minutes 
        } 

       }, 0); 

    return START_STICKY; 
    } 
} 
+0

它会每15分钟工作一次,但如果我在12:02 AM开始服务,应该更新12:15而不是12:17,然后每15分钟更新一次。 –

+0

如果您想在特定时间运行某些内容,您的问题是每15分钟运行一次您的服务。使用报警管理器 – W4R10CK

相关问题