Android 通过服务更新位置

Android 通过服务更新位置,android,service,location,Android,Service,Location,当我的应用程序关闭时,我试图在后台获取位置更新。我通过一个服务来尝试这个。当我的应用程序打开时,它工作正常,但当我关闭它时,服务似乎也关闭了 这就是我使用的代码: 主要活动: public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setConten

当我的应用程序关闭时,我试图在后台获取位置更新。我通过一个服务来尝试这个。当我的应用程序打开时,它工作正常,但当我关闭它时,服务似乎也关闭了

这就是我使用的代码:

主要活动:

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    Intent intent = new Intent(this, MyService.class);
    startService(intent);
}
我的服务:

public class MyService extends Service {

public static final String BROADCAST_ACTION = "Hello World";
private static final int TWO_MINUTES = 1000 * 60 * 2;
public LocationManager locationManager;
public MyLocationListener listener;
public Location previousBestLocation = null;
private String provider;


@Override
public void onCreate() {
super.onCreate();
intent = new Intent(BROADCAST_ACTION);      
}

@Override
public void onStart(Intent intent, int startId) {      
locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
listener = new MyLocationListener();    
provider = locationManager.getBestProvider(new Criteria(), false);
locationManager.requestLocationUpdates(provider, 0, 0, listener);
}

@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
super.onStartCommand(intent, flags, startId);       
return START_STICKY;
}

@Override
public IBinder onBind(Intent intent) {
return null;
}

protected boolean isBetterLocation(Location location, Location currentBestLocation) {
if (currentBestLocation == null) {
    // A new location is always better than no location
    return true;
}

// Check whether the new location fix is newer or older
long timeDelta = location.getTime() - currentBestLocation.getTime();
boolean isSignificantlyNewer = timeDelta > TWO_MINUTES;
boolean isSignificantlyOlder = timeDelta < -TWO_MINUTES;
boolean isNewer = timeDelta > 0;

// If it's been more than two minutes since the current location, use the new location
// because the user has likely moved
if (isSignificantlyNewer) {
    return true;
// If the new location is more than two minutes older, it must be worse
} else if (isSignificantlyOlder) {
    return false;
}

// Check whether the new location fix is more or less accurate
int accuracyDelta = (int) (location.getAccuracy() - currentBestLocation.getAccuracy());
boolean isLessAccurate = accuracyDelta > 0;
boolean isMoreAccurate = accuracyDelta < 0;
boolean isSignificantlyLessAccurate = accuracyDelta > 200;

// Check if the old and new location are from the same provider
boolean isFromSameProvider = isSameProvider(location.getProvider(),
        currentBestLocation.getProvider());

// Determine location quality using a combination of timeliness and accuracy
if (isMoreAccurate) {
    return true;
} else if (isNewer && !isLessAccurate) {
    return true;
} else if (isNewer && !isSignificantlyLessAccurate && isFromSameProvider) {
    return true;
}
return false;
}


@Override
public void onDestroy() {       
// handler.removeCallbacks(sendUpdatesToUI);     
super.onDestroy();
Log.v("STOP_SERVICE", "DONE");
locationManager.removeUpdates(listener);        
}   

public static Thread performOnBackgroundThread(final Runnable runnable) {
final Thread t = new Thread() {
    @Override
    public void run() {
        try {
            runnable.run();
        } finally {

        }
    }
};
t.start();
return t;
}


public class MyLocationListener implements LocationListener
{

public void onLocationChanged(final Location loc)
{
    Log.i("MyService", "Location changed");
    // do something  

    }                               
}

public void onProviderDisabled(String provider)
{
}


public void onProviderEnabled(String provider)
{
 }


public void onStatusChanged(String provider, int status, Bundle extras)
{

}
}
}
公共类MyService扩展服务{
公共静态最终字符串广播\u ACTION=“Hello World”;
私人静态最终整数两分钟=1000*60*2;
公共场所经理;
公共MyLocationListener;
公共位置previousBestLocation=null;
私有字符串提供者;
@凌驾
public void onCreate(){
super.onCreate();
意图=新意图(广播行动);
}
@凌驾
公共void onStart(Intent Intent,int startId){
locationManager=(locationManager)getSystemService(Context.LOCATION\u服务);
listener=新的MyLocationListener();
provider=locationManager.getBestProvider(新标准(),false);
locationManager.RequestLocationUpdate(提供程序、0、0、侦听器);
}
@凌驾
公共int onStartCommand(Intent Intent、int标志、int startId)
{
super.onStartCommand(intent、flags、startId);
返回开始时间;
}
@凌驾
公共IBinder onBind(意向){
返回null;
}
受保护的布尔值isBetterLocation(位置位置,位置currentBestLocation){
如果(currentBestLocation==null){
//新位置总比没有位置好
返回true;
}
//检查新的位置修复程序是较新的还是较旧的
long-timeDelta=location.getTime()-currentBestLocation.getTime();
布尔值isSignificantlyNewer=时间增量>两分钟;
布尔值Issignificantlolder=时间增量<-2_分钟;
布尔值isNewer=timeDelta>0;
//如果距离当前位置已超过两分钟,请使用新位置
//因为用户可能已经移动了
如果(非常重要){
返回true;
//如果新位置比原来的位置早两分钟以上,情况肯定会更糟
}else if(Issignificantlolder){
返回false;
}
//检查新的位置修复是否更精确
int accuracyDelta=(int)(location.getAccuracy()-currentBestLocation.getAccuracy());
布尔值IslesAccurate=accuracyDelta>0;
布尔值IsmorePrecision=精度偏差<0;
布尔值不太精确=精度偏差>200;
//检查新旧位置是否来自同一提供商
布尔值isFromSameProvider=isSameProvider(location.getProvider(),
currentBestLocation.getProvider());
//结合及时性和准确性确定定位质量
如果(更准确){
返回true;
}else if(isNewer&!islesAccurate){
返回true;
}else if(较新且不太准确且来自SameProvider){
返回true;
}
返回false;
}
@凌驾
公共无效onDestroy(){
//handler.removeCallbacks(sendUpdatesToUI);
super.ondestory();
Log.v(“停止服务”,“完成”);
locationManager.RemoveUpdate(侦听器);
}   
公共静态线程性能BackgroundThread(最终可运行可运行){
最终螺纹t=新螺纹(){
@凌驾
公开募捐{
试一试{
runnable.run();
}最后{
}
}
};
t、 start();
返回t;
}
公共类MyLocationListener实现LocationListener
{
位置更改后的公共无效(最终位置loc)
{
Log.i(“MyService”,“位置更改”);
//做点什么
}                               
}
公共无效onProviderDisabled(字符串提供程序)
{
}
公共无效onProviderEnabled(字符串提供程序)
{
}
public void onStatusChanged(字符串提供程序、int状态、Bundle extra)
{
}
}
}

尝试实现前台服务

前台服务将显示通知,并且在您需要之前不会停止

在您的服务中实现此代码段

Notification notification = new Notification(R.drawable.icon, getText(R.string.ticker_text),
        System.currentTimeMillis());
Intent notificationIntent = new Intent(this, ExampleActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getText(R.string.notification_title),
        getText(R.string.notification_message), pendingIntent);
startForeground(ONGOING_NOTIFICATION_ID, notification);

谢谢你的快速回复。我应该在哪里添加这个?在onCreate()方法中?很抱歉,答复太晚,您可以在onCreate()上执行此操作。