谷歌地图位置无法在android一加pohone中工作

时间:2019-04-10 06:58:55

标签: android google-maps

您好,在下面的代码中,我有一个名为set的按钮。如果按set按钮,则正在加载地图并在其中设置当前位置,这会显示纬度和经度。 现在,我尝试按设置的位置,使我的应用在一部手机上崩溃。

java.lang.RuntimeException: Unable to start activity ComponentInfo{in.chipmonk.havellsolarapp/in.chipmonk.havellsolarapp.SplashActivity}: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=in.chipmonk.havellsolarapp/.bluetoothcommunication.BleService }: app is in background uid UidRecord{2046e61 u0a278 TPSL idle change:idle|cached procs:1 seq(0,0,0)}
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3037)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3172)
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78)
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108)
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68)
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1906)
        at android.os.Handler.dispatchMessage(Handler.java:106)
        at android.os.Looper.loop(Looper.java:193)
        at android.app.ActivityThread.main(ActivityThread.java:6863)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858)
     Caused by: java.lang.IllegalStateException: Not allowed to start service Intent { cmp=in.chipmonk.havellsolarapp/.bluetoothcommunication.BleService }: app is in background uid UidRecord{2046e61 u0a278 TPSL idle change:idle|cached procs:1 seq(0,0,0)}
        at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1595)
        at android.app.ContextImpl.startService(ContextImpl.java:1550)
        at android.content.ContextWrapper.startService(ContextWrapper.java:664)
        at in.chipmonk.havellsolarapp.SplashActivity.onCreate(SplashActivity.java:23)
        at android.app.Activity.performCreate(Activity.java:7149)
        at android.app.Activity.performCreate(Activity.java:7140)
        at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1288)
        at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:3017)
        at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:3172) 
        at android.app.servertransaction.LaunchActivityItem.execute(LaunchActivityItem.java:78) 
        at android.app.servertransaction.TransactionExecutor.executeCallbacks(TransactionExecutor.java:108) 
        at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:68) 
        at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1906) 
        at android.os.Handler.dispatchMessage(Handler.java:106) 
        at android.os.Looper.loop(Looper.java:193) 
        at android.app.ActivityThread.main(ActivityThread.java:6863) 
        at java.lang.reflect.Method.invoke(Native Method) 
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:537) 
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:858) 
2019-04-10 12:15:52.011 32007-32217/in.chipmonk.havellsolarapp E/AndroidRuntime: FATAL EXCEPTION: Thread-3
    Process: in.chipmonk.havellsolarapp, PID: 32007

下面是代码:

在下面的代码中尝试调试代码位置管理器崩溃,并且甚至不显示页面。我的应用崩溃了。

