繁体   English   中英

Android GPS应用有时会崩溃

[英]Android GPS Application Sometimes Crashing

我有一个带有GPS按钮以获取您的位置的应用程序,还有一个Google Maps地点选择器。 只要您手动打开了应用程序的位置,这在大多数情况下都可以正常工作。 警报图标并未出现,无法让您打开应有的位置,它还会随机出现以下错误:

D / AndroidRuntime:关闭VM

  --------- beginning of crash E/AndroidRuntime: FATAL EXCEPTION: main Process: com.example.curtisboylan.myapplication, PID: 2443 java.lang.NullPointerException: Attempt to invoke virtual method 'double android.location.Location.getLatitude()' on a 

com.example.curtisboylan.myapplication.SearchScreen.onLocationChanged(SearchScreen.java:391)上com.google.android.gms.location.internal.zzk $ zzb.handleMessage(Unknown Source)处的null对象引用.dispatchMessage(Handler.java:102)在android.os.Looper.loop(Looper.java:154)在android.app.ActivityThread.main(ActivityThread.java:6119)在java.lang.reflect.Method.invoke( com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:886)的com.android.internal.os.ZygoteInit.main(ZygoteInit.java:776)的应用程序终止。

我将附上以下代码:

public class SearchScreen extends Fragment implements GoogleApiClient.ConnectionCallbacks, GoogleApiClient.OnConnectionFailedListener, com.google.android.gms.location.LocationListener {
    public final static String EXTRA_MESSAGE = "com.example.curtisboylan.myapplication";

    private GoogleApiClient client;
    private GridViewAdapter mAdapter;
    private ArrayList<String> listType;
    private ArrayList<Integer> listIcon;
    private String repairtype;
    private GridView gridView;

    private TextView tv;

    private Button contBtn;
    private Button googleLocBtn;
    private Button gpsBtn;
    private boolean setGPSloc = false;

    private Location mLocation;
    private LocationManager locationManager;
    private long UPDATE_INTERVAL = 2 * 1000;  /* 10 secs */
    private long FASTEST_INTERVAL = 2000;
    private LocationRequest mLocationRequest;
    private com.google.android.gms.location.LocationListener listener;

    private TextView mLatitudeTextView;
    private TextView mLongitudeTextView;
    private TextView tv2;

    Double longitude;
    Double latitude;

    public static SearchScreen newInstance(){
        SearchScreen fragment = new SearchScreen();
        return fragment;
    }

