我想创建一个服务,即下载一个文本文件[背景]每隔几分钟。
I want to create a service, that downloads a textfile [in background] every few minutes.
-BootStartU preciver.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);
}
}
};
}
这code工作正常,但只有一次。谁能告诉我怎么可以让它重复(背景)每隔几分钟(15为例)?而且我觉得我的的manifest.xml
是正确的,因为该服务已经在运行。
This Code is working fine, but only once. Can anyone tell me how I can make it repeat (in background) every few minutes (15 for example)? And i think my manifest.xml
is correct because the service is already running.
确定试试这个在您的服务类
ok try this in your service class
@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分钟,这比报警经理/等待更好的意图 - 没有唤醒锁,电池耗尽等..让我知道,如果它可以帮助
broadcast receiver starts the service and the service runs every 15mins in the background, this is better than alarm manager/pending intent - no wake lock, draining of battery etc.. let me know if it helps