if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);

            LocationManager lm = (LocationManager) getApplicationContext().getSystemService(Context.LOCATION_SERVICE);
            boolean gps_enabled = false;
            boolean network_enabled = false;

            try {
                gps_enabled = lm.isProviderEnabled(LocationManager.GPS_PROVIDER);
            } catch (Exception ex) {
            }
            try

            {
                network_enabled = lm.isProviderEnabled(LocationManager.NETWORK_PROVIDER);
            } catch (Exception ex) {
            }

            if (!gps_enabled && !network_enabled)

            {
                // notify user
                AlertDialog.Builder dialog = new AlertDialog.Builder(MapsActivity.this);
                dialog.setMessage(getApplicationContext().getResources().getString(R.string.title_location_permission));
                dialog.setPositiveButton(getApplicationContext().getResources().getString(R.string.text_location_permission), new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        // TODO Auto-generated method stub
                        Intent myIntent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
                        MapsActivity.this.startActivity(myIntent);
                        //get gps
                    }
                });
                dialog.setNegativeButton(getApplicationContext().getString(R.string.ok), new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface paramDialogInterface, int paramInt) {
                        // TODO Auto-generated method stub

                    }
                });
                dialog.show();
            }


            ButterKnife.bind(this);
            mPref = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
            final SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map);
            mapFragment.getMapAsync(this);

        }
    }

    protected synchronized void buildGoogleApiClient() {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

    @Override
    public void onConnected(@Nullable Bundle bundle) {
        mLocationRequest = new LocationRequest();
        mLocationRequest.setInterval(1000);
        mLocationRequest.setFastestInterval(1000);
        mLocationRequest.setPriority(LocationRequest.PRIORITY_BALANCED_POWER_ACCURACY);
        if (ContextCompat.checkSelfPermission(this,
                Manifest.permission.ACCESS_FINE_LOCATION)
                == PackageManager.PERMISSION_GRANTED) {
            LocationServices.FusedLocationApi.requestLocationUpdates(mGoogleApiClient, mLocationRequest, this);
        }
    }

    @Override
    public void onConnectionSuspended(int i) {
    }

    @Override
    public void onConnectionFailed(@NonNull ConnectionResult connectionResult) {
    }

    @Override
    public void onLocationChanged(Location location) {

        mLastLocation = location;
        if (mCurrLocationMarker != null) {
            mCurrLocationMarker.remove();
        }

        LatLng latLng = new LatLng(location.getLatitude(), location.getLongitude());
        MarkerOptions markerOptions = new MarkerOptions();
        markerOptions.position(latLng);
        if(mMap != null) {
            markerOptions.title("Current Position");
            markerOptions.icon(BitmapDescriptorFactory.defaultMarker(BitmapDescriptorFactory.HUE_MAGENTA));
            mCurrLocationMarker = mMap.addMarker(markerOptions);
        }

               });
    }




    @Override
    public void onMapReady(GoogleMap googleMap)
    {
        mMap=googleMap;
        mMap.setMapType(GoogleMap.MAP_TYPE_HYBRID);
       // mMap.setOnMapLongClickListener(getApplicationContext());

        //Initialize Google Play Services
        if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            if (ContextCompat.checkSelfPermission(this,
                    Manifest.permission.ACCESS_FINE_LOCATION)
                    == PackageManager.PERMISSION_GRANTED) {
                //Location Permission already granted
                buildGoogleApiClient();
                mMap.setMyLocationEnabled(true);
            } else {
                //Request Location Permission
                checkLocationPermission();
            }
        }
        else {
            buildGoogleApiClient();
            mMap.setMyLocationEnabled(true);
        }
    }
    public static final int MY_PERMISSIONS_REQUEST_LOCATION = 99;
    public boolean checkLocationPermission() {
        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)) {

                // Show an explanation to the user *asynchronously* -- don't block
                // this thread waiting for the user's response! After the user
                // sees the explanation, try again to request the permission.
                new AlertDialog.Builder(this)
                        .setTitle(R.string.title_location_permission)
                        .setMessage(R.string.text_location_permission)
                        .setPositiveButton(R.string.ok, new DialogInterface.OnClickListener() {
                            @Override
                            public void onClick(DialogInterface dialogInterface, int i) {
                                //Prompt the user once explanation has been shown
                                ActivityCompat.requestPermissions(MapsActivity.this,
                                        new String[]{Manifest.permission.ACCESS_FINE_LOCATION},
                                        MY_PERMISSIONS_REQUEST_LOCATION);
                            }
                        })
                        .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);
            }
            return false;
        } else {
            return true;
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String permissions[], int[] grantResults) {
        switch (requestCode) {
            case MY_PERMISSIONS_REQUEST_LOCATION: {
                // If request is cancelled, the result arrays are empty.
                if (grantResults.length > 0
                        && grantResults[0] == PackageManager.PERMISSION_GRANTED) {

                    // permission was granted, yay! Do the
                    // location-related task you need to do.
                    if (ContextCompat.checkSelfPermission(this,
                            Manifest.permission.ACCESS_FINE_LOCATION)
                            == PackageManager.PERMISSION_GRANTED) {

                        //Request location updates:
                        //.requestLocationUpdates(provider, 400, 1, this);
                    }

                } else {

                    // permission denied, boo! Disable the
                    // functionality that depends on this permission.

                }
                return;
            }

        }
    }
    @OnClick(R.id.setLocation)
    public void onClick() {
        Intent intent = new Intent();
        String longtitude = mLongitude.getText().toString();
        checkLocationPermission();
        if (!TextUtils.isEmpty(longtitude)) {
            intent.putExtra(Constants.LONGITUDE, longtitude);
        } else {
            Toast.makeText(this, R.string.please_enter_longitude, Toast.LENGTH_SHORT).show();
            return;
        }
        String latitude = mLatitude.getText().toString();
        if (!TextUtils.isEmpty(latitude)) {
            intent.putExtra(Constants.LATITUDE, latitude);
        } else {
            Toast.makeText(this, R.string.please_enter_latitude, Toast.LENGTH_SHORT).show();
            return;
        }
        String latCommand = mSolarController.generatePacket("lat " +latitude,"00");
        String longitudeCmd = mSolarController.generatePacket("lon "+longtitude,"00");
        mPref.edit().putString(Constants.LAT_COMMAND,latCommand).commit();
        mPref.edit().putString(Constants.LONG_COMMAND,longitudeCmd).commit();
        mPref.edit().putString(Constants.LAST_LATITUDE,latitude).commit();
        mPref.edit().putString(Constants.LAST_LONGITUDE,latitude).commit();
        setResult(RESULT_OK, intent);
        finish();
    }
    @OnClick({R.id.back, R.id.location})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.back:
                setResult(RESULT_OK, new Intent());
                finish();
                break;
            case R.id.location:
                Intent intent = new Intent();
                String longtitude = mLongitude.getText().toString();
                if (!TextUtils.isEmpty(longtitude)) {
                    intent.putExtra(Constants.LONGITUDE, longtitude);
                } else {
                    Toast.makeText(this, R.string.please_enter_longitude, Toast.LENGTH_SHORT).show();
                    return;
                }
                String latitude = mLatitude.getText().toString();
                if (!TextUtils.isEmpty(latitude)) {
                    intent.putExtra(Constants.LATITUDE, latitude);
                } else {
                    Toast.makeText(this, R.string.please_enter_latitude, Toast.LENGTH_SHORT).show();
                    return;
                }
                Float lat = Float.parseFloat(latitude);
                if (lat > 90 || lat < -90) {
                    Toast.makeText(this, R.string.longitude_alert, Toast.LENGTH_SHORT).show();
                    return;
                }
                float lan = Float.parseFloat(longtitude);
                if (lan > 180 || lan < -180) {
                    Toast.makeText(this, R.string.latitude_alert, Toast.LENGTH_SHORT).show();
                    return;
                }
                String latCommand = mSolarController.generatePacket("lat " + latitude, "00");
                String longitudeCmd = mSolarController.generatePacket("long " + longtitude, "00");
                mPref.edit().putString(Constants.LAT_COMMAND, latCommand).commit();
                mPref.edit().putString(Constants.LONG_COMMAND, longitudeCmd).commit();
                mPref.edit().putString(Constants.LAST_LATITUDE, latitude).commit();
                mPref.edit().putString(Constants.LAST_LONGITUDE, latitude).commit();
                setResult(RESULT_OK, intent);
                finish();
                break;
        }
    }

0 个答案:

没有答案