2

我目前有一項服務,用於獲取用戶位置。我附加了很多活動,所以如果有任何活動需要獲取用戶的位置,他們只需調用此服務即可執行任務並將位置發送到活動。我面臨的問題是,在運行時請求許可的棉花糖條件下,我不知道如何完成這項工作。在這裏看到了一些關於堆棧溢出的例子,但它們主要針對活動而不是服務,我仍然無法弄清楚。 需要幫助搞清楚。下面是我的服務級別,並試圖找出它服務的Android運行時位置權限

public class GPSService extends Service implements LocationListener { 

// saving the context for later use 
private final Context mContext; 

// if GPS is enabled 
boolean isGPSEnabled = false; 
// if Network is enabled 
boolean isNetworkEnabled = false; 
// if Location co-ordinates are available using GPS or Network 
public boolean isLocationAvailable = false; 

// Location and co-ordinates coordinates 
Location mLocation; 
double mLatitude; 
double mLongitude; 

// Minimum time fluctuation for next update (in milliseconds) 
private static final long TIME = 300; 
// Minimum distance fluctuation for next update (in meters) 
private static final long DISTANCE = 20; 

// Declaring a Location Manager 
protected LocationManager mLocationManager; 

public GPSService(Context context) { 
    this.mContext = context; 
    mLocationManager = (LocationManager) mContext 
      .getSystemService(LOCATION_SERVICE); 

} 

/** 
* Returs the Location 
* 
* @return Location or null if no location is found 
*/ 
public Location getLocation() { 
    try { 

     // Getting GPS status 
     isGPSEnabled = mLocationManager 
       .isProviderEnabled(LocationManager.GPS_PROVIDER); 


     // If GPS enabled, get latitude/longitude using GPS Services 
     if (isGPSEnabled) { 
      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) { 

       // 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. 


       mLocationManager.requestLocationUpdates(
         LocationManager.GPS_PROVIDER, TIME, DISTANCE, this); 
       if (mLocationManager != null) { 
        mLocation = mLocationManager 
          .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
        if (mLocation != null) { 
         mLatitude = mLocation.getLatitude(); 
         mLongitude = mLocation.getLongitude(); 
         isLocationAvailable = true; // setting a flag that 
         // location is available 
         return mLocation; 
        } 
       } 
      } 

      // If we are reaching this part, it means GPS was not able to fetch 
      // any location 
      // Getting network status 
      isNetworkEnabled = mLocationManager 
        .isProviderEnabled(LocationManager.NETWORK_PROVIDER); 

      if (isNetworkEnabled) { 
       mLocationManager.requestLocationUpdates(
         LocationManager.NETWORK_PROVIDER, TIME, DISTANCE, this); 
       if (mLocationManager != null) { 
        mLocation = mLocationManager 
          .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 
        if (mLocation != null) { 
         mLatitude = mLocation.getLatitude(); 
         mLongitude = mLocation.getLongitude(); 
         isLocationAvailable = true; // setting a flag that 
         // location is available 
         return mLocation; 
        } 
       } 
      } 
      // If reaching here means, we were not able to get location neither 
      // from GPS not Network, 
      if (!isGPSEnabled) { 
       // so asking user to open GPS 
       askUserToOpenGPS(); 
      } 
     } 

     }catch(Exception e){ 
      e.printStackTrace(); 
     } 
     // if reaching here means, location was not available, so setting the 
     // flag as false 
     isLocationAvailable = false; 
     return null; 

} 

/** 
* Gives you complete address of the location 
* 
* @return complete address in String 
*/ 
public String getLocationAddress() { 

    if (isLocationAvailable) { 

     Geocoder geocoder = new Geocoder(mContext, Locale.getDefault()); 
     // Get the current location from the input parameter list 
     // Create a list to contain the result address 
     List<Address> addresses = null; 
     try { 
      /* 
      * Return 1 address. 
      */ 
      addresses = geocoder.getFromLocation(mLatitude, mLongitude, 1); 
     } catch (IOException e1) { 
      e1.printStackTrace(); 
      return ("IO Exception trying to get address:" + e1); 
     } catch (IllegalArgumentException e2) { 
      // Error message to post in the log 
      String errorString = "Illegal arguments " 
        + Double.toString(mLatitude) + " , " 
        + Double.toString(mLongitude) 
        + " passed to address service"; 
      e2.printStackTrace(); 
      return errorString; 
     } 
     // If the reverse geocode returned an address 
     if (addresses != null && addresses.size() > 0) { 
      // Get the first address 
      Address address = addresses.get(0); 
      /* 
      * Format the first line of address (if available), city, and 
      * country name. 
      */ 
      String addressText = String.format(
        "%s, %s, %s,%s", 
        // If there's a street address, add it 
        address.getMaxAddressLineIndex() > 0 ? address 
          .getAddressLine(0) : "", 
        // Locality is usually a city 
        address.getLocality(), 
        address.getAdminArea(), 
        // The country of the address 
        address.getCountryName()); 
      // Return the text 
      return addressText; 
     } else { 
      return getString(R.string.no_address_gpsservice); 
     } 
    } else { 
     return getString(R.string.loc_unavaliable); 
    } 

} 



/** 
* get latitude 
* 
* @return latitude in double 
*/ 
public double getLatitude() { 
    if (mLocation != null) { 
     mLatitude = mLocation.getLatitude(); 
    } 
    return mLatitude; 
} 

/** 
* get longitude 
* 
* @return longitude in double 
*/ 

public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) { 
    switch (requestCode) { 
     case 1: { 
      // If request is cancelled, the result arrays are empty. 
      if (grantResults.length > 0 
        && grantResults[0] == PackageManager.PERMISSION_GRANTED) { 

      } else { 
       // permission denied, boo! Disable the 
       // functionality that depends on this permission. 
      } 
      return; 
     } 
     // other 'case' lines to check for other 
     // permissions this app might request 
    } 
} 

public double getLongitude() { 
    if (mLocation != null) { 
     mLongitude = mLocation.getLongitude(); 
    } 
    return mLongitude; 
} 

/** 
* close GPS to save battery 
*/ 
public void closeGPS() { 

    if (mLocationManager != null) { 
     mLocationManager.removeUpdates(GPSService.this); 
    } 
} 

/** 
* show settings to open GPS 
*/ 
public void askUserToOpenGPS() { 
    AlertDialog.Builder mAlertDialog = new AlertDialog.Builder(mContext); 

    // Setting Dialog Title 
    mAlertDialog.setTitle(R.string.gpsservice_dialog_title) 
      .setMessage(R.string.gpsservice_dialog_message) 
      .setPositiveButton(R.string.gpsservice_dialog_positive, new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int which) { 
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS); 
        mContext.startActivity(intent); 
       } 
      }) 
      .setNegativeButton(R.string.gpsservice_dialog_negative,new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int which) { 
        dialog.cancel(); 
       } 
      }).show(); 
} 

/** 
* Updating the location when location changes 
*/ 
@Override 
public void onLocationChanged(Location location) { 
    mLatitude = location.getLatitude(); 
    mLongitude = location.getLongitude(); 
} 

@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; 
} 
} 
+0

活動需要檢查的運行權限,並要求對他們來說,啓動或綁定到服務之前請求許可。 – CommonsWare

+0

好吧讓我試試這個 – henry

+0

我是否必須在所有活動中要求它,我可以只需要它一次,它涵蓋了其餘的部分 – henry

回答