2017-04-01 82 views
2
************* TrackGPS.java ***************************** 

    import android.app.AlertDialog; 
    import android.app.Service; 
    import android.content.Context; 
    import android.content.DialogInterface; 
    import android.content.Intent; 

    import android.content.pm.PackageManager; 
    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.support.v4.app.ActivityCompat; 
    import android.util.Log; 
    import android.widget.Toast; 

    /** 
    * Created by ANQ on 8/8/2016. 
    */ 

    public class TrackGPS extends Service implements LocationListener { 

     private final Context mContext; 


     boolean checkGPS = false; 


     boolean checkNetwork = false; 

     boolean canGetLocation = false; 

     Location loc; 
     double latitude; 
     double longitude; 


     private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 10; 


     private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; 
     protected LocationManager locationManager; 

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

     private Location getLocation() { 

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

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

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

       if (!checkGPS && !checkNetwork) { 
        Toast.makeText(mContext, "No Service Provider Available", Toast.LENGTH_SHORT).show(); 
       } else { 
        this.canGetLocation = true; 
        // First get location from Network Provider 
        if (checkNetwork) { 
         Toast.makeText(mContext, "Network", Toast.LENGTH_SHORT).show(); 

         try { 
          locationManager.requestLocationUpdates(
            LocationManager.NETWORK_PROVIDER, 
            MIN_TIME_BW_UPDATES, 
            MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
          Log.d("Network", "Network"); 
          if (locationManager != null) { 
           loc = locationManager 
             .getLastKnownLocation(LocationManager.NETWORK_PROVIDER); 

          } 

          if (loc != null) { 
           latitude = loc.getLatitude(); 
           longitude = loc.getLongitude(); 
          } 
         } 
         catch(SecurityException e){ 

         } 
        } 
       } 
       // if GPS Enabled get lat/long using GPS Services 
       if (checkGPS) { 
        Toast.makeText(mContext,"GPS",Toast.LENGTH_SHORT).show(); 
        if (loc == null) { 
         try { 
          locationManager.requestLocationUpdates(
            LocationManager.GPS_PROVIDER, 
            MIN_TIME_BW_UPDATES, 
            MIN_DISTANCE_CHANGE_FOR_UPDATES, this); 
          Log.d("GPS Enabled", "GPS Enabled"); 
          if (locationManager != null) { 
           loc = locationManager 
             .getLastKnownLocation(LocationManager.GPS_PROVIDER); 
           if (loc != null) { 
            latitude = loc.getLatitude(); 
            longitude = loc.getLongitude(); 
           } 
          } 
         } catch (SecurityException e) { 

         } 
        } 
       } 

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

      return loc; 
     } 

     public double getLongitude() { 
      if (loc != null) { 
       longitude = loc.getLongitude(); 
      } 
      return longitude; 
     } 

     public double getLatitude() { 
      if (loc != null) { 
       latitude = loc.getLatitude(); 
      } 
      return latitude; 
     } 

     public boolean canGetLocation() { 
      return this.canGetLocation; 
     } 

     public void showSettingsAlert() { 
      AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext); 


      alertDialog.setTitle("GPS Not Enabled"); 

      alertDialog.setMessage("Do you wants to turn On GPS"); 


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


      alertDialog.setNegativeButton("No", new DialogInterface.OnClickListener() { 
       public void onClick(DialogInterface dialog, int which) { 
        dialog.cancel(); 
       } 
      }); 


      alertDialog.show(); 
     } 


     public void stopUsingGPS() { 
      if (locationManager != null) { 

       locationManager.removeUpdates(TrackGPS.this); 
      } 
     } 

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

     @Override 
     public void onLocationChanged(Location location) { 

     } 

     @Override 
     public void onStatusChanged(String s, int i, Bundle bundle) { 

     } 

     @Override 
     public void onProviderEnabled(String s) { 

     } 

     @Override 
     public void onProviderDisabled(String s) { 

     } 
    } 






