2017-02-17 42 views
1

我正在尋找一種解決方案,以在Android API 17(Android 4.2)中的特定時間間隔內獲取用戶位置以及手機被鎖定時的位置。手機鎖定時獲取用戶在Android中的位置

我已經嘗試了一些不同的代碼,檢查了很多教程並在網上幾乎所有地方都進行了搜索。解決方案可能在那裏,但我認爲這是Android開發和解釋不同的正確解決方案和方法缺乏經驗的組合。

起初我有一些非常基本的代碼,當屏幕打開時它工作得很好。即使在後臺,該位置也得到了更新(因爲我可以通過Toast消息檢查經度和緯度)。 我用一個處理器可以這樣做:

public void locationRunnable() { 
    final Handler locationHandler = new Handler(); 
    final int distanceDelay = 5000; // milliseconds 

    locationHandler.postDelayed(new Runnable(){ 
     public void run() { 
      // code 
      mMap.clear(); 

      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; 
      } 

      mMap.setMyLocationEnabled(true); 
      mMap.setBuildingsEnabled(true); 
      mMap.getUiSettings().setMyLocationButtonEnabled(false); 

      LocationManager locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE); 
      Criteria criteria = new Criteria(); 
      String provider = locationManager.getBestProvider(criteria, true); 

      myLocation = locationManager.getLastKnownLocation(provider); 

      if (myLocation != null) { 
       latitudeCurrentPosition = myLocation.getLatitude(); 
       longitudeCurrentPosition = myLocation.getLongitude(); 
      } 

      currentPattern = shortTest; 
      Notification.Builder notificationBuilderChecking = new Notification.Builder(this) 
        .setSmallIcon(R.mipmap.ic_launcher) 
        .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher)) 
        .setContentTitle("Test app") 
        .setAutoCancel(true) 
        .setOnlyAlertOnce(false) 
        .setContentText("Getting location!") 
        .setPriority(Notification.PRIORITY_MAX) 
        .setLights(0xffffffff, 200, 200) 
        .setVibrate(currentPattern); 

      Notification notification2 = notificationBuilderChecking.build(); 

      NotificationManager notificationMngr2 = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
      notificationMngr2.notify(NOTIFICATION_ID, notification2); 

      locationHandler.postDelayed(this, distanceDelay); 
     } 

    }, distanceDelay); 

} 

這只是一個片斷和目的是在後臺,當屏幕被鎖定,這將每10秒循環。它確實如此。即使手機被鎖定,但只有約3次。 3次後,計時器上升,手機振動頻率較低(方式中打盹功能?)。 此外,手機確實振動,但位置未更新。當我在前臺使用應用程序解鎖手機時,位置仍然位於鎖定手機的位置。一段時間後(10秒)它會更新。我在地圖上用一個標記來檢查。

再次說明:它在手機解鎖時有效。

現在我試圖使用服務,服務(意圖服務),或廣播接收器,並開始一個新的線程,但我不知道如何和沒有工作。

一些最後的代碼,我有包含一個不正常的廣播接收器和最新的代碼包含一個AlarmManager:

public void getLocation(Context context) { 

    AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); 
    Intent intent = new Intent(context, AlarmIntent.class); 
    PendingIntent pi = PendingIntent.getBroadcast(context, 0, intent, 0); 
    //After after 30 seconds 
    am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, System.currentTimeMillis(), 10000, pi); 


    context.getSystemService(Context.CONNECTIVITY_SERVICE); 

    mMap.clear(); 

    mMap.setMyLocationEnabled(true); 
    mMap.getUiSettings().setMyLocationButtonEnabled(false); 

    LocationManager locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE); 
    Criteria criteria = new Criteria(); 
    String provider = locationManager.getBestProvider(criteria, true); 

    myLocation = locationManager.getLastKnownLocation(provider); 

    latitudeCurrentPosition = myLocation.getLatitude(); 
    longitudeCurrentPosition = myLocation.getLongitude(); 

    LatLng latLngCurrent = new LatLng(latitudeCurrentPosition, longitudeCurrentPosition); 

    mMap.moveCamera(CameraUpdateFactory.newLatLng(latLngCurrent)); 
    mMap.animateCamera(CameraUpdateFactory.zoomTo(distZoom)); 

    currentPattern = shortTest; 
    showNotification(context); 

    mHereIAm = mMap.addMarker(new MarkerOptions() 
      .position(new LatLng(latitudeCurrentPosition, longitudeCurrentPosition)) 
      .title(weAreHere) 
      .draggable(false) 
      .icon(BitmapDescriptorFactory 
        .fromResource(R.drawable.marker_iconv3))); 
    mHereIAm.setTag(0); 
    mHereIAm.showInfoWindow(); 
} 

