我有一个按钮,点击后会显示您的位置,将其与确切的固定位置进行比较,并说明您与该位置之间有多少米,我想要做的就是点击进入服务时执行操作在应用程序启动时运行并一直运行直到应用程序关闭。这是我的按钮代码
@Override
public void onClick(View arg0) {
// create class object
gps = new GPSTracker(AndroidGPSTrackingActivity.this);
TextView status = (TextView) findViewById(R.id.status);
TextView where = (TextView) findViewById(R.id.where);
TextView greet = (TextView) findViewById(R.id.greet);
// check if GPS enabled
if (gps.canGetLocation()) {
double datapostLat = -26.106589;
double datapostLong = 28.015150;
double latitude = gps.getLatitude();
double longitude = gps.getLongitude();
// \n is for new line
Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
status.setText("YOUR LOCATION" + "\n" + "Latitude: " + latitude + "\n" + "Longitude: " + longitude);
try {
float[] results = new float[1];
Location.distanceBetween(latitude, longitude, datapostLat, datapostLong, results);
System.out.println(results[0]);
where.setText("You are: " + results[0] + " M" + " Away from Datapost");
// Toast.makeText(AndroidGPSTrackingActivity.this, ""+ results[0] +"", Toast.LENGTH_SHORT).show();
if(results[0]<50) {
greet.setText("Welcome to Datapost");
} else {
greet.setText("You are leaving Datapost");
}
} catch (Exception e) {
e.getStackTrace();
//for debugging
Toast.makeText(AndroidGPSTrackingActivity.this, "error: " + "\n" + e, Toast.LENGTH_SHORT).show();
}
} else {
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
简而言之,我需要用一个简单的服务代替这个按钮,这可能吗?
答案 0 :(得分:1)
好友〜
您最好的选择是IntentService
,它可以帮助您将操作卸载到后台运行的单独线程中。
您可以不断地从LocationProvider获取固定位置和最新位置之间的距离。然后,您可以通过LocalBroadcastManager
继续将结果发送到您的活动,并在主(UI)主题中更新您的UI。
参考:https://developer.android.com/training/run-background-service/index.html
答案 1 :(得分:0)
我认为你想要不断追踪位置,所以这应该有所帮助。
https://developer.android.com/training/location/receive-location-updates.html