************* MainActivity.java **************** 

    import android.support.v7.app.AppCompatActivity; 
    import android.os.Bundle; 

    import android.support.v7.app.AppCompatActivity; 
    import android.os.Bundle; 
    import android.view.View; 
    import android.widget.Button; 
    import android.widget.Toast; 

    public class MainActivity extends AppCompatActivity { 

     private Button b_get; 
     private TrackGPS gps; 
     double longitude; 
     double latitude; 
     @Override 
     protected void onCreate(Bundle savedInstanceState) { 
      super.onCreate(savedInstanceState); 
      setContentView(R.layout.activity_main); 
      b_get = (Button)findViewById(R.id.get); 



      b_get.setOnClickListener(new View.OnClickListener() { 
       @Override 
       public void onClick(View view) { 

        gps = new TrackGPS(MainActivity.this); 


        if(gps.canGetLocation()){ 


         longitude = gps.getLongitude(); 
         latitude = gps .getLatitude(); 

         Toast.makeText(getApplicationContext(),"Longitude:"+Double.toString(longitude)+"\nLatitude:"+Double.toString(latitude),Toast.LENGTH_SHORT).show(); 
        } 
        else 
        { 

         gps.showSettingsAlert(); 
        } 

       } 
      }); 
     } 

     @Override 
     protected void onDestroy() { 
      super.onDestroy(); 
      gps.stopUsingGPS(); 
     } 
    } 

當我運行應用程序的經度和緯度顯示爲0.0時,我正在使用android棉花糖測試此應用程序。 「http://clover.studio/2016/08/09/getting-current-location-in-android-using-location-manager/」這是我用來創建應用程序的鏈接。經緯度在Android中顯示爲0

+2

試舉對M 6.0的位置和其他權限.. –

+0

試試GoogleApiClient獲取位置 - 請看這個http://www.androidhive.info/2015/02/android-location-api-using-google-play-services/ – Sach

+0

你可以嘗試融合位置服務來實現或者你可以創建一個後臺服務,如果你想通過應用程序的位置 – AbhayBohra

回答

1

請管理所需的棉花糖許可。

首先,您在清單文件

<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" /> 
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" /> 

添加此權限在活動結束後首先聲明兩個變量這樣,

private static final int REQUEST_CODE_PERMISSION = 1; 
String mPermission = Manifest.permission.ACCESS_FINE_LOCATION; 

在onCreate方法後

if(Build.VERSION.SDK_INT>= 23) { 

     if (checkSelfPermission(mPermission) != PackageManager.PERMISSION_GRANTED) { 
      ActivityCompat.requestPermissions(MainActivity.this, 
        new String[]{mPermission, 
        }, 
        REQUEST_CODE_PERMISSION); 
      return; 
     } 

     else 
     { 
      *here manage your code if permission already access 
     } 
    } 
+0

這怎麼能做到sir – chris

+0

ohk,我更新我的代碼。 –

+0

非常感謝,先生它像魅力 – chris

1

這裏以時間間隔檢測當前位置的後臺服務

import android.annotation.SuppressLint; 
import android.app.Service; 
import android.content.Context; 
import android.content.Intent; 
import android.location.Location; 
import android.os.Bundle; 
import android.os.IBinder; 
import android.support.annotation.Nullable; 
import android.util.Log; 
import android.widget.Toast; 
import com.google.android.gms.common.ConnectionResult; 
import com.google.android.gms.common.GooglePlayServicesUtil; 
import com.google.android.gms.common.api.GoogleApiClient; 
import com.google.android.gms.common.api.PendingResult; 
import com.google.android.gms.common.api.Status; 
import com.google.android.gms.location.LocationListener; 
import com.google.android.gms.location.LocationRequest; 
import com.google.android.gms.location.LocationServices; 

