【发布时间】: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。 -
为此,您可以使用
AlarmManager和PendingIntent并在特定时间间隔重复调用您的服务类。即 15 分钟 -
好的,谢谢大家,我会尝试谷歌AlarmManager并试一试