0
基本上,我的想法是檢查網絡會話是否仍然有效,如果沒有,我開始主動活動,自動記錄用戶。從新線程中的類開始活動
我有這個工作,不知道這是否是最好的方法。如果有人有更好的方法,請讓我知道。
感謝
用途:
@Override
public void onResume() {
super.onResume();
new LoginCheck(this,new Intent(this,MyActivity.class));
}
的Class
public class LoginCheck extends Application {
Intent home;
Activity activity;
public LoginCheck(Activity activity, Intent home) {
this.activity = activity;
this.home = home;
new Check().execute();
}
public class Check extends AsyncTask {
@Override
protected Object doInBackground(Object... objects) {
try {
InputStream is = null;
String result = "";
JSONObject jArray = null;
PersistentCookieStore myCookieStore = new PersistentCookieStore(MyApp.getAppContext());
//http post
DefaultHttpClient mClient = AppSettings.getClient();
try {
HttpPost request = new HttpPost(MyApp.getServiceUrl() + "/Api/Login/AmILoggedIn");
mClient.setCookieStore(myCookieStore);
HttpResponse response = mClient.execute(request);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
Log.e("log_tag", "Error in http connection " + e.toString());
}
//convert response to string
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
} catch (Exception e) {
Log.e("log_tag", "Error converting result " + e.toString());
}
final String r = result;
final Intent i = home;
activity.runOnUiThread(new Runnable() {
@Override
public void run() {
try {
JSONObject j = new JSONObject(r);
if (!j.getBoolean("Success")) {
try {
activity.startActivity(i);
} catch (Exception e) {
Log.e("log_tag", e.getMessage());
}
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
}
}
});
return true;
} catch (Exception e) {
}
return null;
}
}
}
我不是你在做什麼完全清楚,但你可以移動代碼中的run()''到onPostExecute()'。這種方法已經可以訪問UI線程... – Sam
良好的捕獲,這將清理它一點。 – user1723341