AndroidManifest權限:

<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 
<uses-permission android:name="android.permission.VIBRATE" /> 
<uses-permission android:name="android.permission.WAKE_LOCK" /> 
<uses-permission android:name="com.android.alarm.permission.SET_ALARM" /> 

但在長期的10000, Android Studio告訴我「Android 5.1的價值將被強制升至60000;不要依賴這個......」等。所以AlarmManager也沒有用。 隨着最後的代碼,我的應用程序甚至不再運行。

但仍然:震動和東西仍然發生,但位置更新不。

總之: 我需要一些基本的(至少,我認爲它不是那麼難,因爲唯一的問題是,它不能在屏幕鎖定時工作)代碼,更新我的位置確定的,可變的區間。

也許我必須使用Handler/Runnable,啓動一個新的Thread,使用Service或Broadcast Receiver。也許一個AlarmManager也可以工作,但我不知道如何以及使用哪一個。

這是我的第一篇文章。如果有什麼錯過或者你們需要更多信息,請詢問。我試圖儘可能精確,而不用太多開銷。

編輯01 我可以使用Job Service嗎? - 我已將API更新至21,因此我可以使用此服務,但我不知道這是我尋找的正確解決方案嗎?有一些偉大的教程使用它。

編輯02 讓我用更少的開銷更清楚:我在尋找一個解決方案來獲得當設備被鎖定的用戶的當前位置:有一個API,一個服務,一個IntentService,一個BroadcastReceiver。 .. - 每個教程都告訴我不同​​的東西,即使在Stack Overflow,我也遇到了找到正確解決方案的麻煩。 我能夠使用服務以及意圖服務,但由於某些錯誤,我無法請求任何位置更新,例如: java.lang.RuntimeException: Unable to start activity ComponentInfo{com.name.name/com.name.name.MapsActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void com.google.android.gms.maps.GoogleMap.setMyLocationEnabled(b‌​oolean)' on a null object reference - 正在搜索此錯誤的解決方案,稍後再提供另一個錯誤,並且,然後......我陷入了一個錯誤循環和大量不必要的代碼。

我希望有一個簡單的方法來獲取用戶的位置,你們可以幫助我。再次感謝。

編輯03 我已經按照上this tutorial指令和位置檢查。請看下面的代碼:

public class LocationService extends Service implements LocationListener {

private final Context mContext; 

// flag for GPS status 
boolean isGPSEnabled = false; 

// flag for network status 
boolean isNetworkEnabled = false; 

// flag for GPS status 
boolean canGetLocation = false; 

Location location; // location 
double latitude; // latitude 
double longitude; // longitude 

// The minimum distance to change Updates in meters 
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters 

// The minimum time between updates in milliseconds 
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute 

// Declaring a Location Manager 
protected LocationManager locationManager; 

public LocationService(Context context) { 
    this.mContext = context; 
    getLocation(); 
} 

public Location getLocation() { 
    try { 
     locationManager = (LocationManager) mContext 
       .getSystemService(LOCATION_SERVICE); 

     // getting GPS status 
     isGPSEnabled = locationManager 
       .isProviderEnabled(LocationManager.GPS_PROVIDER); 

     // getting network status 
     //isNetworkEnabled = locationManager 
     //  .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

     if (!isGPSEnabled && !isNetworkEnabled) { 
      // no network provider is enabled 
     } else { 
      this.canGetLocation = true; 
      // First get location from Network Provider 
      if (isNetworkEnabled) { 
       locationManager.requestLocationUpdates(
         LocationManager.NETWORK_PROVIDER, 
         MIN_TIME_BW_UPDATES, 
         MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
       Log.d("Network", "Network"); 
       if (locationManager != null) { 
        location = locationManager 
          .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        if (location != null) { 
         latitude = location.getLatitude(); 
         longitude = location.getLongitude(); 
        } 
       } 
      } 
      // if GPS Enabled get lat/long using GPS Services 
      if (isGPSEnabled) { 
       if (location == null) { 
        locationManager.requestLocationUpdates(
          LocationManager.GPS_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("GPS Enabled", "GPS Enabled"); 
        if (locationManager != null) { 
         location = locationManager 
           .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
         if (location != null) { 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
         } 
        } 
       } 
      } 
     } 

    } catch (Exception e) { 
     e.printStackTrace(); 
    } 

    return location; 
} 

/** 
* Stop using GPS listener 
* Calling this function will stop using GPS in your app 
* */ 
public void stopUsingGPS(){ 
    if(locationManager != null){ 
     locationManager.removeUpdates(LocationService.this); 
    } 
} 

/** 
* Function to get latitude 
* */ 
public double getLatitude(){ 
    if(location != null){ 
     latitude = location.getLatitude(); 
    } 

    // return latitude 
    return latitude; 
} 

/** 
* Function to get longitude 
* */ 
public double getLongitude(){ 
    if(location != null){ 
     longitude = location.getLongitude(); 
    } 

    // return longitude 
    return longitude; 
} 

/** 
* Function to check GPS/wifi enabled 
* @return boolean 
* */ 
public boolean canGetLocation() { 
    return this.canGetLocation; 
} 

/** 
* Function to show settings alert dialog 
* On pressing Settings button will lauch Settings Options 
* */ 
public void showSettingsAlert(){ 
    AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); 

    // Setting Dialog Title 
    alertDialog.setTitle("GPS is settings"); 

    // Setting Dialog Message 
    alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?"); 

    // On pressing Settings button 
    alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog,int which) { 
      Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
      mContext.startActivity(intent); 
     } 
    }); 

    // on pressing cancel button 
    alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
     public void onClick(DialogInterface dialog, int which) { 
      dialog.cancel(); 
     } 
    }); 

    // Showing Alert Message 
    alertDialog.show(); 
} 

