Android 无法解析符号 OnRequestPermissionsResultCallback

Posted

技术标签:

【中文标题】Android 无法解析符号 OnRequestPermissionsResultCallback【英文标题】:Android Cannot resolve symbol OnRequestPermissionsResultCallback 【发布时间】:2016-06-15 17:48:34 【问题描述】:

我是 android 新手,我正在尝试构建一个应用程序来显示我当前的位置,我正在关注来自 google 链接 here 的 apidemos 中的设置。这是作业的一部分,所以我不想透露我的最终目标是什么。现在我希望能够在我的应用程序上使用 gps 位置。我将发布我的活动代码、xml 布局代码、清单代码和 gradle 代码。如果还有什么我需要发布的,请告诉我。我已经尝试搜索,但我找不到任何东西。另外,如果它有帮助,我主要是为我的手机制作这个。 Nexus 6p 安卓 6.0.1

编辑:得到 OnRequestPermissionsResultCallback 工作但仍然有 PermissionUtils 给我一个错误。

我会评论我的错误/无法解决的地方

XML 代码

<fragment xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_
    android:layout_
    android:id="@+id/map"
    tools:context=".MapsActivity"
    android:name="com.google.android.gms.maps.SupportMapFragment">

    <Button
        android:id="@+id/StartButton"
        android:layout_
        android:layout_
        android:layout_gravity="start|bottom"
        android:text="@string/Start"
        android:padding="10dp"
        android:layout_marginBottom="10dp"
        android:paddingLeft="10dp"
        android:onClick="start"/>
    <Button
        android:id="@+id/StopButton"
        android:layout_
        android:layout_
        android:layout_gravity="start|bottom"
        android:text="@string/Stop"
        android:padding="10dp"
        android:layout_marginBottom="10dp"
        android:layout_marginLeft="107dp"
        android:paddingLeft="10dp"
        android:onClick="stop"/>
    <Button
        android:id="@+id/CameraButton"
        android:layout_
        android:layout_
        android:layout_gravity="end|bottom"
        android:text="@string/Camera"
        android:padding="10dp"
        android:layout_marginBottom="10dp"
        android:layout_marginRight="107dp"
        android:paddingRight="10dp"
        android:onClick="openCamera"/>
    <Button
        android:id="@+id/ShareButton"
        android:layout_
        android:layout_
        android:layout_gravity="end|bottom"
        android:text="@string/Share"
        android:padding="10dp"
        android:layout_marginBottom="10dp"
        android:paddingRight="10dp"/>

</fragment>

这是我的活动

package com.example.name.app;

import android.Manifest;
import android.app.Activity;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.v4.app.FragmentActivity;

import android.view.View;

import com.google.android.gms.maps.GoogleMap;
import com.google.android.gms.maps.OnMapReadyCallback;
import com.google.android.gms.maps.SupportMapFragment;
import android.support.v4.content.ContextCompat;
import com.google.android.gms.maps.GoogleMap.OnMyLocationButtonClickListener;

import android.support.annotation.NonNull;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
import com.google.android.gms.maps.model.LatLng;
import com.google.android.gms.maps.model.MarkerOptions;

import android.content.Intent;

import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.widget.Button;