    public SearchScreen(){}

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);




        client = new GoogleApiClient.Builder(this.getActivity())
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();

        locationManager = (LocationManager) getActivity().getSystemService(Context.LOCATION_SERVICE);
        checkLocation();


    }



    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        final View view = inflater.inflate(R.layout.activity_main, container, false);

         tv = (TextView) view.findViewById(R.id.textView);

        prepareList();
        repairtype ="";

        text = (TextView) view.findViewById(R.id.txt_TextDateTime);
        btn_date = (Button) view.findViewById(R.id.btn_datePicker);

        btn_date.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                updateDate();
            }
        });

        contBtn = (Button) view.findViewById(R.id.button);
        contBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(getActivity(), TechnicianListView.class);
                intent.putExtra("message", repairtype);
                startActivity(intent);
            }
        });

        gpsBtn = (Button) view.findViewById(R.id.button3);
        gpsBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tv2.setText("" + getMyPosAddress(mLocation.getLatitude(), mLocation.getLongitude()));
            }
        });


        tv2 = (TextView) view.findViewById((R.id.textView));


        updateTextLabel();


        // prepared arraylist and passed it to the Adapter class
        mAdapter = new GridViewAdapter(getActivity(), listType, listIcon);

        // Set custom adapter to gridview
        gridView = (GridView) view.findViewById(R.id.gridView1);
        gridView.setAdapter(mAdapter);

        // Implement On Item click listener
        gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                    long arg3) {
                Toast.makeText(getActivity(), "DEBUG " + mAdapter.getItem(position), Toast.LENGTH_SHORT).show();
                repairtype = mAdapter.getItem(position);
            }
        });

        googleLocBtn = (Button) view.findViewById(R.id.googleLocBtn);
        googleLocBtn.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                findPlace(v.findViewById(android.R.id.content));
            }
        });


        return view;
    }



    //Calling method DateFormat and Calendar
    DateFormat formatDateTime = DateFormat.getDateInstance();
    Calendar dateTime = Calendar.getInstance();
    //Creating Vars
    private TextView text;
    private Button btn_date;


    private void updateDate() {
        new DatePickerDialog(getActivity(), d, dateTime.get(Calendar.YEAR), dateTime.get(Calendar.MONTH), dateTime.get(Calendar.DAY_OF_MONTH)).show();
    }


    DatePickerDialog.OnDateSetListener d = new DatePickerDialog.OnDateSetListener() {
        @Override
        public void onDateSet(DatePicker view, int year, int monthOfYear, int dayOfMonth) {
            dateTime.set(Calendar.YEAR, year);
            dateTime.set(Calendar.MONTH, monthOfYear);
            dateTime.set(Calendar.DAY_OF_MONTH, dayOfMonth);
            updateTextLabel();
        }
    };


    private void updateTextLabel() {
        text.setText(formatDateTime.format(dateTime.getTime()));
    }


    public void prepareList() {
        listType = new ArrayList<String>();

        listType.add("di1");
        listType.add("screen1");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");
        listType.add("placeholder");

        listIcon = new ArrayList<Integer>();

        listIcon.add(R.drawable.camerabrokenicon);
        listIcon.add(R.drawable.screenrepairicon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
        listIcon.add(R.drawable.placeholdericon);
    }

    public void testBtn(View v) {
       // tv.setText("Welcome");

    }

    public void findPlace(View v) {
        try {
            Intent intent =
                    new PlaceAutocomplete
                            .IntentBuilder(PlaceAutocomplete.MODE_FULLSCREEN)
                            .build(getActivity());
            startActivityForResult(intent, 1);
        } catch (GooglePlayServicesRepairableException e) {
            // TODO: Handle the error.
        } catch (GooglePlayServicesNotAvailableException e) {
            // TODO: Handle the error.
        }
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == 1) {
            if (resultCode == RESULT_OK) {
                Place place = PlaceAutocomplete.getPlace(this.getContext(), data);
                Log.e("Tag", "Place: " + place.getAddress() + place.getPhoneNumber());

                ((TextView) getView().findViewById(R.id.textView))
                        .setText("" + place.getName());

            } else if (resultCode == PlaceAutocomplete.RESULT_ERROR) {

            } else if (resultCode == RESULT_CANCELED) {
            }
        }
    }


    @Override
    public void onStart() {
        super.onStart();
        super.onStart();
        if (client != null) {
            client.connect();
        }


    }

    @Override
    public void onStop() {
        super.onStop();
        client.disconnect();
    }


    private String getMyPosAddress(double dbLat, double dbLon) {
        String addressString = "No address found";
        Geocoder gc = new Geocoder(getContext(), Locale.getDefault());

        try {
            List<android.location.Address> gclist ;

            gclist =  gc.getFromLocation(dbLat, dbLon, 1);


            if (gclist.size() > 0) {
                android.location.Address address = gclist.get(0);

                addressString = "" + address.getAddressLine(0) + ", " + address.getAdminArea();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }



        return addressString;
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {

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

            return;
        } startLocationUpdates();
        mLocation = LocationServices.FusedLocationApi.getLastLocation(client);
        if(mLocation == null){
            startLocationUpdates();
        }
        if (mLocation != null) {
            latitude = mLocation.getLatitude();
            longitude = mLocation.getLongitude();
        } else {
        }


    }

    protected void startLocationUpdates() {
        // Create the location request
        mLocationRequest = LocationRequest.create()
                .setPriority(LocationRequest.PRIORITY_HIGH_ACCURACY)
                .setInterval(UPDATE_INTERVAL)
                .setFastestInterval(FASTEST_INTERVAL);
        // Request location updates
        if (ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(getContext(), Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            return;
        }
        LocationServices.FusedLocationApi.requestLocationUpdates(client,
                mLocationRequest, this);
        Log.d("reque", "--->>>>");
    }

    @Override
    public void onConnectionSuspended(int i) {
        Log.i(TAG, "Connection Suspended");
        client.connect();
    }

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

    @Override
    public void onLocationChanged(Location location) {
        String msg = "Updated Location: " +
                Double.toString(location.getLatitude()) + "," +
                Double.toString(location.getLongitude());

        latitude = mLocation.getLatitude();
        longitude = mLocation.getLongitude();
        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
    }

    private boolean checkLocation() {
        if(!isLocationEnabled())
            showAlert();
        return isLocationEnabled();
    }

    private void showAlert() {
        final AlertDialog.Builder dialog = new AlertDialog.Builder(getContext());
        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.show();
    }

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



}

似乎在调用onLocationChanged时会收到NullPointerException,因此您的Location对象为null。

您可以检查if(location!= null),以免崩溃。

添加BroadcastReceiver,侦听gps提供程序中的更改。 这样,您将知道用户何时关闭GPS。 发生这种情况时,请更改用于计算用户位置的策略。

请检查清单文件中是否有适当的权限以及其他事项如果您正在android m中运行,则需要转到设置->应用程序->选择您的应用程序,然后手动进行权限启用..

或者在您的代码中使用对话框询问权限

ActivityCompat.requestPermissions(this, new String[]{ACCESS_FINE_LOCATION}, 200);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM