重复服务任务

时间:2014-08-29 14:08:44

标签: android service

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

-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是正确的,因为该服务已经在运行。

2 个答案:

答案 0 :(得分:0)

另一方面,我认为这会有所帮助,但不完全。

// 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();
              }

       };

希望它有效,但从未尝试过运行它,但你会得到这个想法。 :)

答案 1 :(得分:0)

好的,在您的服务类

中试试这个
@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分钟运行一次, 这比警报管理器/未决意图更好 - 没有唤醒锁定,电池耗尽等。 让我知道它是否有帮助

相关问题