@Override 
public void onLocationChanged(Location location) { 
} 

@Override 
public void onProviderDisabled(String provider) { 
} 

@Override 
public void onProviderEnabled(String provider) { 
} 

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

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

}

我已經禁用網絡位置,並只允許GPS位置進行測試 - 測試的兩種。

而且我MapsActivity:

public void getLocation(){ 
    gps = new LocationService(MapsActivity.this); 
    if(gps.canGetLocation()) { // gps enabled} // return boolean true/false 
     latitudeCurrentPosition = gps.getLatitude(); // returns latitude 
     longitudeCurrentPosition = gps.getLongitude(); // returns longitude 

     latLngCurrent = new LatLng(latitudeCurrentPosition, longitudeCurrentPosition); 

     Toast toastLatCur = makeText(getApplicationContext(), "Lat Current: " + latitudeCurrentPosition + "" ,Toast.LENGTH_SHORT); 
     toastLatCur.show(); 

     Toast toastLongCur = makeText(getApplicationContext(), "Long Current: " + longitudeCurrentPosition + "" ,Toast.LENGTH_SHORT); 
     toastLongCur.show(); 
    } 

    else { 
     gps.showSettingsAlert(); 
    } 

    if(goToLocation){ 
     mMap.moveCamera(CameraUpdateFactory.newLatLng(latLngCurrent)); 
     goToLocation = false; 

     if(firstStart){ 
      mMap.animateCamera(CameraUpdateFactory.zoomTo(distZoom)); 
      firstStart = false; 
     } 
    } 

    vibrateNotification(); 
} 

當屏幕被鎖定,手機振動,我在vibrateNotificatoin()告訴 - 完美的作品每10秒。但位置不會更新!所以服務不是解決這個問題的正確方法。幫幫我!

回答

1

您應該使用服務來執行即使應用程序未運行時也需要完成的任務。試一下。

+0

我現在就試試這個。 –

+0

IntentService或常規服務? IntentService給我:'java.lang.RuntimeException:無法啓動活動ComponentInfo {com.name.name/com.name.name.MapsActivity}:java.lang.NullPointerException:試圖調用虛擬方法'void com.google。 android.gms.maps.GoogleMap.setMyLocationEnabled(布爾)'空對象引用' –

+0

@ k.schaaf嘗試常規的。 –

0

所以,我跟着一些教程和搜索,並試圖更多地找出解決辦法:

  1. 創建一個新的服務:
package com.name.name; 


import android.app.AlertDialog; 
import android.app.Notification; 
import android.app.NotificationManager; 
import android.app.Service; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.graphics.BitmapFactory; 
import android.location.Location; 
import android.location.LocationListener; 
import android.location.LocationManager; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.provider.Settings; 
import android.util.Log; 

import static com.name.name.MapsActivity.NOTIFICATION_ID; 

public class LocationService extends Service implements LocationListener { 

    private final Context mContext; 

    // flag for GPS status 
    boolean isGPSEnabled = false; 

    // flag for network status 
    boolean isNetworkEnabled = false; 

    // flag for GPS status 
    boolean canGetLocation = false; 

    Location location; // location 
    double latitude; // latitude 
    double longitude; // longitude 

    // The minimum distance to change Updates in meters 
    private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; // 10 meters 

    // The minimum time between updates in milliseconds 
    private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1 minute 

    // Declaring a Location Manager 
    protected LocationManager locationManager; 

    public LocationService(Context context) { 
     this.mContext = context; 
     getLocation(); 
    } 