@SuppressWarnings("MissingPermission") 
public class LocationBackGroundService extends Service implements LocationListener, 
     GoogleApiClient.ConnectionCallbacks, 
     GoogleApiClient.OnConnectionFailedListener { 

    private static final String TAG = "LocationBackGroundService"; 
    private static final long INTERVAL = 10; 
    private static final long FASTEST_INTERVAL = 10; 

    LocationRequest mLocationRequest; 
    GoogleApiClient mGoogleApiClient; 
    Location mCurrentLocation; 
    Context mCOntext; 

    public void LocationBackGroundService(Context mContext) { 
     this.mCOntext = mContext; 
    } 

    protected void createLocationRequest() { 
     mLocationRequest = new LocationRequest(); 
     mLocationRequest.setInterval(INTERVAL); 
     mLocationRequest.setFastestInterval(FASTEST_INTERVAL); 
     mLocationRequest.setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY); 
    } 

    @Override 
    public void onStart(Intent intent, int startId) { 
     super.onStart(intent, startId); 
     mGoogleApiClient.connect(); 
    } 

    @Override 
    public void onCreate() { 
     super.onCreate(); 

     if (!isGooglePlayServicesAvailable()) { 

     } 
     createLocationRequest(); 
     mGoogleApiClient = new GoogleApiClient.Builder(this) 
       .addApi(LocationServices.API) 
       .addConnectionCallbacks(this) 
       .addOnConnectionFailedListener(this) 
       .build(); 

     if (mGoogleApiClient.isConnected()) { 
      startLocationUpdates(); 
     } 

    } 

    private boolean isGooglePlayServicesAvailable() { 
     int status = GooglePlayServicesUtil.isGooglePlayServicesAvailable(this); 
     if (ConnectionResult.SUCCESS == status) { 
      return true; 
     } else { 
      return false; 
     } 
    } 

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

    @Override 
    public void onConnected(Bundle bundle) { 
     startLocationUpdates(); 
    } 

    @SuppressLint("LongLogTag") 
    protected void startLocationUpdates() { 
     PendingResult<Status> pendingResult = LocationServices.FusedLocationApi.requestLocationUpdates(
       mGoogleApiClient, mLocationRequest, this); 

     Log.d(TAG, "Location update started ..............: "); 
    } 

    @Override 
    public void onConnectionSuspended(int i) { 

     Toast.makeText(this,"OnConnection Suspended",Toast.LENGTH_SHORT).show(); 
    } 

    @Override 
    public void onConnectionFailed(ConnectionResult connectionResult) { 
     Toast.makeText(this,"OnConnection Failed",Toast.LENGTH_SHORT).show(); 
    } 

    @Override 
    public void onLocationChanged(Location location) { 

     if (null != mCurrentLocation) { 
      mCurrentLocation = location; 
      String lat = String.valueOf(mCurrentLocation.getLatitude()); 
      String lng = String.valueOf(mCurrentLocation.getLongitude()); 

      ConstantFunction.saveStatus(this, ConstantVariables.CURRENT_LATITUDE, lat); 
      ConstantFunction.saveStatus(this, ConstantVariables.CURRENT_LONGTITUDE, lng); 
      System.out.println("First Condition Hit"); 
      System.out.println("Lat::-- " + lat + "\n" + "LONG::--" + lng); 
     } 

     System.out.println("Lat::-- " + location.getLatitude() + "\n" + "LONG::--" + location.getLongitude()); 
    } 
} 

將在名爲LocationBackGroundService.java單獨的Java文件的代碼,並把它在你的MainActivity這樣startService(new Intent(this, LocationBackGroundService.class));,不要忘記將它添加在menifest這樣<service android:name="LocationBackGroundService"></service>

+0

這裏應該放置這個代碼先生在MainActivity或別的地方。如果你能簡單地描述這段代碼做什麼,因爲我是新手? – chris

+0

@chris檢查我的編輯 – AbhayBohra

+0

並且還必須添加啓動服務的運行時權限 – AbhayBohra