I am newbie to native android development. For understanding it, i am developing an app which will show me gps
location of me. For this i searched on the internet and found two tutorials.
我是本机android开发的新手。为了理解它,我正在开发一个应用程序,它将向我显示gps的位置。为此,我在互联网上搜索并找到了两个教程。
I am following Link1
, and followed each step in it, Bellow is the code which I have written.
我正在关注Link1,并按照其中的每一步,Bellow是我编写的代码。
GPSTracker.java
import android.Manifest;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.provider.Settings;
public class GPSTracker extends Service implements LocationListener {
private final Context mContext;
// flag for GPS status
boolean isGPSEnabled = false;
// flag for network status
boolean isNetworkEnabled = false;
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 = 5; // 5 meters
// The minimum time between updates in milliseconds
private static final long MIN_TIME_BW_UPDATES = 10000; // 10 seconds
// Declaring a Location Manager
protected LocationManager locationManager;
public GPSTracker(Context mContext) {
this.mCOntext= mContext;
}
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) {
Log.i("", "Network Value: " + isNetworkEnabled);
Log.i("", "GPS Value: " + isGPSEnabled);
// 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 (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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 location;
}*/
}
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();
Log.i("", "Exception " + e);
}
return location;
}
/**
* Stop using GPS listener
* Calling this function will stop using GPS in your app
* */
public void stopUsingGPS() {
if (locationManager != null) {
/*if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(this, 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;
}*/
locationManager.removeUpdates(GPSTracker.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();
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onLocationChanged(Location location) {
}
@Override
public void onStatusChanged(String provider, int status, Bundle extras) {
}
@Override
public void onProviderEnabled(String provider) {
}
@Override
public void onProviderDisabled(String provider) {
}}
Bellow is my main activity code
贝娄是我的主要活动代码
MainActivity.java
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.app.Activity;
public class MainActivity extends Activity {
Button btnShowLocation;
TextView textShowLocation;
// GPSTracker class
GPSTracker gps;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnShowLocation = (Button) findViewById(R.id.btnShowLocation);
// show location button click event
btnShowLocation.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View v) {
// create class object
gps = new GPSTracker(MainActivity.this);
// need to make canGetLocation flag true by calling below method as per your code.
**gps.getLocation()**
// check if GPS enabled
if(gps.canGetLocation()){
double latitude = gps.getLatitude();
double lOngitude= gps.getLongitude();
textShowLocation.append("Your Location is - \nLat: " + latitude+ "\nLong: " + longitude);
}
else
{
// can't get location
// GPS or Network is not enabled
// Ask user to enable GPS/network in settings
gps.showSettingsAlert();
}
}
});
}
Update 1
Below is my manifest code:
以下是我的清单代码:
While running the app into my device, whenever i click the show location
button it always redirect me to the else
part i.e. gps.showSettingsAlert();
run. No matter if 'GPS' of my device is on it still not showing me the location. Moreover, comment or un-comment the permission check
is not helping.
在将应用程序运行到我的设备中时,每当我点击显示位置按钮时,它总是将我重定向到其他部分,即gps.showSettingsAlert();跑。无论我的设备的“GPS”是否打开,它仍然没有显示我的位置。此外,评论或取消评论权限检查没有帮助。
Any help would be highly appreciated:
任何帮助将受到高度赞赏:
1
you need to call getLocation
(); method in the constructor:
你需要调用getLocation();构造函数中的方法:
public GPSTracker(Context mContext) {
this.mCOntext= mContext;
getLocation();
}
in your GPSTracker class add this code:
在您的GPSTracker类中添加以下代码:
@Override
public void onLocationChanged(Location location) {
this.location = location;
getLatitude();
getLongitude();
}
Also the class u are using has some problems: see this blog http://gabesechansoftware.com/location-tracking/
您使用的课程也有一些问题:请参阅此博客http://gabesechansoftware.com/location-tracking/
you can use FusedLocationApi
你可以使用FusedLocationApi
here is an example:http://www.androidwarriors.com/2015/10/fused-location-provider-in-android.html
这是一个例子:http://www.androidwarriors.com/2015/10/fused-location-provider-in-android.html
0
if you are using 5.0+ version then add
如果您使用的是5.0+版本,请添加
to your manifest. and if you are testing on marshmallow you have to add
到你的清单。如果你在棉花糖上测试,你必须添加
int REQUEST_CODE_PERMISSION=101;
void allowGPS() {
try {
if (Build.VERSION.SDK_INT >= 23 {
Log.i("*******", "check build permission");
try {
if (getApplicationContext().checkSelfPermission(Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
if (ActivityCompat.shouldShowRequestPermissionRationale(LoginActivity.this, Manifest.permission.ACCESS_FINE_LOCATION)) {
// permission wasn't granted
} else {
ActivityCompat.requestPermissions(LoginActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, REQUEST_CODE_PERMISSION);
}
}
} catch (Exception ae) {
}
}
} catch (Exception ae) {
ae.printStackTrace();
}
}
@Override
public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == REQUEST_CODE_PERMISSION) {
if (grantResults.length >= 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted
} else {
// permission wasn't granted
}
}
}
0
GPSTracker is a service class. You have to start the service to get location. Now else condition is showing because location is not fetched yet. You can start service by startService(new Intent(context, GPSTracker.class));
GPSTracker是一个服务类。您必须启动服务才能获得位置。现在显示其他条件,因为尚未提取位置。您可以通过startService启动服务(new Intent(context,GPSTracker.class));
Also change your button click code by this
也可以通过此更改按钮单击代码
LocationManager locatiOnManager= (LocationManager) getSystemService(LOCATION_SERVICE);
if (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)){
Toast.makeText(this, "GPS is Enabled in your devide", Toast.LENGTH_SHORT).show();
}else{
showGPSDisabledAlertToUser();
}