0

我正在使用Location偵聽器服務來每隔幾秒更新用戶的當前位置。我還使用WakeLock使聽衆在後臺工作。現在一切正常,但我無法停止Location偵聽器。即使應用程序強制關閉,偵聽器也會將用戶位置更新爲數據庫。如何停止位置偵聽器服務? (現在不停止)

位置監聽器:

import android.app.Service; 
import android.content.Context; 
import android.content.Intent; 
import android.content.pm.PackageManager; 
import android.location.Location; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.os.PowerManager; 
import android.support.v4.app.ActivityCompat; 
import android.util.Log; 
import android.widget.Toast; 

import com.google.android.gms.maps.model.LatLng; 

public class MyLocationService extends Service { 
private static final String TAG = "MyLocationService"; 
private LocationManager mLocationManager = null; 
private static final int LOCATION_INTERVAL = 3000; 
private static final float LOCATION_DISTANCE = 0f; 
Context context = this; 
PowerManager.WakeLock wakeLock; 
public int e=0; 

LocationListener[] mLocationListeners = new LocationListener[]{ 
     new LocationListener(LocationManager.GPS_PROVIDER), 
     new LocationListener(LocationManager.NETWORK_PROVIDER) 
}; 

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

@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 
    Log.e(TAG, "onStartCommand"); 
    super.onStartCommand(intent, flags, startId); 
    Toast.makeText(this, "MyService Started.", Toast.LENGTH_SHORT).show(); 
    return START_STICKY; 
} 

@Override 
public void onCreate() { 
    Log.e(TAG, "onCreate"); 
    initializeLocationManager(); 
    PowerManager mgr = (PowerManager)context.getSystemService(Context.POWER_SERVICE); 
    wakeLock= mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock"); 
    wakeLock.acquire(); 
    try { 
     mLocationManager.requestLocationUpdates(
       LocationManager.NETWORK_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, 
       mLocationListeners[1]); 
    } catch (java.lang.SecurityException ex) { 
     Log.i(TAG, "fail to request location update, ignore", ex); 
    } catch (IllegalArgumentException ex) { 
     Log.d(TAG, "network provider does not exist, " + ex.getMessage()); 
    } 
    try { 
     mLocationManager.requestLocationUpdates(
       LocationManager.GPS_PROVIDER, LOCATION_INTERVAL, LOCATION_DISTANCE, 
       mLocationListeners[0]); 
    } catch (java.lang.SecurityException ex) { 
     Log.i(TAG, "fail to request location update, ignore", ex); 
    } catch (IllegalArgumentException ex) { 
     Log.d(TAG, "gps provider does not exist " + ex.getMessage()); 
    } 
} 

@Override 
public void onDestroy() { 
    Log.e(TAG, "onDestroy"); 
    wakeLock.release(); 
    super.onDestroy(); 


    if (mLocationManager != null) { 
     for (int i = 0; i < mLocationListeners.length; i++) { 
      try { 
       if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) { 
        // TODO: Consider calling 
        // ActivityCompat#requestPermissions 
        // here to request the missing permissions, and then overriding 
        // public void onRequestPermissionsResult(int requestCode, String[] permissions, 
        //           int[] grantResults) 
        // to handle the case where the user grants the permission. See the documentation 
        // for ActivityCompat#requestPermissions for more details. 
        return; 
       } 
       mLocationManager.removeUpdates(mLocationListeners[i]); 
      } catch (Exception ex) { 
       Log.i(TAG, "fail to remove location listners, ignore", ex); 
      } 
     } 
    } 
} 

private void initializeLocationManager() { 
    Log.e(TAG, "initializeLocationManager"); 
    if (mLocationManager == null) { 
     mLocationManager = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE); 
    } 
} 

// create LocationListener class to get location updates 
private class LocationListener implements android.location.LocationListener 
{ 
    Location mLastLocation; 
    double latitude; 
    double longitude; 
    LatLng latLngcurrent; 


    public LocationListener(String provider) 
    { 
     Log.e(TAG, "LocationListener " + provider); 
     mLastLocation = new Location(provider); 
    } 

    @Override 
    public void onLocationChanged(Location location) 
    { 
     Log.e(TAG, "onLocationChanged: " + location); 
     mLastLocation.set(location); 
     latitude = location.getLatitude(); 
     longitude = location.getLongitude(); 
     Store.latu=latitude; 
     Store.longu=longitude; 
     latLngcurrent = new LatLng(location.getLatitude(), location.getLongitude()); 
     Toast.makeText(context,"Location " + String.valueOf(e), Toast.LENGTH_SHORT).show(); 
     e++; 
     Toast.makeText(MyLocationService.this,Store.latu+" "+Store.longu, Toast.LENGTH_SHORT).show(); 

    } 

    @Override 
    public void onProviderDisabled(String provider) 
    { 
     Log.e(TAG, "onProviderDisabled: " + provider); 
    } 

    @Override 
    public void onProviderEnabled(String provider) 
    { 
     Log.e(TAG, "onProviderEnabled: " + provider); 
    } 

    @Override 
    public void onStatusChanged(String provider, int status, Bundle extras) 
    { 
     Log.e(TAG, "onStatusChanged: " + provider); 
    } 
} 
} 

啓動服務意向:(從mainactivity)

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_maps); 


    Intent serviceIntent = new Intent(context , MyLocationService.class); 
    context.startService(serviceIntent ); 



    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { 
     checkLocationPermission(); 
    } 
    if (!isGooglePlayServicesAvailable()) { 
     finish(); 
    } else { 
     Log.d("onCreate", "Google Play Services available."); 
    } 
    SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map); 
    mapFragment.getMapAsync(this); 
} 

停止意圖:(從mainactivity)

private class LogOutTimerTask extends TimerTask 
{ 
    @Override 
    public void run() 
    { 
     Intent i = new Intent(MapsActivity.this, Login.class); 
     i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); 
     startActivity(i); 
     Intent intent = new Intent(MapsActivity.this, MyLocationService.class); 
     stopService(intent); 
     finish(); 
    } 
} 

停止意圖在用戶註銷時調用,現在服務類中的onDestroy()方法被調用,但它不停止進程。當應用程序被強制關閉時,onDestroy()甚至不會被調用。在這兩種情況下,過程都會恢復並不斷更新值到DB.Thanks提前。

+0

是'removeUpdates()'被調用?或者由於權限'IF'返回該方法?雖然,爲什麼你在刪除監聽器時檢查權限?這應該是'initializeLocationManager()'或者''' – Yazan

+0

我還沒有檢查removeupdates()是否被調用。我已經添加了權限,因爲android studio正在推薦我。 @Yazan –

+1

我懷疑這個地方是不是很好的請求一個許可(同時銷燬服務?!),但是,它不是很好放置在循環中,你可以要求它一次(循環之前)也嘗試添加在'removeUpdates()'之前的日誌'Log.i(TAG,「移除監聽者...」);'看看它是否出現在logcat中 – Yazan

回答

1

解決方案: 我終於找到了解決方案。正如@ Yazan說我已經從onDestroy()方法中刪除了權限,這有助於服務在用戶註銷時手動停止。並且當應用程序強制關閉時停止服務,在使用標籤的清單中也添加此行。

段:

<service android:name=".MyLocationService" 
android:stopWithTask="true"></service> 

當我們強制關閉應用程序stopWithTask將停止服務和LocationListener的也將停止。

here是文檔。添加後,我的應用程序正常工作。