在Android M中获取纬度和经度0.0 [英] Getting Latitude and Longitude 0.0 in Android M

查看:189
本文介绍了在Android M中获取纬度和经度0.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

已经搜索了很多关于这个,但没有找到它的解决方案。我的代码完全适用于小于23的其他API版本。



我还将代码设置为selfPermission,并且所有代码都在工作,而不是它给我0.0请稍后再看看我的方式:

GPSTracker.java

p>

  public class GPSTracker extends Service implements LocationListener {

private Context mContext;

//标记GPS状态
boolean isGPSEnabled = false;

//标记网络状态
布尔isNetworkEnabled = false;

//标记GPS状态
boolean canGetLocation = false;

位置位置; //位置
双纬度; //纬度
双经度; // Longitude

//改变的最小距离以米为单位的更新
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1000;

//以毫秒为单位的最小更新时间间隔
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1分钟

//声明位置管理器
受保护的LocationManager locationManager;

活动活动;
$ b公共GPSTracker(){
}

公共GPSTracker(上下文环境,活动活动){
this.mContext = context;
this.activity = activity;
getLocation();


公共位置getLocation(){
尝试{


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

//获取GPS状态
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);

//获取网络状态
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

if(!isGPSEnabled&&!isNetworkEnabled){
//没有启用网络提供程序
} else {
this.canGetLocation = true;
if(isNetworkEnabled){
int requestPermissionsCode = 50;
if(ContextCompat.checkSelfPermission(activity,Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED&&& ActivityCompat.checkSelfPermission(activity,Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(activity,new String [] {Manifest.permission.ACCESS_FINE_LOCATION},requestPermissionsCode);

} else {
locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,this);
Log.d(网络,网络);
if(locationManager!= null){
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!= null){
latitude = location.getLatitude();
longitude = location.getLongitude();



$ b //如果启用了GPS,使用GPS服务得到纬度/经度
if(isGPSEnabled){
if(location == null){
if(ContextCompat.checkSelfPermission(activity,Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED&&& ActivityCompat.checkSelfPermission(activity,Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager .PERMISSION_GRANTED){
ActivityCompat.requestPermissions(activity,new String [] {Manifest.permission.ACCESS_FINE_LOCATION},50);

} else {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,this);
Log.d(已启用GPS,已启用GPS);
if(locationManager!= null){
location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location!= null){
latitude = location.getLatitude();
longitude = location.getLongitude();





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

返回地点;
}


/ **
*停止使用GPS监听器
*调用此函数将停止在您的应用中使用GPS。
* * /
public void stopUsingGPS(){
if(locationManager!= null){
if(ContextCompat.checkSelfPermission(activity,Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager .PERMISSION_GRANTED&&& ActivityCompat.checkSelfPermission(activity,Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(activity,new String [] {Manifest.permission.ACCESS_FINE_LOCATION},50);

} else {
locationManager.removeUpdates(GPSTracker.this);
}


}
}


/ **
*函数获得纬度$ b $如果(位置!= null){
纬度= location.getLatitude();如果(位置!=空){b $ * b /
public double getLatitude(){

}

//返回纬度
返回纬度;


$ b / **
*函数获得经度
* * /
public double getLongitude(){
if(location!= null){
longitude = location.getLongitude();
}

//返回经度
返回经度;
}

/ **
*支持GPS / Wi-Fi的功能
* @return布尔
* * /
public boolean canGetLocation(){
return this.canGetLocation;
}


/ **
*显示设置警报对话框的功能。
*按下设置按钮后,它将启动设置选项。
* * /
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

//设置对话框标题
alertDialog.setTitle(GPS is settings);

//设置对话框消息
alertDialog.setMessage(GPS未启用,是否要进入设置菜单?);

//按下设置按钮。
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);
}
});

//按下取消按钮
alertDialog.setNegativeButton(取消,新的DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int which){
dialog.cancel();
}
});

//显示提示信息
alertDialog.show();



@Override
public void onLocationChanged(位置位置){
}


@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(意向arg0){
返回null;


$ / code>

DashboardActivity.java:

在onCreate()中我初始化了GPSTracker:

$ g $ = new GPSTracker(mContext,DashboardActivity。这个);

//检查GPS是否启用
if(gps.canGetLocation()){

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

// \\\
是换行
Toast.makeText(getApplicationContext(),您的位置是 - \\\
Lat:+ latitude +\\\
Long:+ longitude ,Toast.LENGTH_LONG).show();
} else {
//无法获取位置。
// GPS或网络未启用。
//要求用户在设置中启用GPS /网络。
gps.showSettingsAlert();
}

AndroidManifest.xml

 < permission android:name =android.permission.ACCESS_COARSE_LOCATION/> 
< permission android:name =android.permission.ACCESS_FINE_LOCATION/>


<使用权限android:name =android.permission.ACCESS_COARSE_LOCATION/>
< uses-permission android:name =android.permission.ACCESS_FINE_LOCATION/>
< uses-permission android:name =android.permission.INTERNET/>

我经历了堆栈溢出中提供的许多链接,但没有人帮助我解决这个问题。



我很感谢这里的任何帮助。

CommonsWare Blackkara 答案的帮助下,我解决了我的问题。

根据他们的建议I已经改变了我的代码,并仔细观察了我的代码的每一步,并进行了调试。



由于我遇到了问题,我的onLocationChanged()但是令人惊讶的是,它在Android M或6.0以下的老设备的情况下很火。

为了解决这个问题,我改变了我的代码如下所示,我在这里发布完整的代码,以便任何有同样问题的人都可以摆脱它。 GPSTracker.java

 公共类GPSTracker扩展S服务{

private Context mContext;

//标记GPS状态
boolean isGPSEnabled = false;

//标记网络状态
布尔isNetworkEnabled = false;

//标记GPS状态
boolean canGetLocation = false;

位置位置; //位置
双纬度; //纬度
双经度; // Longitude

//改变的最小距离以米为单位的更新
private static final long MIN_DISTANCE_CHANGE_FOR_UPDATES = 1000; // 10米

//以毫秒为单位的最小更新时间间隔
private static final long MIN_TIME_BW_UPDATES = 1000 * 60 * 1; // 1分钟

//声明位置管理器
受保护的LocationManager locationManager;

活动活动;
$ b公共GPSTracker(){
}

公共GPSTracker(上下文环境,活动活动){
this.mContext = context;
this.activity = activity;
getLocation();


公共位置getLocation(){
尝试{


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

//获取GPS状态
isGPSEnabled = locationManager
.isProviderEnabled(LocationManager.GPS_PROVIDER);

//获取网络状态
isNetworkEnabled = locationManager
.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

if(!isGPSEnabled&&!isNetworkEnabled){
//没有启用网络提供程序
} else {
this.canGetLocation = true;
if(isNetworkEnabled){
int requestPermissionsCode = 50;

locationManager.requestLocationUpdates(
LocationManager.NETWORK_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,mLocationListener);
Log.d(网络,网络);
if(locationManager!= null){
location = locationManager
.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
if(location!= null){
latitude = location.getLatitude();
longitude = location.getLongitude();



$ b //如果启用了GPS,使用GPS服务得到纬度/经度
if(isGPSEnabled){
if(location == null){
if(ContextCompat.checkSelfPermission(activity,Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED&&& ActivityCompat.checkSelfPermission(activity,Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager .PERMISSION_GRANTED){
ActivityCompat.requestPermissions(activity,new String [] {Manifest.permission.ACCESS_FINE_LOCATION},50);

} else {
locationManager.requestLocationUpdates(
LocationManager.GPS_PROVIDER,
MIN_TIME_BW_UPDATES,
MIN_DISTANCE_CHANGE_FOR_UPDATES,mLocationListener);
Log.d(已启用GPS,已启用GPS);
if(locationManager!= null){

location = locationManager
.getLastKnownLocation(LocationManager.GPS_PROVIDER);
if(location!= null){
latitude = location.getLatitude();
longitude = location.getLongitude();

$ b}
}

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

返回地点;
}


/ **
*停止使用GPS监听器
*调用此函数将停止在您的应用中使用GPS。
* * /
public void stopUsingGPS(){

}


private final LocationListener mLocationListener = new LocationListener(){
@Override
public void onLocationChanged(final Location location){

if(location!= null){
latitude = location.getLatitude();
longitude = location.getLongitude();


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

}

@Override
public void onProviderEnabled(String provider){

}

@Override
public void onProviderDisabled(String provider){

}
};
$ b / **
*获得纬度的函数
* * /
public double getLatitude(){
if(location!= null){
latitude = location.getLatitude();
}

//返回纬度
返回纬度;


$ b / **
*函数获得经度
* * /
public double getLongitude(){
if(location!= null){
longitude = location.getLongitude();
}

//返回经度
返回经度;
}

/ **
*支持GPS / Wi-Fi的功能
* @return布尔
* * /
public boolean canGetLocation(){
return this.canGetLocation;
}


/ **
*显示设置警报对话框的功能。
*按下设置按钮后,它将启动设置选项。
* * /
public void showSettingsAlert(){
AlertDialog.Builder alertDialog = new AlertDialog.Builder(mContext);

//设置对话框标题
alertDialog.setTitle(GPS is settings);

//设置对话框消息
alertDialog.setMessage(GPS未启用,是否要进入设置菜单?);

//按下设置按钮。
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);
}
});

//按下取消按钮
alertDialog.setNegativeButton(取消,新的DialogInterface.OnClickListener(){
public void onClick(DialogInterface dialog,int which){
dialog.cancel();
}
});

//显示提示信息
alertDialog.show();
}


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

DashboardActivity.java

  public class DashboardActivity extends Activity {

Context mContext;

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

mContext = this;

if(ContextCompat.checkSelfPermission(mContext,Manifest.permission.ACCESS_FINE_LOCATION)!= PackageManager.PERMISSION_GRANTED&&& ActivityCompat.checkSelfPermission(mContext,Manifest.permission.ACCESS_COARSE_LOCATION)!= PackageManager.PERMISSION_GRANTED){
ActivityCompat.requestPermissions(DashboardActivity.this,new String [] {Manifest.permission.ACCESS_FINE_LOCATION},1);
$ b $} else {
Toast.makeText(mContext,您需要授予权限,Toast.LENGTH_SHORT).show();
gps =新的GPSTracker(mContext,DashboardActivity.this);

//检查GPS是否启用
if(gps.canGetLocation()){

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

// \\\
是换行
Toast.makeText(getApplicationContext(),您的位置是 - \\\
Lat:+ latitude +\\\
Long:+ longitude ,Toast.LENGTH_LONG).show();
} else {
//无法获取位置。
// GPS或网络未启用。
//要求用户在设置中启用GPS /网络。
gps.showSettingsAlert();
}
}
}


@Override
public void onRequestPermissionsResult(int requestCode,String [] permissions,int [] grantResults) {
super.onRequestPermissionsResult(requestCode,permissions,grantResults);

switch(requestCode){
case 1:{
//如果请求被取消,结果数组为空。
if(grantResults.length> 0
&&& amp; grantResults [0] == PackageManager.PERMISSION_GRANTED){

//许可被授予,yay!做你需要做的

//联系人相关的任务。

gps =新的GPSTracker(mContext,DashboardActivity.this);

//检查GPS是否启用
if(gps.canGetLocation()){

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

// \\\
是换行
Toast.makeText(getApplicationContext(),您的位置是 - \\\
Lat:+ latitude +\\\
Long:+ longitude ,Toast.LENGTH_LONG).show();
} else {
//无法获取位置。
// GPS或网络未启用。
//要求用户在设置中启用GPS /网络。
gps.showSettingsAlert();
}

} else {

// permission denied,boo!禁用依赖此权限的
//功能。

Toast.makeText(mContext,您需要授予权限,Toast.LENGTH_SHORT).show();
}
return;
}
}
}
}

Manifest.xml:



已添加的权限

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

在Application Tag中声明服务:

 < service android:name =。utilities.GPSTracker/> 


I am suffering from the problem of getting value 0.0 as latitude and longitude in Android Marshmallow (API 23) i.e. 6.0.

I have searched a lot regarding this but didn't find solution of it. My code is fully working for the other API versions which are less than 23.

I have also put the code for selfPermission and which all are working instead it's giving me 0.0 as late and long.

Please have a look on the way I am following:

GPSTracker.java

public class GPSTracker extends Service implements LocationListener {

    private  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 = 1000; 

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

    Activity activity;

    public GPSTracker() {
    }

    public GPSTracker(Context context, Activity activity) {
        this.mContext = context;
        this.activity = activity;
        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;
                if (isNetworkEnabled) {
                    int requestPermissionsCode = 50;
                    if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, requestPermissionsCode);

                    } else {
                        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 latitude/longitude using GPS Services
                if (isGPSEnabled) {
                    if (location == null) {
                        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 50);

                        } else {
                            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) {
            if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 50);

            } else {
                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/Wi-Fi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }


    /**
     * Function to show settings alert dialog.
     * On pressing the Settings button it will launch 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 the 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 the 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;
    }
 }

DashboardActivity.java:

In onCreate() I have initialized GPSTracker:

gps = new GPSTracker(mContext,DashboardActivity.this);

        // Check if GPS enabled
        if(gps.canGetLocation()) {

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

            // \n is for new line
            Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
        } else {
            // Can't get location.
            // GPS or network is not enabled.
            // Ask user to enable GPS/network in settings.
            gps.showSettingsAlert();
        }

AndroidManifest.xml

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


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

I have gone through many links provided in Stack Overflow but none of them helped me to solve this problem.

I would appreciate any kind of help here.

解决方案

With the help of CommonsWare and Blackkara answer, I was able to solve my problem.

As per their suggestion I have changed my code and have a look after each and every step of my code with debugging.

Due to that I came with the problem that my onLocationChanged() did not get fired in the case of Marshmallow but surprisingly, it gets fire in the case of older devices which are less than Android M or 6.0.

For solving this I have changed my code as below, here I am posting the full code so that anyone who has the same problem can get rid of it.

GPSTracker.java

public class GPSTracker extends Service{

    private  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 = 1000; // 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;

    Activity activity;

    public GPSTracker() {
    }

    public GPSTracker(Context context, Activity activity) {
        this.mContext = context;
        this.activity = activity;
        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;
                if (isNetworkEnabled) {
                    int requestPermissionsCode = 50;

                    locationManager.requestLocationUpdates(
                            LocationManager.NETWORK_PROVIDER,
                            MIN_TIME_BW_UPDATES,
                            MIN_DISTANCE_CHANGE_FOR_UPDATES, mLocationListener);
                    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 latitude/longitude using GPS Services
            if (isGPSEnabled) {
                if (location == null) {
                    if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
                        ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 50);

                    } else {
                        locationManager.requestLocationUpdates(
                                LocationManager.GPS_PROVIDER,
                                MIN_TIME_BW_UPDATES,
                                MIN_DISTANCE_CHANGE_FOR_UPDATES, mLocationListener);
                        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() {

    }


    private final LocationListener mLocationListener = new LocationListener() {
        @Override
        public void onLocationChanged(final Location location) {

            if (location != null) {
                latitude = location.getLatitude();
                longitude = location.getLongitude();
            }
        }

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

        }

        @Override
        public void onProviderEnabled(String provider) {

        }

        @Override
        public void onProviderDisabled(String provider) {

        }
    };

    /**
     * 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/Wi-Fi enabled
     * @return boolean
     * */
    public boolean canGetLocation() {
        return this.canGetLocation;
    }


    /**
     * Function to show settings alert dialog.
     * On pressing the Settings button it will launch 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 the 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 the cancel button
        alertDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.cancel();
            }
        });

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


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

DashboardActivity.java

public class DashboardActivity extends Activity {      

    Context mContext;   

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

        mContext = this;

        if (ContextCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(mContext, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(DashboardActivity.this, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, 1);

        } else {
            Toast.makeText(mContext,"You need have granted permission",Toast.LENGTH_SHORT).show();
            gps = new GPSTracker(mContext, DashboardActivity.this);

            // Check if GPS enabled
            if (gps.canGetLocation()) {

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

                // \n is for new line
                Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
            } else {
                // Can't get location.
                // GPS or network is not enabled.
                // Ask user to enable GPS/network in settings.
                gps.showSettingsAlert();
            }
        }           
    }


    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);

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

                    // permission was granted, yay! Do the

                    // contacts-related task you need to do.

                    gps = new GPSTracker(mContext, DashboardActivity.this);

                    // Check if GPS enabled
                    if (gps.canGetLocation()) {

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

                        // \n is for new line
                        Toast.makeText(getApplicationContext(), "Your Location is - \nLat: " + latitude + "\nLong: " + longitude, Toast.LENGTH_LONG).show();
                    } else {
                        // Can't get location.
                        // GPS or network is not enabled.
                        // Ask user to enable GPS/network in settings.
                        gps.showSettingsAlert();
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.

                    Toast.makeText(mContext, "You need to grant permission", Toast.LENGTH_SHORT).show();
                }
                return;
            }
        }
    }
}

Manifest.xml :

Permission which are added

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

Declare service in Application Tag:

 <service android:name=".utilities.GPSTracker"/>

这篇关于在Android M中获取纬度和经度0.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