java - 如何解决这个 GPS 问题?

标签 java android gps

为什么当我点击按钮时这个应用程序崩溃了? 那是什么问题? 我在主要 Activity 中有一个按钮,当我点击它时它崩溃了!

    package com.example.gpsapp;

import android.Manifest;
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.ContactsContract;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.annotation.Nullable;

public class GpsTracker   extends Service implements LocationListener {

  private Context context;
  private LocationManager locationManager;
  private Location location;
  private double latitude = 0.0;
  private double longitude = 0.0;


  private  boolean isGpsEnabled= false;  // flagi baraye gps
  private  boolean isNetworkEnabled = false;//hamishe ke az ro gps nis az net ham mishe
  private  boolean canGetLocation = false; //neshan midahad aya object ma mitavanad location ra daryaft konad ya na

  public  static final  int TIME_BW_UPDATE = 1000*60*1; // 1 minute
  public static final int MIN_DISTANCE_FOR_UPDATE =10; // 10 METER

  // tabee sazande ke context ro daryaft mikone
  public GpsTracker(Context context){
      this.context = context;
      getLocation();
  }

   public Location getLocation() throws SecurityException {

          locationManager = (LocationManager) context.getSystemService(Context.LOCATION_SERVICE);// daryafte location manage va set kardane anha
          isGpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
          isNetworkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

          if (!isGpsEnabled && !isNetworkEnabled) {
              //no provider enabled
              canGetLocation = false;

          } else {

              canGetLocation = true;
              // first , get location by network provider
              if (isNetworkEnabled) {
                  locationManager.requestLocationUpdates(LocationManager.NETWORK_PROVIDER, TIME_BW_UPDATE, MIN_DISTANCE_FOR_UPDATE, this);// bayad dar manifest mojavez dashte bashe

              if (locationManager!= null){
                  location = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER);
                  if (location!= null){
                      latitude=location.getLatitude();
                      longitude =location.getLongitude();
                  }
              }
              }
              if(isGpsEnabled && location == null){
                      locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER , TIME_BW_UPDATE, MIN_DISTANCE_FOR_UPDATE , this);
                      if (locationManager !=null){
                          location = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
                          if (location != null){
                              latitude=location.getLatitude();
                              longitude =location.getLongitude();

                          }
                      }

                  }



          }
       return location;
   }



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

    public boolean canGetLocation (){ // aya mitavanad location ra begirad ya na agar natonest ye dialogi mide be karbar
      return this.canGetLocation;
    }

    // zamani ke Gps roshan nist chikar konad
    public void showGpsAlertDialog(){
        AlertDialog.Builder builder = new AlertDialog.Builder(context);
        builder.setTitle("GPS").setMessage("Gps is not Enabled . turn it ON")
                .setPositiveButton("Settings", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        Intent intent = new Intent();
                        intent.setAction(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        context.startActivity(intent);
                       // dialog.dismiss();

                    }
                })
                .setNegativeButton("cancel", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        dialog.cancel();
                    }
                });
        builder.show();

    }

    public  void stopUsingGps (){

      if(locationManager != null){
          if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
               == PackageManager.PERMISSION_DENIED &&
          ActivityCompat.checkSelfPermission(this,Manifest.permission.ACCESS_COARSE_LOCATION)
          ==PackageManager.PERMISSION_GRANTED) {

              locationManager.removeUpdates(this);
          }
        }

    }


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

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

    }

    @Override
    public void onProviderEnabled(String provider) {

    }

    @Override
    public void onProviderDisabled(String provider) {

    }



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

这是当我点击崩溃并出现此错误时的恶意 Activity 代码:

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.example.gpsapp, PID: 30374
    java.lang.IllegalStateException: Could not execute method for android:onClick
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:390)
        at android.view.View.performClick(View.java:6261)
        at android.widget.TextView.performClick(TextView.java:11163)
        at android.view.View$PerformClick.run(View.java:23748)
        at android.os.Handler.handleCallback(Handler.java:751)
        at android.os.Handler.dispatchMessage(Handler.java:95)
        at android.os.Looper.loop(Looper.java:154)
        at android.app.ActivityThread.main(ActivityThread.java:6776)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386)
     Caused by: java.lang.reflect.InvocationTargetException
        at java.lang.reflect.Method.invoke(Native Method)
        at android.support.v7.app.AppCompatViewInflater$DeclaredOnClickListener.onClick(AppCompatViewInflater.java:385)
        at android.view.View.performClick(View.java:6261) 
        at android.widget.TextView.performClick(TextView.java:11163) 
        at android.view.View$PerformClick.run(View.java:23748) 
        at android.os.Handler.handleCallback(Handler.java:751) 
        at android.os.Handler.dispatchMessage(Handler.java:95) 
        at android.os.Looper.loop(Looper.java:154) 
        at android.app.ActivityThread.main(ActivityThread.java:6776) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1496) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1386) 
     Caused by: java.lang.SecurityException: "network" location provider requires ACCESS_COARSE_LOCATION or ACCESS_FINE_LOCATION permission.:

主要 Activity :

    public class MainActivity extends AppCompatActivity {


TextView tv;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        tv= this.<TextView>findViewById(R.id.tv);
    }

    public void onClick(View view) {
        // Toast.makeText(this, "hi sahar", Toast.LENGTH_SHORT).show();
        GpsTracker gpsTracker = new GpsTracker(this);
         if (gpsTracker.canGetLocation()){
                double lat = gpsTracker.getLatitude();
                double lon= gpsTracker.getLongitude();
             tv.append("Your Location is - \nLat: " + lat+ "\nLong: " + lon);
            // Toast.makeText(this, "Location is \n lat : " + lat + "\n lon : " +lon , 
            Toast.LENGTH_SHORT).show();
         }else {
             gpsTracker.showGpsAlertDialog();
         }


    }

最佳答案

您需要请求用户允许您的应用访问位置权限

ACCESS_COARSE_LOCATION 和/或 ACCESS_FINE_LOCATION

在获取设备位置之前。

检查这个thread 还有这个link

关于java - 如何解决这个 GPS 问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59509447/

相关文章:

java - 线程和可运行

java - 在java程序中存储字符串

android - 是否可以在 LinearLayout 的宽度上均匀分布按钮

android - 每隔几分钟获取一次 Android GPS 位置

java - Location.getLatitude 方法返回非精度 double ,这对 GPS 坐标不利

java - 使用 JSF 从 URL 中删除 Foobar.xhtml

java - 你如何在java中返回一个数组对象?

java - Firebase 实时数据库在查询之间按单词搜索?

java - 从 URL 部分加载图像,就像在 WhatsApp 中实现的一样

ios - MKReverseGeocoder不返回SubAdministrativeArea