处理程序卡在Android服务的循环中
我目前正在尝试使用一项服务,通过GPS跟踪手机。为了让GPS更新坐标,我需要在服务中使用处理程序。现在的问题是,当我执行Handler.post时,它会陷入一个循环中,然后,它会完全忽略其余的服务代码 当我进行调试时,我发现处理程序在方法之间交换消息,但没有任何有用的结果,它只是在相同方法之间反复循环 以下是我的服务代码,其中包括处理程序:处理程序卡在Android服务的循环中,android,gps,android-service,handler,android-handler,Android,Gps,Android Service,Handler,Android Handler,我目前正在尝试使用一项服务,通过GPS跟踪手机。为了让GPS更新坐标,我需要在服务中使用处理程序。现在的问题是,当我执行Handler.post时,它会陷入一个循环中,然后,它会完全忽略其余的服务代码 当我进行调试时,我发现处理程序在方法之间交换消息,但没有任何有用的结果,它只是在相同方法之间反复循环 以下是我的服务代码,其中包括处理程序: public int onStartCommand(Intent intent, int flags, int startId) {
public int onStartCommand(Intent intent, int flags, int startId)
{
ctx = ServicioDeFondo.this;
mHandler = new Handler();
reportarGPS = new Thread(new Runnable() { public void run()
{
try
{
while(true)
{
mHandler.post(new Runnable() {
@Override
public void run() {
gps = new GPSTrack(ctx);
latitude = String.valueOf(gps.getLatitude());
longitude = String.valueOf(gps.getLongitude());
}
});
Thread.sleep(10000);
try {
new APISendClass().execute();
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
catch (Exception e)
{
//TODO Auto-generated catch block
e.printStackTrace();
}
} });
reportarGPS.start();
return START_STICKY;
}
我被困在这里一整天了,任何帮助都将不胜感激!通过您对问题的简要描述,很难理解预期的行为是什么。您没有解释
GPSTrack
和APISendClass
做什么以及它们是什么类型的对象。您声明“它卡在一个循环中”不清楚“它”是什么。使用while(true)
语句,线程将循环直到取消
请注意,Service
方法,例如onStartCommand()
在主线程上运行。这意味着您的Handler()
构造函数将处理程序与主线程相关联。您发布到该处理程序的可运行程序在主线程上运行。这就是你想要的吗
还要注意,通过stopSelf()
或Context.stopService()
停止服务不会终止线程。当不再需要线程时,您需要有代码来取消该线程。这通常在onDestroy()
中完成
我接受了您发布的代码,用日志语句替换了对未知对象的调用,并运行了它。logcat输出在“Get lat/long”和“APISendClass()”之间交替
Handler mHandler;
Context ctx;
Thread reportGPS;
public int onStartCommand(Intent intent, int flags, int startId){
Log.i("TEST", "onStartCommand()");
ctx = this;
// Service methods run on main thread.
// Handler constructor with no args associates Handler
// with current thread, which here is the main thread.
mHandler = new Handler();
reportGPS = new Thread(new Runnable() {
@Override
public void run() {
try {
while (true) {
mHandler.post(new Runnable() {
@Override
public void run() {
// This runnable is posted to the main thread.
// Is that what you intended?
//gps = new GPSTrack(ctx);
//latitude = String.valueOf(gps.getLatitude());
//longitude = String.valueOf(gps.getLongitude());
Log.i("TEST", "Get lat/long");
}
});
Thread.sleep(2000);
try {
//new APISendClass().execute();
Log.i("TEST", "APISendClass().execute()");
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
reportGPS.start();
return START_STICKY;
}