如何在Android中加载没有WebView的URL?

时间:2019-07-18 09:21:25

标签: android webview android-service

我想每30秒(作为一项服务)在我的应用程序中在后台加载一个url。我必须在服务类中加载url,因为它没有布局,因此webview不适合这样做。即使关闭应用程序,我该如何在后台加载url?

MyService.java类

public class MyService extends Service {
Activity activity ;

Handler handler = new Handler();
Runnable runnable;
int delay = 7*1000;

public MyService(Activity activity){
    this.activity = activity ;
}

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

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    handler.postDelayed( runnable = new Runnable() {
        public void run() {
            loadURL();

            handler.postDelayed(runnable, delay);
        }
    }, delay);
    return START_STICKY ;
}

@Override
public void onDestroy() {

}

public void loadURL(){
    try{
        String id = activity.getIntent().getStringExtra("ID");
        URL url = new URL("http://localhost/att.php?id=" + id + "&status=&submit=Insert");
        HttpURLConnection con = (HttpURLConnection) url.openConnection();
        con.setRequestMethod("GET");
    } catch (Exception e){
        Toast.makeText(this, ""+e.getMessage(), Toast.LENGTH_SHORT).show();
    }
}

}

1 个答案:

答案 0 :(得分:0)

您可以使用新的WorkManager。

基本上,您创建一个从以下其中一个扩展的Worker类:​​

工人 协程工人 RxWorker ListenableWorker

然后您这样声明它:

val mWorker = PeriodicWorkRequestBuilder<Worker>(15, TimeUnit.MINUTES)
            .addTag(WORK_TAG)
            .setConstraints(Constraints.Builder().setRequiredNetworkType(NetworkType.CONNECTED).build())
            .build()

然后排队唯一的工作,以使工作管理器不再执行同一任务:

  WorkManager.getInstance(context)
            .enqueueUniquePeriodicWork(WORK_TAG, ExistingPeriodicWorkPolicy.KEEP, locationWorker)

在将Worker类扩展到例如ListenableWorker时使用代码,您将覆盖startWork()函数并在正文中运行:

 handler.postDelayed( runnable = new Runnable() {
        public void run() {
            loadURL();

            handler.postDelayed(runnable, delay);
        }
    }, delay);