我想检查一些 Web API并每 x 分钟做一些事情。我认为我应该在 Android 上编写一个服务(还有其他解决方案吗?)。
但怎么能做到呢?
我正在考虑编写一个服务类,在清单文件中我应该添加这一行:
<service
android:name="com.xx.yy.noti_check"
android:enabled="true"
>
</service>
在我的 noti_check 类中,我在 onStartCommand 上检查我的 Web API:
public class noti_check extends Service {
Context mcont;
private Handler myhandler ;
private long RETRY_TIME = 15000;
private long START_TIME = 2000;
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
@Override
public void onStart(Intent intent, int startId) {
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
mcont=this;
myhandler= new Handler();
myhandler.postDelayed(myRunnable, START_TIME);
return Service.START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
try {
myhandler.removeCallbacks(myRunnable);
}
catch (Exception e) {
// TODO: handle exception
}
}
private Runnable myRunnable = new Runnable() {
public void run() {
try {
new get_notifyalert(mcont).execute("") ;
}
catch (Exception e) {
// TODO: handle exception
}
myhandler.postDelayed(myRunnable, RETRY_TIME);
}
};
}
这是正确的方法吗?