Java android studio中的GPS设置问题
我是本地android开发的新手。为了理解它,我正在开发一个应用程序,它将向我显示Java android studio中的GPS设置问题,java,android,eclipse,android-studio,gps,Java,Android,Eclipse,Android Studio,Gps,我是本地android开发的新手。为了理解它,我正在开发一个应用程序,它将向我显示gps我的位置。为此,我在网上搜索了两本教程 我遵循Link1,并遵循其中的每个步骤,下面是我编写的代码 GPSTracker.java import android.Manifest; import android.app.Service; import android.content.Context; import android.content.Intent; import android.conte
gps
我的位置。为此,我在网上搜索了两本教程
Link1
,并遵循其中的每个步骤,下面是我编写的代码
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>
在我的设备中运行应用程序时,每当我单击显示位置
按钮时,它总是将我重定向到其他
部分,即gps.showSettingsAlert()代码>运行。不管我的设备的“GPS”是否在上面,它仍然不会显示我的位置。此外,对权限检查进行注释或取消注释也无济于事
如果您使用的是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
}
}
}
GPSTracker是一个服务类。您必须启动服务才能获取位置。现在显示else条件,因为尚未获取位置。
您可以通过以下方式开始服务:
startService(新意图(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();
}
您需要调用getLocation
();构造函数中的方法:
public GPSTracker(Context mContext) {
this.mContext = mContext;
getLocation();
}
在GPSTracker类中添加以下代码:
@Override
public void onLocationChanged(Location location) {
this.location = location;
getLatitude();
getLongitude();
}
你使用的类也有一些问题:请看这个博客
您可以使用FusedLocationApi
下面是一个示例:您是否正确设置了清单上的权限?@ThisaruGuruge请查看更新1
您是否尝试了多台设备?@faisal1208告诉我们您正在测试的设备的完整详细信息。。它的API级别和代码块,它将从中访问。。调试并检查if-else条件您获得的值,然后只有我们可以提供帮助。正如我看到的代码一样,最小的sdk是android:minSdkVersion=“8”
为什么您对我们撒谎?通过实现您的逻辑,现在在按钮上单击我的应用程序崩溃,并给我消息,不幸的是,Tracker已停止
它在logcat中给了我这个错误致命异常:主进程:com.example.accurat.Tracker,PID:10668 java.lang.NullPointerException:尝试调用虚拟方法'void android.widget.TextView.append(java.lang.CharSequence)'在空对象引用上
您需要首先使用布局中的findviewByID
实例化textShowLocation
,现在它正在运行,但它显示的是lat,long0,0
:|尝试更改MIN\u DISTANCE\u CHANGE\u以更新
和MIN\u TIME\u BW\u更新
到0,0
,并检查编辑