Android 使用位置权限时应用程序崩溃

Android 使用位置权限时应用程序崩溃,android,google-location-services,Android,Google Location Services,我对android开发和java非常陌生。我正在努力学习一些android代码。 现在,问题是,只要我添加FusedLocation(发送代码中的commanted部分),它就会崩溃。代码的当前状态是(大部分是第一个应用程序,很少有行来自)是: MainActivity.java package com.example.myfirstapp; import android.content.Intent; import android.support.v7.app.AppCompatActivi

我对android开发和java非常陌生。我正在努力学习一些android代码。 现在,问题是,只要我添加
FusedLocation
(发送代码中的commanted部分),它就会崩溃。代码的当前状态是(大部分是第一个应用程序,很少有行来自)是:

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);
    }
}
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);
    }
}

DisplayMessageActivity.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);
    }
}
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)
(此日志中引用的部分为红色,可能有错误。)

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>
这将导致生成错误:

/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
/home/rudra/AndroidStudioProjects/MyFirstApp/app/src/main/java/com/example/MyFirstApp/DisplayMessageActivity.java
错误:(13,8)错误:应为类、接口或枚举
错误:(30,31)错误:应为类、接口或枚举
错误:(35、24)错误:应为类、接口或枚举
错误:(41,8)错误:应为类、接口或枚举
错误:(46,9)错误:应为类、接口或枚举
错误:(48,5)错误:应为类、接口或枚举
错误:(50,5)错误:应为类、接口或枚举
错误:(89,25)错误:应为
错误:(89,33)错误:应为
错误:(91,1)错误:应为类、接口或枚举
错误:任务“:app:compiledBugJavaWithJavaC”的执行失败。
>编译失败;有关详细信息,请参阅编译器错误输出。
信息:生成在0秒内失败
我知道这是我的错,我犯了一些愚蠢的错误,但请帮忙
关于,

您可以使用此代码在运行时设置位置权限

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

希望这有帮助

您是否添加了运行时权限请求?你在测试哪个操作系统版本?我在AVD27上使用它。如何处理运行时权限请求?请解释。您需要有运行时权限请求,您可以共享您的清单吗。这是我对另一个关于外部存储许可的问题的回答。因此,您可能需要使用“访问”和“位置”权限,而不是“外部存储”权限。别忘了在清单中添加权限。@AbdulKawee:manifest被添加了当我将此代码复制粘贴到我的代码时,我得到了大量的红色下划线,表明其中有错误,不是吗?你能检查一下吗?是的,那个会像这样的错误引起的,有活动名称的,请分享
if (checkLocationPermission()){
            //do your work

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