如下,发现应用好像陷入了死循环,程序总是无响应无响应的。 求大神指点!

new Timer().schedule(new TimerTask() {
@Override
public void run() {
// TODO Auto-generated method stub
Log.i("aaa", "hello");
TelephonyManager tm = (TelephonyManager)getBaseContext()
.getSystemService(Context.TELEPHONY_SERVICE);
deviceid = tm.getDeviceId();
username = SysUtil.loginname;
SimpleDateFormat sDateFormat = new SimpleDateFormat("yyyy-MM-dd");
SimpleDateFormat stimeFormat = new SimpleDateFormat("HH:mm:ss");
date = sDateFormat.format(new java.util.Date());
time = stimeFormat.format(new java.util.Date());
//发送
message = username + ","
+ deviceid + ","
+ date + ","
+ time + ","
+ preferences.getString("longtitude", "fail") + ","
+ preferences.getString("latitude", "fail") + ","
+ preferences.getString("accelerator", "fail,fail,fail") + ","
+ preferences.getString("magnetic", "fail,fail,fail") + ","
+ preferences.getString("pressure", "0") + ","
+ preferences.getString("light", "0") + ","
+ preferences.getString("wifi", "fail,fail,fail");
try {
String s = SysUtil.client.sendMessage(message);
if(s.equals("fail"))
{
editor.putString("last" + SysUtil.cur++, message);
editor.commit();
}
if(s.equals("login"))
{
SysUtil.pushlogin(getApplicationContext());
editor.putString("last" + SysUtil.cur++, message);
editor.commit();
}
if(s.equals("success"))
{
SysUtil.cur--;
for(; SysUtil.cur > 0; SysUtil.cur--)
{
preferences.getString("last" + SysUtil.cur, message);
s = SysUtil.client.sendMessage(message);
if(!s.equals("success"))
break;
}
}
} catch (Exception e) {
// TODO Auto-generated catch block
editor.putString("last" + SysUtil.cur++, message);
editor.commit();
}
}
}, 0, SysUtil.frequncy * 300);
}
目前我是用Timer来实现每隔一段时间执行一次run()里面的程序
但是后来功能需要,发现要动态的改变间隔时间,这一点上timer好像不能实现。

后来改成了while(true)循环里面加Thread.sleep(/*间隔时间*/),try/catch异常

绝地无双
浏览 116回答 2
2回答

潇潇雨雨

我觉得吧你暂停的时候应该吧TIMER.CANCEL()掉,也就是退出TIMER,等恢复的时候再重新调用TIMER如果时间是变动的,那么你就不要用TIMER,自己NEW 一个THREAD然后在THREAD里设置一个标志变量,可以再外面访问的,用它来控制线程的退出,里面再调用this.sleep(),不能再主线程里直接SLEEP,那样程序会全停掉

慕田峪9158850

像这类定时的工作android上建议使用AlarmManager,里面可以完成timer的所有功能,而且更简单
打开App,查看更多内容
随时随地看视频慕课网APP