可能重复:
Can’t create handler inside thread that has not called Looper.prepare() inside AsyncTask for ProgressDialog无法在线程内部创建处理程序。我如何使用Looper.prepare()?
我开发一个Android的服务,尝试获取设备的IP地址每x时间,它comunicate到服务器。 我使用:
的Netbeans 7.2
Android SDK中
谷歌Android的API 8
SQLite的
我知道有与此相同的问题的一些问题,但他们都不给我解决我的问题。正如你可以在我的代码中看到的,我没有试图访问服务主线程的UI(当然,我尝试了,但是在我评论这一行后,错误仍然是一样的)。另一方面,我使用AsyncTask,我认为这是实现它的合适方法。
这是我服务的主要部分:
public class ArsosService extends Service {
private NotificationManager mNM;
private final Messenger mMessenger = new Messenger(new IncomingHandler());
protected DatabaseUtil dbu = null;
@Override
public void onCreate() {
mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
try {
dbu = DatabaseUtility.getInstance(this);
} catch (IOException ex) {
Log.e("Service", ex);
}
Timer timer = new Timer();
timer.schedule(new Checks(), 0, 15000);
}
private class Checks extends TimerTask {
@Override
public void run() {
CheckIpAddress_Task checkIp = new CheckIpAddress_Task();
checkIp.execute();
}
}
// Other methods
private class CheckIpAddress_Task extends AsyncTask<Void, Void, Integer> {
@Override
protected Integer doInBackground(Void... arg0) {
String ipLocal = getLocalIpAddress();
String text = null;
// ipLocal==null means there is no available connection, so we do nothing.
if (ipLocal != null) {
String ipDb = dbu.getLastIP(); // we get the IP saved in the DB.
if (ipDb == null) {
dbu.addProperty("IP", ipLocal); // we save the IP in the DB.
} else if (!ipLocal.equals(ipDb)) {
dbu.setProperty("IP", ipLocal); // we update the IP in the DB.
}
}
if (text != null) {
//showNotification(1, text, ipLocal);
}
return 0;
}
private String getLocalIpAddress() {
String result = null;
// Irrelevant code
return result;
}
}
}
我认为这个问题可能与线程,但我看不到的地方。任何帮助将不胜感激。
编辑:尽管我接受了其中一个正确的答案,或许正因为此,我一直在寻找更多关于它的信息。我遇到了this page我想与大家分享一些需要了解此问题的人。它的作者Tejas Lagvankar以一种非常明确和可理解的方式解释了关于线程,操作符和处理程序的所有信息。
首先,我很抱歉没有回答过。感谢您的时间和答案。我遵循你的指示,而且效果很好。但是,我不太确定这是否是一种非常正统的方式。我的方法现在看起来是这样的: 私有类检查扩展的TimerTask { @覆盖 公共无效的run(){ h.post(新的Runnable(){ 公共无效的run(){ CheckIpAddress_Task checkIp =新CheckIpAddress_Task() ; checkIp.execute(); } }); } } 正如我所说,这个字,但它是正确的吗? – Julio