我正在使用后台服务来获取特定时间间隔内的位置坐标并对数据库执行更新操作。我已经搜索了许多类似的问题,但没有帮助。
我在服务中创建了线程来执行此操作。但是当服务没有更新位置时我被卡住了。我发现方法“requestLocationUpdates()”没有在线程中被调用。事实上,我在线程中使用了 Toast 方法,该方法也不起作用。
可能问题出在传递给上述两种方法的“上下文”参数中。但我无法更正此代码。
主要关注的是从服务中的线程获取准确的位置并将它们更新到服务器。考虑这部分,请向我展示正确的代码或以更好的方式说明相同功能的任何其他来源。这是我的代码...
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(){
.............}
}