【问题标题】:Repeat Service Task重复服务任务
【发布时间】:2014-08-29 14:08:43
【问题描述】:

我想创建一个服务,每隔几分钟[在后台]下载一个文本文件。

-BootStartUpReciver.Java

public class BootStartUpReciver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        Intent service = new Intent(context, DownloadService.class);
        context.startService(service);
        Log.e("Autostart", "started");
    }
}

-DownloadService.Java

public class DownloadService extends Service {
    @Override
    public void onCreate() {
        super.onCreate();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Download.start();
        return START_STICKY;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
    }

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

    public Thread Download = new Thread() {
        public void run() {
            try {
                URL updateURL = new URL("MYURLHERE");
                URLConnection conn = updateURL.openConnection();
                InputStream is = conn.getInputStream();
                BufferedInputStream bis = new BufferedInputStream(is);
                ByteArrayBuffer baf = new ByteArrayBuffer(50);

                int current = 0;
                while ((current = bis.read()) != -1) {
                    baf.append((byte) current);
                }

                final String s = new String(baf.toByteArray());
                Log.e("Done", "Download Complete : " + s);
            }
            catch (Exception e) {
                Log.e("Downladoing", "exception", e);
            }
        }
    };
}

此代码运行良好,但只有一次。谁能告诉我如何让它每隔几分钟(例如 15 分钟)重复一次(在后台)?而且我认为我的manifest.xml 是正确的,因为该服务已经在运行。

【问题讨论】:

  • 每15分钟使用AlarmManager触发Download
  • 为此,您可以使用AlarmManagerPendingIntent 并在特定时间间隔重复调用您的服务类。即 15 分钟
  • 好的,谢谢大家,我会尝试谷歌AlarmManager并试一试

标签: android service


【解决方案1】:

好的,在你的服务类中试试这个

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
   // TODO Auto-generated method stub      
   Timer timer = new Timer();
        TimerTask task = new TimerTask() {       
            @Override
            public void run() {
                 Download.start();
            }
        };
        timer.schedule(task, 0, (60000 * 15));// In ms 60 secs is 60000 
        // 15 mins is 60000 * 15


return START_STICKY;
}

广播接收器启动服务,服务在后台每15分钟运行一次, 这比警报管理器/未决意图更好 - 没有唤醒锁定,电池耗尽等。 如果有帮助,请告诉我

【讨论】:

  • 谢谢@Elltz,它第一次工作,但是当它重复时,我得到这个错误致命异常:Timer-0 _ java.lang.IllegalThreadStateException:线程已经启动。在 java.lang.Thread.start(Thread.java:1045) 在 java.util.Timer$TimerImpl.run(Timer.java:284)
  • 你修好了??如果不让我知道,如果您遇到线程错误,请直接从计时器任务运行..
  • 是的,我只是直接从计时器任务器运行它,它可以工作:) 谢谢
【解决方案2】:

另一方面,我认为这会有所帮助,但并非完全如此。

// the scheduler
protected FunctionEveryFifteenMinutes scheduler;


// method to schedule your actions
private void scheduleEveryFifteenMinutes(){

        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, 
                                                                 new Intent(WAKE_UP_AFTER_FIFTEEN_MINUTES), 
                                                                 PendingIntent.FLAG_UPDATE_CURRENT);

        // wake up time every 15 minutes
        Calendar wakeUpTime = Calendar.getInstance();
        wakeUpTime.add(Calendar.SECOND, 60 * 15);

        AlarmManager aMgr = (AlarmManager) getSystemService(ALARM_SERVICE);        
        aMgr.set(AlarmManager.RTC_WAKEUP,  
                 wakeUpTime.getTimeInMillis(),                 
                 pendingIntent);
}

//put this in the creation of service or if service is running long operations put this in onStartCommand

scheduler = new FunctionEveryFifteenMinutes();
registerReceiver(scheduler , new IntentFilter(WAKE_UP_AFTER_FIFTEEN_MINUTES));

// broadcastreceiver to handle your work
class FunctionEveryFifteenMinutes extends BroadcastReceiver{
        @Override
        public void onReceive(Context context, Intent intent) {
                // if phone is lock use PowerManager to acquire lock

                // your code to handle operations every fifteen minutes...
                // example Download.start() and etc.

                // after that call again your method to schedule again
                scheduleEveryFifteenMinutes();

        }
}

并将其添加到您的 Download run 方法的末尾

public Thread Download = new Thread() {
     public void run() {

 try {

                 URL updateURL = new URL("MYURLHERE");                
                 URLConnection conn = updateURL.openConnection(); 
                 InputStream is = conn.getInputStream();
                 BufferedInputStream bis = new BufferedInputStream(is);
                 ByteArrayBuffer baf = new ByteArrayBuffer(50);

                 int current = 0;
                 while((current = bis.read()) != -1){
                      baf.append((byte)current);
                 }

                 final String s = new String(baf.toByteArray());         


                Log.e("Done",  "Download Complete : " + s);


                } catch (Exception e) {
                Log.e("Downladoing", "exception", e);
                }
                //here
                scheduleEveryFifteenMinutes();
              }

       };

希望它有效,但从未尝试过运行它,但你会明白的。 :)

【讨论】:

    猜你喜欢
    • 2015-08-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-31
    • 1970-01-01
    相关资源
    最近更新 更多