我對Android開發和Java一般都非常陌生。以下是基本設置:我有一個啓動屏幕,其中AsyncTask
用於檢查服務器的可用性。正在關注this線程我在我的活動中進行了回調。這比在OnPostExecute()
中進行工作更有意義,因爲我想在不同的活動中重複使用此任務。Android從匿名類中獲取活動
但是,在我的回調中,我會檢查狀態是否正常。如果是,它應該啓動下一個活動。但從我的回調中,我不明白我能如何獲得我的Activity
參考,我需要它作爲Intent的參數。
這是在OnCreate下在我的活動代碼:
//Check server status
CheckServiceTask t = new CheckServiceTask(new OnTaskCompleted<ShaggyServiceStatus>() {
@Override
public void onTaskCompleted(ShaggyServiceStatus result) {
Log.i(TAG, "Callback. Result: " + result.getStatus());
ProgressBar pb = (ProgressBar) findViewById(R.id.splash_progress);
pb.setVisibility(View.INVISIBLE);
if (result.getStatusCode() == 999){
TextView t = (TextView) findViewById(R.id.splash_status_text);
t.setText(result.getStatus());
return;
}
Intent i = new Intent(getActivity(), LoginActivity.class);
startActivity(i);
finish();
}
});
t.execute();
哪裏失敗是getActivity()
的一部分。該呼叫不可用。使用this
會拋出一個錯誤(我知道,因爲我在OnTaskCompleted
的上下文中)。
爲了完整,這是OnTaskCompleted接口:
public interface OnTaskCompleted<T> {
public void onTaskCompleted(T result);
}
這是CheckServiceTask類:
public class CheckServiceTask extends AsyncTask<Void, Void, ShaggyServiceStatus>{
private static final String TAG = "coo";
public OnTaskCompleted<ShaggyServiceStatus> listener;
public CheckServiceTask (OnTaskCompleted<ShaggyServiceStatus> l){
this.listener = l;
}
@Override
protected ShaggyServiceStatus doInBackground(Void... params) {
try {
Log.i(TAG, "Connecting to server...");
//TODO: Make this a setting
final String url = "https://someplace.com/status";
RestTemplate restTemplate = new RestTemplate();
restTemplate.getMessageConverters().add(new MappingJackson2HttpMessageConverter());
//restTemplate.postForObject("url", bodyObject, ShaggySer.class);
ShaggyServiceStatus sss = restTemplate.getForObject(url, ShaggyServiceStatus.class);
Log.d(TAG, "Got the status.");
return sss;
} catch (Exception e) {
//TODO: Exception handling
Log.e(TAG, e.getMessage(), e);
}
//If we're here, it's not okay.
ShaggyServiceStatus r = new ShaggyServiceStatus("Cannot connect to server", 999, "none");
return r;
}
@Override
protected void onPostExecute(ShaggyServiceStatus result) {
super.onPostExecute(result);
listener.onTaskCompleted(result);
}
}
是啊,這確實訣竅! 'SplashActivity.this' – Coo