【问题标题】:GPS setting issue in android studioandroid studio中的GPS设置问题
【发布时间】:2017-01-25 05:39:45
【问题描述】:

我是原生 android 开发的新手。为了理解它,我正在开发一个应用程序,它将向我显示gps 我的位置。为此,我在互联网上搜索并找到了两个教程。

我正在关注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) {

}}

下面是我的主要活动代码

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



}

更新 1

下面是我的清单代码:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.accurat.tracker">
<uses-sdk android:minSdkVersion="8" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>

<application
    android:allowBackup="true"
    android:icon="@mipmap/ic_launcher"
    android:label="@string/app_name"
    android:supportsRtl="true"
    android:theme="@style/AppTheme">
    <activity android:name=".MainActivity">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

在我的设备中运行应用程序时,每当我单击show location 按钮时,它总是将我重定向到else 部分,即gps.showSettingsAlert(); 运行。无论我的设备的“GPS”是否在它上面,它仍然不会向我显示位置。此外,评论或取消评论 permission check 也无济于事。

任何帮助将不胜感激:

【问题讨论】:

  • 你在Manifest上设置权限了吗?
  • @ThisaruGuruge 请参阅update 1
  • 您是否尝试过使用多个设备?
  • @faisal1208 告诉我们您正在测试哪个设备的完整详细信息 .. 它的 API 级别和代码块 .. 调试并检查 if else 条件您得到的值,那么只有我们可以提供帮助。
  • 我可以看到最小sdk的代码是android:minSdkVersion="8" 你为什么要骗我们?

标签: java android eclipse android-studio gps


【解决方案1】:

您需要致电getLocation();构造函数中的方法:

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

在您的 GPSTracker 类中添加以下代码:

 @Override
public void onLocationChanged(Location location) {
    this.location = location;
    getLatitude();
    getLongitude();
}

您使用的课​​程也有一些问题:请参阅此博客 http://gabesechansoftware.com/location-tracking/

你可以使用FusedLocationApi

这里是一个例子:http://www.androidwarriors.com/2015/10/fused-location-provider-in-android.html

【讨论】:

  • 通过实现你的逻辑,现在在button click 我的应用程序崩溃并给我消息Unfortunately, Tracker has stopped
  • 它在 logcat 中给了我这个错误 FATAL EXCEPTION: main Process: com.example.accurat.tracker, PID: 10668 java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.TextView.append(java.lang.CharSequence)' on a null object reference
  • 你需要先从布局中使用findviewByID 实例化textShowLocation
  • 现在它正在运行,但它显示我经纬度0,0:|
  • 尝试将 MIN_DISTANCE_CHANGE_FOR_UPDATES MIN_TIME_BW_UPDATES 更改为 0 , 0 并检查编辑
【解决方案2】:

如果您使用的是 5.0+ 版本 然后添加

到您的清单。 如果您在棉花糖上进行测试,则必须添加

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

【讨论】:

    【解决方案3】:

    GPSTracker 是一个服务类。您必须启动服务才能获取位置。现在显示其他条件,因为尚未获取位置。 您可以通过以下方式启动服务 startService(new Intent(context, GPSTracker.class));

    也可以通过这个改变你的按钮点击代码

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

    【讨论】:

      猜你喜欢
      • 2018-03-21
      • 1970-01-01
      • 2020-10-17
      • 2013-09-29
      • 2015-03-19
      • 1970-01-01
      • 2021-04-13
      • 2017-12-25
      • 1970-01-01
      相关资源
      最近更新 更多