按下“获取位置”按钮后,我的应用崩溃

时间:2016-10-18 20:44:19

标签: java android crash gps

我从这里复制代码以获取我的应用中的坐标http://rdcworld-android.blogspot.hr/2012/01/get-current-location-coordinates-city.html 无论如何,当我按下#34;获取位置"按钮,应用程序崩溃和退出。

MainActivity.java

package com.lipa.flashlight;

import android.*;
import android.app.AlertDialog;
import android.content.ContentResolver;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.location.Address;
import android.location.Geocoder;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.ParcelFileDescriptor;
import android.provider.Settings;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.Toast;
import android.view.View.OnClickListener;

import java.io.IOException;
import java.util.List;
import java.util.Locale;

public class Main2Activity extends AppCompatActivity implements OnClickListener {    

    private LocationManager locationManager = null;
    private LocationListener locationListener = null;

    private Button location = null;
    private EditText editLocation = null;
    private ProgressBar pb =null;

    private static final String TAG = "Debug";
    private Boolean flag = false;

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

        pb = (ProgressBar) findViewById(R.id.progressBar1);
        pb.setVisibility(View.INVISIBLE);

        editLocation = (EditText) findViewById(R.id.editTextLocation);
        location = (Button) findViewById(R.id.location);
        location.setOnClickListener(this);
    }    

    @Override
    public void onClick(View v) {
        flag = displayGpsStatus();
        if (flag) {
            Log.v(TAG, "onClick");
            editLocation.setText("Please! move your device to" +
                    " see the changes in coordinates." + "\nWait...");

            pb.setVisibility(View.VISIBLE);
            locationListener = new MyLocationListener();

            if (ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED &&
                    ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_COARSE_LOCATION)
                            != PackageManager.PERMISSION_GRANTED) {    
                return;
            }
            locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);

        } else {
            alertbox("GPS STATUS!!", "Your GPS is: OFF");
        }
    }

    private Boolean displayGpsStatus(){
        ContentResolver contentResolver = getBaseContext().getContentResolver();
        boolean gpsStatus = Settings.Secure.isLocationProviderEnabled(contentResolver, LocationManager.GPS_PROVIDER);
        if(gpsStatus){
            return true;

        }else{
            return false;
        }    
    }

    protected void alertbox(String title, String mymessage){
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage("Your Device's GPS is disabled")
                .setCancelable(false)
                .setTitle("** Gps Status **")
                .setPositiveButton("Gps On", new DialogInterface.OnClickListener(){
                    public void onClick(DialogInterface dialog, int id) {
                        Intent myIntent = new Intent(
                                Settings.ACTION_SECURITY_SETTINGS);
                        startActivity(myIntent);
                        dialog.cancel();
                    }
                })
                .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id){
                        dialog.cancel();
                    }
                });
        AlertDialog alert = builder.create();
        alert.show();
    }

    private class MyLocationListener implements LocationListener {
        @Override
        public void onLocationChanged(Location loc){    

            editLocation.setText("");
            pb.setVisibility(View.INVISIBLE);
            Toast.makeText(getBaseContext(),"Location changed: Lat: "+
                    loc.getLatitude()+" Lng: " + loc.getLongitude(), Toast.LENGTH_SHORT).show();
            String longitude = "Longitude: " +loc.getLongitude();
            Log.v(TAG, longitude);
            String latitude = "Latitude: " +loc.getLatitude();
            Log.v(TAG, latitude);

            String cityName=null;
            Geocoder gcd = new Geocoder(getBaseContext(),
                    Locale.getDefault());
            List<Address> addresses;
            try {
                addresses = gcd.getFromLocation(loc.getLatitude(), loc
                        .getLongitude(), 1);
                if (addresses.size() > 0)
                    System.out.println(addresses.get(0).getLocality());
                cityName=addresses.get(0).getLocality();
            } catch (IOException e) {
                e.printStackTrace();
            }

            String s = longitude+"\n"+latitude +
                    "\n\nMy Currrent City is: "+cityName;
            editLocation.setText(s);    
        }

        @Override
        public void onProviderDisabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onProviderEnabled(String provider) {
            // TODO Auto-generated method stub
        }

        @Override
        public void onStatusChanged(String provider,
                                    int status, Bundle extras) {
            // TODO Auto-generated method stub
        }
    }
}

XML:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1">
<TextView
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Get Current Location and City Name"
    android:layout_weight="0.20"
    android:gravity="center"
    android:textSize="20sp" />
<EditText
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_weight="0.33"
    android:id="@+id/editTextLocation"
    android:editable="false">
    <requestFocus></requestFocus>
</EditText>
<LinearLayout
    android:id="@+id/layButtonH"
    android:layout_height="wrap_content"
    android:layout_width="fill_parent"
    android:gravity="center"
    android:layout_weight="0.15">
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get Location"
        android:id="@+id/location"></Button>
</LinearLayout>
<LinearLayout
    android:id="@+id/layloadingH"
    android:layout_height="wrap_content"
    android:layout_weight="0.20"
    android:layout_width="fill_parent"
    android:gravity="center">
    <ProgressBar
        android:layout_width="wrap_content"
        android:id="@+id/progressBar1"
        android:layout_height="wrap_content"></ProgressBar>
</LinearLayout>
</LinearLayout>

1 个答案:

答案 0 :(得分:0)

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

    return;
}

该应用是否有权限?如果没有,您的代码将无法访问requestLocationUpdates。

locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 5000, 10, locationListener);
  

minDistance参数还可用于控制位置更新的频率。如果它大于0,那么位置提供者只会在位置至少改变minDistance米时向您的应用程序发送更新,并且至少已经过了minTime毫秒

从LocationManager documentation

中考虑此部分at least minDistance meters, AND at least minTime milliseconds have passed