public class MapsActivity extends AppCompatActivity
        implements
        OnMyLocationButtonClickListener,
        OnMapReadyCallback,
        ActivityCompat.OnRequestPermissionsResultCallback  //ERROR on OnRequest...CallBack
    /**
     * Request code for location permission request.
     *
     * @see #onRequestPermissionsResult(int, String[], int[])
     */
    private static final int LOCATION_PERMISSION_REQUEST_CODE = 1;
    /**
     * Flag indicating whether a requested permission has been denied after returning in
     * @link #onRequestPermissionsResult(int, String[], int[]).
     */
    private boolean mPermissionDenied = false;

    Button startbutton;
    Button stopbutton;
    Button sharebutton;
    private GoogleMap mMap;
    static final int REQUEST_IMAGE_CAPTURE = 1;
    static final int REQUEST_TAKE_PHOTO = 1;

    String mCurrentPhotoPath;

    @Override
    protected void onCreate(Bundle savedInstanceState) 
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_maps);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);

        startbutton= (Button) findViewById(R.id.StartButton);
        stopbutton = (Button) findViewById(R.id.StopButton);
        sharebutton= (Button) findViewById(R.id.ShareButton);

    

    @Override
    public void onMapReady(GoogleMap googleMap) 
        mMap = googleMap;

        // Add a marker in Venice, Italy, and move the camera.
        /* LatLng venice = new LatLng(45.43, 12.33);
        mMap.addMarker(new MarkerOptions().position(venice).title("Marker in Venice"));
        mMap.moveCamera(CameraUpdateFactory.newLatLng(venice));*/

        mMap.setOnMyLocationButtonClickListener(this);
        enableMyLocation();
    

    private void enableMyLocation() 
        //ERROR CANNOT RESOLVE METHOD checkSelfPermission
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
                != PackageManager.PERMISSION_GRANTED) 
            // Permission to access the location is missing.
            //ERROR CANNOT RESOLVE SYMBOL PermissionUtils
            PermissionUtils.requestPermission(this, LOCATION_PERMISSION_REQUEST_CODE,
                    Manifest.permission.ACCESS_FINE_LOCATION, true);
         else if (mMap != null) 
            // Access to the location has been granted to the app.
            mMap.setMyLocationEnabled(true);
        
    

    @Override
    public boolean onMyLocationButtonClick() 
        Toast.makeText(this, "MyLocation button clicked", Toast.LENGTH_SHORT).show();
        // Return false so that we don't consume the event and the default behavior still occurs
        // (the camera animates to the user's current position).
        return false;
    

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) 
        if (requestCode != LOCATION_PERMISSION_REQUEST_CODE) 
            return;
        
        //ERROR CANNOT RESOLVE SYMBOL PermissionUtils

        if (PermissionUtils.isPermissionGranted(permissions, grantResults,
                Manifest.permission.ACCESS_FINE_LOCATION)) 
            // Enable the my location layer if the permission has been granted.
            enableMyLocation();
         else 
            // Display the missing permission error dialog when the fragments resume.
            mPermissionDenied = true;
        
    
    @Override
    protected void onResumeFragments() 
        super.onResumeFragments();
        if (mPermissionDenied) 
            // Permission was not granted, display error dialog.
            showMissingPermissionError();
            mPermissionDenied = false;
        
    
    //ERROR CANNOT RESOLVE SYMBOL PermissionUtils

    private void showMissingPermissionError() 
        PermissionUtils.PermissionDeniedDialog
                .newInstance(true).show(getSupportFragmentManager(), "dialog");
    

    public void start(View view)
        startbutton.setText("Running");
        stopbutton.setText("Stop");
    
    public void stop(View view)
        stopbutton.setText("Stopped");
        startbutton.setText("Start");
    
    private File createImageFile() throws IOException 
        // Create an image file name
        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "JPEG_" + timeStamp + "_";
        //Get location and store it
        File storageDir = new File (Environment.getExternalStoragePublicDirectory(
                Environment.DIRECTORY_PICTURES)+"/MyMap"); //Saves it in Pictures/MyMapp  but can only be viewd from file explorer
        File image = File.createTempFile(
                imageFileName,  /* prefix */
                ".jpg",         /* suffix */
                storageDir      /* directory */
        );
        // Save a file: path for use with ACTION_VIEW intents
        mCurrentPhotoPath = "file:" + image.getAbsolutePath();
        return image;
    
    public void openCamera(View view) 
        Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Ensure that there's a camera activity to handle the intent
        if (takePictureIntent.resolveActivity(getPackageManager()) != null) 
            // Create the File where the photo should go
            File photoFile = null;
            try 
                photoFile = createImageFile();
             catch (IOException ex) 
                // Error occurred while creating the File

            
            // Continue only if the File was successfully created
            if (photoFile != null) 
                takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                        Uri.fromFile(photoFile));
                startActivityForResult(takePictureIntent, REQUEST_TAKE_PHOTO);
                galleryAddPic();
            
        
    
    private void galleryAddPic() 
        Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
        File f = new File(mCurrentPhotoPath);
        Uri contentUri = Uri.fromFile(f);
        mediaScanIntent.setData(contentUri);
        this.sendBroadcast(mediaScanIntent);
    


这是我的安卓清单

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

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES" />
    <!--
 The ACCESS_COARSE/FINE_LOCATION permissions are not required to use
         Google Maps Android API v2, but are recommended.
    -->
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
    <uses-permission android:name="android.permission.CAMERA"> </uses-permission>

    <uses-feature android:name="android.hardware.camera"
        android:required="true" />
    <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="@string/google_maps_key" />
        <meta-data
            android:name="com.google.android.gms.version"
            android:value="@integer/google_play_services_version" />
        <activity
            android:name=".MapsActivity"
            android:label="@string/title_activity_maps"
            android:screenOrientation="portrait">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

这是我更新的构建 gradle

apply plugin: 'com.android.application'

android 
    compileSdkVersion 23
    buildToolsVersion "23.0.2"

    defaultConfig 
        applicationId "com.example.name.app"
        minSdkVersion 15
        targetSdkVersion 23
        versionCode 1
        versionName "1.0"
    
    buildTypes 
        release 
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        
    


dependencies 
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:appcompat-v7:23.2.0'
    compile 'com.google.android.gms:play-services:8.4.0'
    compile 'com.android.support:support-v13:23.2.0'

【问题讨论】:

你能把compilesdkversion和targetsdk版本改成23吗? @RavjitSingh 我该怎么做。我可以右键单击并打开模块设置并以这种方式进行更改吗? 不,在 gradle 文件中,您在您的问题中发布的最后一个文件 @RavjitSingh 我已将其更改为您所指示的内容。我会更新播放服务并尽快报告。我将在大约半小时后上课(现在上课)。感谢您迄今为止的帮助 @RavjitSingh onRequestPermissionsResultCallback 不再给我一个错误,但是我仍然有 PermissionUtils 给我一个错误。有什么建议吗? 【参考方案1】:

升级:

compileSdkVersion23 buildToolsVersion23.0.2 com.android.support:appcompat-v7com.android.support:support-v1323.2.0

您缺少的符号来自 appcompat-v7 的 23.x.y 版本;其他更改是保持主要版本同步。

另外,请注意7.5.0play-services 的一个相当旧的版本;我建议将其升级到 8.4.0

而且,请记住,鉴于targetSdkVersion 22,您的所有运行时权限都是毫无意义的。

【讨论】:

嗨,我按照您的指示更改了前两个要点。我不完全确定你所说的第三个是什么意思。对不起,我对此很陌生。我的targetsdkversion现在是23。我将在大约一个小时后更新我的游戏服务,因为我现在有课。我很快就会回来。感谢您的帮助 @SamuelJacksonJr:“我不完全确定您所说的第三个是什么意思”——它指的是您在 build.gradle 文件中拥有的两个 dependencies 嘿,我附上了更新的 build.gradle 文件,其中包含所有建议的更改。 onRequestPermissionResultsCallback 不再给我一个错误。 PermissionUtils 的三个实例仍然给我一个错误。有什么建议吗? @SamuelJacksonJr:Android SDK 中没有名为 PermissionUtils 的东西。我碰巧写了一个名为PermissionUtils 的类,但是您使用的API 与我的不一致。您将需要追踪您从哪里获得此代码并找出它的PermissionUtils 从哪里获得。 在我找到 PermissionUtils 类后让它工作。非常感谢你的帮助。对此非常陌生,我学到了很多东西。【参考方案2】:

我有类似的问题想知道为什么找不到 PermissionUtil 类。可以在 Github 的 googlemap/android-maps 示例 (https://github.com/googlemaps/android-samples/blob/master/ApiDemos/app/src/main/java/com/example/mapdemo/PermissionUtils.java) 中找到该类。我只是创建了一个 java 文件,复制了代码并替换了字符串资源。

【讨论】:

以上是关于Android 无法解析符号 OnRequestPermissionsResultCallback的主要内容,如果未能解决你的问题,请参考以下文章

Android Studio:无法解析符号 R [重复]

无法解析符号'setOnClickListener' - Android Studio

Android Studio 无法解析符号“TabLayout”

无法解析 Android Studio 上的符号“属性”

(Android和Firebase)无法解析符号“dataSnapshot”[关闭]

无法在 Android 中解析符号 repeatOnLifecycle