每隔15分钟安排一次TimerTask来刷新应用程序的数据。如何在没有感情计划的计时器任务的情况下在课外执行一次timertask。因为我必须每15分钟不断更新应用程序的数据。有一种情况我需要立即更新课外的数据。
public class SplashActivity extends AppCompatActivity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
}
final Handler handler = new Handler();
timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
if (timer == null) {
cancel();
}
Boolean isInternetPresent = internetCheck.isConnectingToInternet();
if(isInternetPresent)
new MyAsyncTask().execute();
else
System.out.println("Internet connection not presents ");
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 900000);
}
public class MyAsyncTask extends AsyncTask<String, String, String> {
@Override
protected String doInBackground(String... params) {
long s_time = System.currentTimeMillis();
android.util.Log.i("Start ", " Time value in millisecinds " + s_time);
String xmlDataOverHttp = PostData();
long e_time = System.currentTimeMillis();
android.util.Log.i("End ", " Time value in millisecinds " + e_time);
Myregistry registry= AppRegistry.getInstance();
Serializer serializer = new Persister();
MyObject example = null;
try {
example = serializer.read(MyObject.class, student_xml);
} catch (Exception e) {
e.printStackTrace();
}
SharedPreferences.Editor editor = sharedpreferences.edit();
editor.putString(MyObjectXMl, xmlDataOverHttp);
editor.apply();
registry.setObject(example);
return xmlDataOverHttp;
}
public String PostData() {
Boolean s = false;
HttpParams params = new BasicHttpParams();
params.setParameter(CoreProtocolPNames.PROTOCOL_VERSION,
HttpVersion.HTTP_1_1);
HttpClient httpClient = new DefaultHttpClient(params);
String url = "http://localhost:8080" +"/get_xml_data?id=" + 1;
System.out.println("url----------" + url);
HttpPost httpPost = new HttpPost(url);
HttpResponse httpResponse = null;
try {
httpResponse = httpClient.execute(httpPost);
} catch (IOException e) {
e.printStackTrace();
}
HttpEntity httpEntity = httpResponse.getEntity();
String token = readResponse(httpResponse);
return token;
}
这里MyAsyncTask是计时器任务中的计划,每15分钟后调用一次。如何在类外调用此MyAsyncTask调用,而不会影响计划的计时器任务。我没有将MyAsyncTask类设为静态。