我的 IntentService 中有一个无限循环,可根据主要活动的输入每 30 秒更新一次视图。
public class IntentServiceTest extends IntentService {
String Tag = "IntentServiceTest";
String ACTION_RCV_MESSAGE = "com.jsouptest8.intent.action.MESSAGE";
public IntentServiceTest(){
super("IntentServiceTest");
Log.d(Tag, "IntentServiceTest constructor");
}
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Log.d(Tag, "in onHandleIntent");
String url = intent.getStringExtra("URL");
Document doc;
int i=0;
try{
while(true){
Log.d(Tag, "entered try block...");
Log.d(Tag, "url = "+url);
doc = Jsoup.connect(url)
.get();
Log.d(Tag, "past Jsoup.connect");
Element data = doc.select("table").get(1).attr("bgcolor", "#f4f36f");
Log.d(Tag, data.toString());
Log.d(Tag, data.text());
Log.d(Tag, "creating intent...");
Intent broadcastIntent = new Intent();
Log.d(Tag, "setting action...");
broadcastIntent.setAction(ACTION_RCV_MESSAGE);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
broadcastIntent.putExtra("OUTPUT", data.toString());
Log.d(Tag, "sending broadcast: "+(i++));
sendBroadcast(broadcastIntent);
Thread.sleep(30*1000);
}
}
catch(StackOverflowError e){
Log.d(Tag, "in StackOverflowError block...");
Log.d(Tag, "creating intent...");
Intent broadcastIntent = new Intent();
Log.d(Tag, "setting action...");
broadcastIntent.setAction(ACTION_RCV_MESSAGE);
broadcastIntent.addCategory(Intent.CATEGORY_DEFAULT);
broadcastIntent.putExtra("OUTPUT", "系統忙線中, 請稍後再試");
Log.d(Tag, "sending broadcast...");
sendBroadcast(broadcastIntent);
}
catch(Exception e){
Log.d(Tag, "in catch Exception block...");
onHandleIntent(intent);
}
}
}
问题是,我陷入了这个循环。即使我杀死主要活动然后返回它以输入新输入,并且 IntentService 仍然基于旧输入返回。
我需要知道如何每 30 秒从 URL 更新一次而不会卡住。谢谢!