使用位置权限时应用崩溃

时间:2018-02-08 07:35:44

标签: android google-location-services

我是android开发和java的新手。我正在尝试从Build your first app学习一些Android代码。 现在,问题是,只要我添加FusedLocation(发送代码中的命令部分),它就会崩溃。代码的当前状态(主要是第一个应用程序,以及来自getting the last location的几行)是:

MainActivity.java

package com.example.myfirstapp;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.EditText;


public class MainActivity extends AppCompatActivity {
    public static final String EXTRA_MESSAGE = "com.example.myfirstapp.MESSAGE";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    /** Called when the user taps the Send button */
    public void sendMessage(View view) {
        Intent intent = new Intent(this, DisplayMessageActivity.class);
        EditText editText = (EditText) findViewById(R.id.editText);
        String message = editText.getText().toString();
        intent.putExtra(EXTRA_MESSAGE, message);
        startActivity(intent);
    }
}

DisplayMessageActivity.java

package com.example.myfirstapp;

import android.content.Intent;
import android.location.Location;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;

public class DisplayMessageActivity extends AppCompatActivity {
    private FusedLocationProviderClient mFusedLocationClient;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_message);

        // Get the Intent that started this activity and extract the string
        Intent intent = getIntent();
        String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

        //Location
        mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);                        
        TextView textView = findViewById(R.id.textView);
        textView.setText(message);
    }
}

应用程序的构建没有错误,但是当我按下发送按钮时avd中的应用程序崩溃了。应用程序启动日志为:

02/08 13:00:44: Launching app
$ adb install-multiple -r -t -p com.example.myfirstapp /home/rudra/AndroidStudioProjects/MyFirstApp/app/build/intermediates/split-apk/debug/slices/slice_9.apk 
Split APKs installed
$ adb shell am start -n "com.example.myfirstapp/com.example.myfirstapp.MainActivity" -a android.intent.action.MAIN -c android.intent.category.LAUNCHER
Client not ready yet..Waiting for process to come online
Connected to process 6972 on device emulator-5554
Capturing and displaying logcat messages from application. This behavior can be disabled in the "Logcat output" section of the "Debugger" settings page.
I/InstantRun: starting instant run server: is main process
D/OpenGLRenderer: HWUI GL Pipeline
I/zygote: android::hardware::configstore::V1_0::ISurfaceFlingerConfigs::hasWideColorDisplay retrieved: 0
I/OpenGLRenderer: Initialized EGL, version 1.4
D/OpenGLRenderer: Swap behavior 1
W/OpenGLRenderer: Failed to choose config with EGL_SWAP_BEHAVIOR_PRESERVED, retrying without...
D/OpenGLRenderer: Swap behavior 0
D/EGL_emulation: eglCreateContext: 0x9fe040c0: maj 3 min 0 rcv 3
D/EGL_emulation: eglMakeCurrent: 0x9fe040c0: ver 3 0 (tinfo 0x9fe032c0)
E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf
E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008cdf
E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008824
E/eglCodecCommon: glUtilsParamSize: unknow param 0x00008824
D/EGL_emulation: eglMakeCurrent: 0x9fe040c0: ver 3 0 (tinfo 0x9fe032c0)
V/View: dispatchProvideAutofillStructure(): not laid out, ignoring 0 children of 1073741830
I/AssistStructure: Flattened final assist data: 2144 bytes, containing 1 windows, 8 views
I/zygote: Do partial code cache collection, code=27KB, data=30KB
I/zygote: After code cache collection, code=27KB, data=30KB
I/zygote: Increasing code cache capacity to 128KB

(此日志中的引用部分为红色,可能是错误。)

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.myfirstapp">
      <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity android:name=".DisplayMessageActivity"
                android:parentActivityName=".MainActivity">
            <!-- The meta-data tag is required if you support API level 15 and lower -->
            <meta-data
                android:name="android.support.PARENT_ACTIVITY"
                android:value=".MainActivity" />
        </activity>
    </application>
</manifest>

另外,请告诉我,我是否可以将location作为字符串放在textview中。

更新 添加权限后,我的DisplayMessege为:

package com.example.myfirstapp;

import android.content.Intent;
import android.location.Location;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.TextView;

import com.google.android.gms.location.FusedLocationProviderClient;
import com.google.android.gms.location.LocationServices;
import com.google.android.gms.tasks.OnSuccessListener;

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_dialog_location, new DialogInterface.OnClickListener() {
                       @Override
                       public void onClick(DialogInterface dialogInterface, int i) {
                           //Prompt the user once explanation has been shown
                           ActivityCompat.requestPermissions(PlaceOrder.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;
    }
}


public class DisplayMessageActivity extends AppCompatActivity {
    private FusedLocationProviderClient mFusedLocationClient;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_display_message);

        // Get the Intent that started this activity and extract the string
        Intent intent = getIntent();
        String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);

        //Location
        if (checkLocationPermission()) {

            mFusedLocationClient = LocationServices.getFusedLocationProviderClient(this);

            mFusedLocationClient.getLastLocation()
                    .addOnSuccessListener(this, new OnSuccessListener<Location>() {
                        @Override
                        public void onSuccess(Location location) {
                            // Got last known location. In some rare situations this can be null.
                            if (location != null) {
                                // Logic to handle location object
                            }
                        }
                    });
        }
        else {
            Toast.makeText(this, "Location Permision is not granted", Toast.LENGTH_SHORT).show();

        }
        }

        // Capture the layout's TextView and set the string as its text
        TextView textView = findViewById(R.id.textView);
        textView.setText(message);
    }
}

这给出了构建错误:

/home/rudra/AndroidStudioProjects/MyFirstApp/app/src/main/java/com/example/myfirstapp/DisplayMessageActivity.java
Error:(13, 8) error: class, interface, or enum expected
Error:(30, 31) error: class, interface, or enum expected
Error:(35, 24) error: class, interface, or enum expected
Error:(41, 8) error: class, interface, or enum expected
Error:(46, 9) error: class, interface, or enum expected
Error:(48, 5) error: class, interface, or enum expected
Error:(50, 5) error: class, interface, or enum expected
Error:(89, 25) error: <identifier> expected
Error:(89, 33) error: <identifier> expected
Error:(91, 1) error: class, interface, or enum expected
Error:Execution failed for task ':app:compileDebugJavaWithJavac'.
> Compilation failed; see the compiler error output for details.
Information:BUILD FAILED in 0s

我知道这是愚蠢的,我正在做一些愚蠢的错误,但请帮助 的问候,

1 个答案:

答案 0 :(得分:1)

您可以将此代码用作运行时的位置权限。

 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_dialog_location, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialogInterface, int i) {
                            //Prompt the user once explanation has been shown
                            ActivityCompat.requestPermissions(PlaceOrder.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;
    }
}

并简单地使用此代码

if (checkLocationPermission()){
            //do your work

        }
        else {
            Toast.makeText(this, "Location Permision is not granted", Toast.LENGTH_SHORT).show();
        }

希望这有帮助