我有一个流程来处理andoid:
假设我在活动1中,然后有一个API说https://status.com/key,它告诉我是否需要导航到活动2或保留活动1本身。
所以在Activity-1中我将HttpRequest调用放在runnable线程中,并且每隔一秒钟就会持续ping该API以了解其响应。当我得到回答“是”的那一刻,我导航到Activity-2(谷歌地图活动)。
但是我注意到,即使在导航到Activity-2之后,Activity-1中的Runnable线程也在不断运行,因此Activity-2(Google maps活动)会不断地再次加载。如何在Activity-1中停止可运行的线程:
- 尝试过Thread.stop()//无法正常工作
- System.exit(0)//是一个糟糕的选择
醇>
final Runnable r = new Runnable() {
public void run() {
String myUrl="https://app.herokuapp.com/users/userredirection-pickup/"+ridetrackingno;
Log.d("URL",myUrl);
HttpGetRequest getRequest = new HttpGetRequest();
try{
String result = getRequest.execute(myUrl).get();
JSONArray j=new JSONArray(result);
JSONObject jo= j.getJSONObject(0);
String r=jo.getString("status");
if(r.equals("yes")){
Intent show = new Intent (getApplicationContext(), Riding.class);
show.putExtra("Username",username);
show.putExtra("Phone",phone);
startActivity(show);
}
} catch(Exception e)
{
e.printStackTrace();
}
handler.postDelayed(this, 2000);
}
};
handler.postDelayed(r, 2000);
请帮忙。谢谢!
答案 0 :(得分:0)
试试这个。也许它会起作用
final Runnable r = new Runnable() {
public void run() {
String myUrl="https://app.herokuapp.com/users/userredirection-pickup/"+ridetrackingno;
Log.d("URL",myUrl);
HttpGetRequest getRequest = new HttpGetRequest();
try{
String result = getRequest.execute(myUrl).get();
JSONArray j=new JSONArray(result);
JSONObject jo= j.getJSONObject(0);
String r=jo.getString("status");
if(r.equals("yes")){
try {
runOnUiThread(new Runnable() {
@Override
public void run() {
Intent show = new Intent (getApplicationContext(), Riding.class);
show.putExtra("Username",username);
show.putExtra("Phone",phone);
startActivity(show);
}
});
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch(Exception e)
{
e.printStackTrace();
}
handler.postDelayed(this, 2000);
}
};
handler.postDelayed(r, 2000);
答案 1 :(得分:0)
我说的是这个
if(r.equals("yes")){
Intent show = new Intent (getApplicationContext(), Riding.class);
show.putExtra("Username",username);
show.putExtra("Phone",phone);
startActivity(show);
} else {
handler.postDelayed(this, 2000);
}