定期在后台运行任务

时间:2015-06-24 11:40:53

标签: java android

我希望在5分钟间隔后在后台运行一些任务(从数据库中获取数据)。我该怎么用?

6 个答案:

答案 0 :(得分:0)

您可以在服务中使用TimerTask

 Timer timer = new Timer(); 
 timer.schedule( new YourTask(), 50000 );

答案 1 :(得分:0)

试试这个。

  Timer timer = new Timer();
  timer.scheduleAtFixedRate(new TimerTask() {

   @Override
   public void run() {
    //Do something

   }
  }, 0, 5000);

答案 2 :(得分:0)

使用异步任务:

执行前执行,执行inBackground,执行后执行

使用闹钟管理器

Intent myIntent1 = new Intent(sign_in.this,MyNotificationService.class);
                        pendingintent2 = PendingIntent.getService(sign_in.this, 1,myIntent1, 1);
                        AlarmManager alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE);
                        Calendar calendar1Notify = Calendar.getInstance();
                        calendar1Notify.setTimeInMillis(System.currentTimeMillis());
                        calendar.add(Calendar.SECOND, 20);

                        alarmManager1.set(AlarmManager.RTC_WAKEUP,calendar1Notify.getTimeInMillis(), pendingintent2);

                        long time = 300*1000;// 5 minutes repeat

 alarmManager1.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar1Notify.getTimeInMillis(),time,pendingintent2);

在清单

中添加权限
    <service android:name="com.example.MyNotificationService" >

        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </service>

答案 3 :(得分:0)

您可以使用计时器任务:

TimerTask scanTask;
final Handler handler = new Handler();
Timer t = new Timer();

public void doTask(){

scanTask = new TimerTask() {
        public void run() {
                handler.post(new Runnable() {
                        public void run() {
                            //your task(fetch data)
                        }
               });
        }};

    t.schedule(scanTask, 300000, 300000); 
 }

答案 4 :(得分:0)

请注意,Google会要求您对服务进行长时间的操作。请阅读以下文章,找出您需要的服务(服务,服务间)!

意图服务将在作业完成后自行关闭。 要按照每5分钟触发一次服务来完成这项工作,您可以按照上面的建议与计时器结合使用。

继续之前的思考:服务属于您创建它的同一个线程。因此,当您即将开发您的服务时,请使用新的线程来启动它。如果你忘记这样做,你的服务将属于UI线程,意味着你遇到麻烦.... 先阅读: http://developer.android.com/guide/components/services.html

开发者指南: http://developer.android.com/reference/android/app/Service.html

答案 5 :(得分:0)

你可以使用计时器,这不是问题但是android中的方法确实有一些优点

private int mInterval = 5000; // 5 seconds by default, can be changed later
  private Handler mHandler; 

  @Override 
  protected void onCreate(Bundle bundle) {
    ... 
    mHandler = new Handler(); 
  } 

  Runnable mStatusChecker = new Runnable() {
    @Override  
    public void run() { 
      updateStatus(); //this function can change value of mInterval. 
      mHandler.postDelayed(mStatusChecker, mInterval);
    } 
  }; 

  void startRepeatingTask() { 
    mStatusChecker.run(); 
  } 

  void stopRepeatingTask() { 
    mHandler.removeCallbacks(mStatusChecker);
  }