我想每隔1分钟通过我的应用程序调用一个URL。即使该应用被终止,该网址也应每分钟重新加载一次。因此,我认为可以使用后台服务。如何在后台将URL作为服务加载。我进行了很多搜索,但没有任何方法可以解决我的问题。 这是我的尝试:
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://192.168.1.6/att.php?emp_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();
}
}
}