我正在使用后台服务来获取特定时间间隔内的位置坐标并对数据库执行更新操作。我已经搜索了许多类似的问题,但没有帮助。
我在服务中创建了线程来执行此操作。 但是当服务未更新位置时,我陷入困境。我发现在线程中没有调用方法“requestLocationUpdates()”。事实上,我在线程中使用Toast方法也无法正常工作。
问题可能在于传入上述两种方法的“Context”参数。但我无法更正此代码。
主要关注点是从服务中的线程获取准确的位置并将其更新到服务器。考虑这部分,请告诉我正确的代码或任何其他来源以更好的方式说明相同的功能。这是我的代码......
public class IcareService extends Service implements LocationListener
{
private Handler mUserLocationHandler = null;
Thread triggerService;
LocationManager lm;
Criteria criteria;
String provider,lat,lon,rid;
@Override
public void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
Toast.makeText(this, "Stopping Service and so thread...", Toast.LENGTH_SHORT).show();
mUserLocationHandler.getLooper().quit();
}
@Override
public IBinder onBind(Intent intent)
{
//Not implemented...this sample is only for starting and stopping services.
//Service binding will be covered in another tutorial
return null;
}
@Override
public void onCreate()
{
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
super.onStartCommand(intent, flags, startId);
//Announcement about starting
Toast.makeText(this, "Starting Service...", Toast.LENGTH_SHORT).show();
addLocationListener();
return START_STICKY;
}
private void addLocationListener()
{
triggerService = new Thread(new Runnable(){
public void run(){
try{
Looper.prepare();//Initialise the current thread as a looper.
mUserLocationHandler = new Handler();
lm = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
// Creating a criteria object to retrieve provider
Criteria c = new Criteria();
criteria.setAccuracy(Criteria.ACCURACY_COARSE);
// Getting the name of the best provider
final String PROVIDER = lm.getBestProvider(c, true);
//This 2 below statement not executing...
lm.requestLocationUpdates(PROVIDER, 7000, 5, IcareService.this);
Toast.makeText(IcareService.this, "Updating Location...", Toast.LENGTH_SHORT).show();
Thread.sleep(7000);
Looper.loop();
}catch(Exception ex){
ex.printStackTrace();
}
}
}, "LocationThreadicare");
triggerService.start();
}
@Override
public void onLocationChanged(Location location) {
// Getting latitude of the current location
double latitude = location.getLatitude();
lat = Double.toString(latitude);
// Getting longitude of the current location
double longitude = location.getLongitude();
lon= Double.toString(longitude);
Toast.makeText(this, "Gt loc nw sendng to srvr", Toast.LENGTH_SHORT).show();
SendtoServer();
}
@Override
public void onProviderDisabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onProviderEnabled(String provider) {
// TODO Auto-generated method stub
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
// TODO Auto-generated method stub
}
SendtoServer(){
.............}
}
答案 0 :(得分:0)
不要使用Toast进行调试(顺便说一句,它需要在UI线程上运行,a.k.a。主线程),使用
Log.d("--------","\n\n-------"+Thread.currentThread().getName()+"\n\n");
将此类日志记录添加到onCreate()
/ onDestroy()
和感兴趣的地方,你会看到会发生什么。
使用adb logcat
查看日志。