    public Location getLocation() { 
     try { 
      locationManager = (LocationManager) mContext 
        .getSystemService(LOCATION_SERVICE); 

      // getting GPS status 
      isGPSEnabled = locationManager 
        .isProviderEnabled(LocationManager.GPS_PROVIDER); 

      // getting network status 
      isNetworkEnabled = locationManager 
        .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

      if (!isGPSEnabled && !isNetworkEnabled) { 
       // no network provider is enabled 
      } else { 
       this.canGetLocation = true; 
       // First get location from Network Provider 
       if (isNetworkEnabled) { 
        locationManager.requestLocationUpdates(
          LocationManager.NETWORK_PROVIDER, 
          MIN_TIME_BW_UPDATES, 
          MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
        Log.d("Network", "Network"); 
        if (locationManager != null) { 
         location = locationManager 
           .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
         if (location != null) { 
          latitude = location.getLatitude(); 
          longitude = location.getLongitude(); 
         } 
        } 
       } 
       // if GPS Enabled get lat/long using GPS Services 
       if (isGPSEnabled) { 
        if (location == null) { 
         locationManager.requestLocationUpdates(
           LocationManager.GPS_PROVIDER, 
           MIN_TIME_BW_UPDATES, 
           MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
         Log.d("GPS Enabled", "GPS Enabled"); 
         if (locationManager != null) { 
          location = locationManager 
            .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
          if (location != null) { 
           latitude = location.getLatitude(); 
           longitude = location.getLongitude(); 
          } 
         } 
        } 
       } 
      } 

     } catch (Exception e) { 
      e.printStackTrace(); 
     } 

     return location; 
    } 

    /** 
    * Stop using GPS listener 
    * Calling this function will stop using GPS in your app 
    * */ 
    public void stopUsingGPS(){ 
     if(locationManager != null){ 
      locationManager.removeUpdates(LocationService.this); 
     } 
    } 

    /** 
    * Function to get latitude 
    * */ 
    public double getLatitude(){ 
     if(location != null){ 
      latitude = location.getLatitude(); 
     } 

     // return latitude 
     return latitude; 
    } 

    /** 
    * Function to get longitude 
    * */ 
    public double getLongitude(){ 
     if(location != null){ 
      longitude = location.getLongitude(); 
     } 

     // return longitude 
     return longitude; 
    } 

    /** 
    * Function to check GPS/wifi enabled 
    * @return boolean 
    * */ 
    public boolean canGetLocation() { 
     return this.canGetLocation; 
    } 

    /** 
    * Function to show settings alert dialog 
    * On pressing Settings button will lauch Settings Options 
    * */ 
    public void showSettingsAlert(){ 
     AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); 

     // Setting Dialog Title 
     alertDialog.setTitle("GPS is settings"); 

     // Setting Dialog Message 
     alertDialog.setMessage("GPS is not enabled. Do you want to go to settings menu?"); 

     // On pressing Settings button 
     alertDialog.setPositiveButton("Settings", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog,int which) { 
       Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
       mContext.startActivity(intent); 
      } 
     }); 

     // on pressing cancel button 
     alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() { 
      public void onClick(DialogInterface dialog, int which) { 
       dialog.cancel(); 
      } 
     }); 

     // Showing Alert Message 
     alertDialog.show(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 
    } 

    @Override 
    public void onProviderDisabled(String provider) { 
    } 

    @Override 
    public void onProviderEnabled(String provider) { 
    } 

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

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

} 
  • 每次運行此服務時,都要使用Handler和Runnable並使用Wakelock:
    • 在OnCreate中:
  • PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE); 
        wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, 
          "MyWakelockTag"); 
    
    • 做的東西與獲得性數據形成LocationService。
    • 啓動此功能時,你需要的數據和做的事情與它:

    公共無效startDoingStuffWithLocationData(){

       final Runnable runnable= new Runnable() { 
            public void run() { 
             // do stuff here 
             getLocation(); 
             } 
    
             else { 
              handler.postDelayed(this, 10000); 
             } 
            } 
           }; 
           runnable.run(); 
          } 
        } 
    
    • 獲取從服務中的數據:

    公共無效的getLocation(){

    wakeLock.acquire(); 
    
        gps = new LocationService(MapsActivity.this); 
        if(gps.canGetLocation()) { // gps enabled} // return boolean true/false 
         latitudeCurrentPosition = gps.getLatitude(); // returns latitude 
         longitudeCurrentPosition = gps.getLongitude(); // returns longitude 
    
         latLngCurrent = new LatLng(latitudeCurrentPosition, longitudeCurrentPosition); 
        } 
    
        else { 
         gps.showSettingsAlert(); 
        } 
    
        wakeLock.release(); 
    } 
    

    請務必使用release()函數來結束喚醒鎖定,以節省電池。