在android studio中单击按钮时无法查看当前坐标

Posted

技术标签:

【中文标题】在android studio中单击按钮时无法查看当前坐标【英文标题】:Unable to view current coordinates on button click in android studio 【发布时间】:2017-07-06 23:04:20 【问题描述】:

我正在创建一个应用程序,它将从DB 获取用户名并打印ID,然后单击按钮将显示当前的GPS coordinates。我已经实现了它,但不知道为什么它不起作用。

这是我的Manifest 文件

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

下面是我的MainActivity.java

public class MainActivity extends AppCompatActivity implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, LocationListener 


private static final String TAG = "MainActivity";
private TextView tv_lat;
private TextView tv_long;
private Button btn_loc;
private GoogleApiClient googleApiClient;
private Location location;
private LocationManager mLocationManager;
private LocationManager locationManager;

private LocationRequest locationRequest;
private LocationListener locationListener;
private long UPDATE_INTERVAL = 2 * 1000;  /* 10 secs */
private long FASTEST_INTERVAL = 2000; /* 2 sec */

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

    tv_lat = (TextView)findViewById(R.id.tv_lat);
    tv_long = (TextView)findViewById(R.id.tv_long);
    btn_loc = (Button)findViewById(R.id.btn_loc);


    // show location button click event
    btn_loc.setOnClickListener(new View.OnClickListener() 
        @Override
        public void onClick(View v) 
            googleApiClient = new GoogleApiClient.Builder(MainActivity.this)
                    .addConnectionCallbacks(MainActivity.this)
                    .addOnConnectionFailedListener(MainActivity.this)
                    .addApi(LocationServices.API)
                    .build();


        
    );

    mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

    checkLocation(); //check whether location service is enable or not in your  phone



 @Override
public void onConnected(Bundle bundle) 

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

    location = LocationServices.FusedLocationApi.getLastLocation(googleApiClient);

    if(location == null)
    
        startLocationUpdates();
    
    if (location != null)
    

    
    else 
        Toast.makeText(this, "Location not Detected", Toast.LENGTH_SHORT).show();
    



 @Override
public void onConnectionSuspended(int i) 

    Log.i(TAG, "Connection Suspended");
    googleApiClient.connect();



@Override
public void onConnectionFailed(ConnectionResult connectionResult) 
    Log.i(TAG, "Connection failed. Error: " + connectionResult.getErrorCode());


@Override
protected void onStart() 
    super.onStart();
    if (googleApiClient != null) 
        googleApiClient.connect();
    


@Override
protected void onStop() 
    super.onStop();
    if (googleApiClient.isConnected()) 
        googleApiClient.disconnect();
    


private void startLocationUpdates() 

    // Create the location request
    locationRequest = LocationRequest.create()
            .setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY)
            .setInterval(UPDATE_INTERVAL)
            .setFastestInterval(FASTEST_INTERVAL);

    // Request location updates
    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;
    
    LocationServices.FusedLocationApi.requestLocationUpdates(googleApiClient,
            locationRequest, this);
    Log.d("reque", "--->>>>");


@Override
public void onLocationChanged(Location location) 

    double lattitude = location.getLatitude();
    double longitude = location.getLongitude();

    String msg = "Updated Location:  " +
            Double.toString(lattitude) + " , " +
            Double.toString(longitude);

    tv_lat.setText("Latitude is " + lattitude );
    tv_long.setText("Longitude is " + longitude);

    Toast.makeText(this, msg, Toast.LENGTH_SHORT).show();

    // You can now create a LatLng Object for use with maps
    LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());



private boolean checkLocation() 

   if(!isLocationEnabled())
    showAlert();

    return isLocationEnabled();



private boolean isLocationEnabled() 
    locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
    return locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) ||
            locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER);

public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
private void showAlert() 

    if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
            != PackageManager.PERMISSION_GRANTED) 
        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(this,
                Manifest.permission.ACCESS_FINE_LOCATION)) 

            final AlertDialog.Builder dialog = new AlertDialog.Builder(this);
            dialog.setTitle("Enable Location")
                    .setMessage("Your Locations Settings is set to 'Off'.\nPlease Enable Location to " +
                            "use this app")
                    .setPositiveButton("Location Settings", new DialogInterface.OnClickListener() 
                        @Override
                        public void onClick(DialogInterface paramDialogInterface, int paramInt) 

                            Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                            startActivity(myIntent);
                        
                    )
                    .setNegativeButton("Cancel", new DialogInterface.OnClickListener() 
                        @Override
                        public void onClick(DialogInterface paramDialogInterface, int paramInt) 

                        
                    );
            dialog.create().show();
        
    
    else 
        // No explanation needed, we can request the permission.
        ActivityCompat.requestPermissions(this,
                new String[]Manifest.permission.ACCESS_FINE_LOCATION,
                MY_PERMISSIONS_REQUEST_LOCATION );
    




当我在我的设备上运行我的应用程序时,会显示以下结果

当我点击get location coordinates 时,什么也没有发生。 logcat 中也没有显示错误或警告。

更新 1

我已将所有代码从button click 事件中移出

    googleApiClient = new GoogleApiClient.Builder(this)
            .addConnectionCallbacks(this)
            .addOnConnectionFailedListener(this)
            .addApi(LocationServices.API)
            .build();
    googleApiClient.connect();

    mLocationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);

然后调试它,我得到了以下结果。

我不知道为什么坐标没有显示:(

任何帮助将不胜感激。

【问题讨论】:

您在哪个 android 版本上运行它?棉花糖还是牛轧糖?您是否提供了权限? 我建议您阅读教程并从那里下载工作源代码。您将在那里找到所有详细信息。得到这个答案,你会在那里找到链接。 ***.com/questions/1513485/… @HammadNasir 我在棉花糖上运行它,是的,我已经设置了权限 【参考方案1】:

当您的设备超过 Android 6.0 Marshmallow 时,您必须检查应用程序设置中是否允许位置权限。您可以在设置中手动打开它,也可以使用运行时权限库。我为此找到了一个非常有用的库:https://github.com/ParkSangGwon/TedPermission

【讨论】:

它询问了我的许可,在允许之后,它仍然没有显示坐标:( 您是否在授予位置权限后尝试重启应用? 哦,是的,它现在可以工作了,但是为什么它在第一次运行时没有工作? 授予权限后是否调用 checkLocation 方法? 在授予权限后,您可以尝试重新实例化 GoogleApiClient 吗?这将管理 onLocationManage 等方法。【参考方案2】:

进入手机设置-->位置设置 检查您的移动 GPS 服务是否打开或关闭 如果它关闭,则打开。 希望这会有所帮助。

【讨论】:

我的位置设置已在我的设备中开启

以上是关于在android studio中单击按钮时无法查看当前坐标的主要内容,如果未能解决你的问题,请参考以下文章

为什么我在android studio中调试时看不到代码?

Android Studio:单击按钮时一一更新多个按钮的背景

如何单击图像按钮并将其显示在 Android Studio 的新页面中?

如何在单击按钮的 Android Studio 上发送邮件?

无法在Android Studio AVD Manager中启用“快照”并保存

使画布视图无效时单击按钮后应用程序崩溃(Android Studio,Java)