我正在制作音乐播放器应用并在其中创建了一个播放列表。对于marshmallow设备(API 6.0.0),我需要获得READ_EXTERNAL_STORAGE权限。所以我创建了一个类Permission.java,以便在需要时请求权限(关于检查权限和请求它的所有方法都在其中实现,在此应用程序中我使用的是Permission.java实例)。但我不确定方法 onRequestPermissionsResult()我应该在哪里实现它。如果在权限类本身那么如何在MainActivity.java中如何? 在这些上传的文件中,我在Permission.java中实现了 onRequestPermissionsResult()
请帮助!
MainActivity.java
package com.abhi.music.musicplayer1;
import android.Manifest;
import android.content.ContentResolver;
import android.content.ContentUris;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.support.design.widget.CoordinatorLayout;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.view.Menu;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
public class MainActivity extends AppCompatActivity {
public String TAG="permission_log";
private static final File EXTERNAL_LOCATION= Environment.getExternalStorageDirectory();
ListView PlaylistView;
TextView tV;
ArrayList<String> songNamesList= new ArrayList<String>();
String[] songNamesInStringArray;
private static final int REQUEST_CODE= 1;
public long sampleID;
Permission permission;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
tV= (TextView) findViewById(R.id.textView);
permission= new Permission(this,getApplicationContext(),Manifest.permission.READ_EXTERNAL_STORAGE,tV,REQUEST_CODE);
permission.permission_allowed();
//PlaylistView= (ListView) findViewById(R.id.PlaylistView);
//findMediaFromSD();
//findMediaFromInternal();
//songNamesInStringArray= new String[songNamesList.size()];
//songNamesInStringArray= songNamesList.toArray(songNamesInStringArray);
//ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(getApplicationContext(),R.layout.listview_layout,songNamesInStringArray);
///PlaylistView.setAdapter(arrayAdapter);
//Toast.makeText(getApplicationContext(),songNamesInStringArray[1],Toast.LENGTH_LONG).show();
//playMusic();
}
public void findMediaFromSD()
{
ContentResolver contentResolver = getContentResolver();
Uri uri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor cursor = contentResolver.query(uri, null, null, null, null);
if (cursor == null) {
// query failed, handle error.
} else if (!cursor.moveToFirst()) {
// no media on the device
} else {
int titleColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
do {
long thisId = cursor.getLong(idColumn);
sampleID=thisId;
String thisTitle = cursor.getString(titleColumn);
// ...process entry...
// Toast(thisTitle);
Log.d("Add hua?", "beforre adding in songNameslist");
songNamesList.add(thisTitle);
Log.d("Add hua?", "after adding in songNameslist");
} while (cursor.moveToNext());
}
}
public void findMediaFromInternal()
{
ContentResolver contentResolver = getContentResolver();
Uri uri = android.provider.MediaStore.Audio.Media.INTERNAL_CONTENT_URI;
Cursor cursor = contentResolver.query(uri, null, null, null, null);
if (cursor == null) {
// query failed, handle error.
} else if (!cursor.moveToFirst()) {
// no media on the device
} else {
int titleColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = cursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
do {
long thisId = cursor.getLong(idColumn);
String thisTitle = cursor.getString(titleColumn);
// ...process entry...
// Toast(thisTitle);
Log.d("Add hua?", "before adding in songNameslist");
songNamesList.add(thisTitle);
Log.d("Add hua?", "after adding in songNameslist");
} while (cursor.moveToNext());
}
}
public void playMusic()
{
Uri contentUri= ContentUris.withAppendedId(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,sampleID);
MediaPlayer mp= new MediaPlayer();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mp.setDataSource(getApplicationContext(), contentUri);
} catch (IOException e) {
e.printStackTrace();
Log.d("Media","Error");
}
mp.start();
Toast("mp started");
Toast.makeText(getApplicationContext(),"sample id is"+ sampleID,Toast.LENGTH_LONG);
}
public void Toast(String text)
{
Toast.makeText(getApplicationContext(),text,Toast.LENGTH_SHORT).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
Permission.java 类是
package com.abhi.music.musicplayer1;
import android.Manifest;
import android.app.Activity;
import android.content.Context;
import android.content.pm.PackageManager;
import android.support.design.widget.Snackbar;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
/**
* Created by abhi on 2/3/2016.
*/
public class Permission extends ActivityCompat{
private String Per; // Remember to put the per string as menifest.permission.READ_EXTERNAL_SOURCE or any other READ_...
private Context context;
private View view;
private Activity activity;
private static final int PERMISSION_REQUEST_CODE = 1;
private static final int Request_code=1;
public String TAG="permission_log";
public Permission(Activity activity,Context context,String Per, View view, final int Request_code)
{
this.activity=activity;
this.Per=Per;
this.context=context;
this.view=view;
//this.Request_code=Request_code;
}
public void permission_allowed(){
checkPermission();
Log.v(TAG, "check permission done");
RequestPermission();
Log.v(TAG, "request permission done");
}
public void onRequestPermissionsResult(int requestCode,
String permissions[], int[] grantResults) {
Log.v(TAG,"mil gayi hai");
switch (requestCode) {
case PERMISSION_REQUEST_CODE: {
// If request is cancelled, the result arrays are empty.
if (grantResults.length > 0
&& grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// permission was granted, yay! Do the
// contacts-related task you need to do.
Log.v(TAG,"mil gayi hai");
} else {
// permission denied, boo! Disable the
// functionality that depends on this permission.
Log.v(TAG,"mil gayi hai");
}
return;
}
// other 'case' lines to check for other
// permissions this app might request
}
}
private boolean checkPermission()
{
int permissionCheck = ContextCompat.checkSelfPermission(context,
Per);
//Log.v(TAG, "true");
if(permissionCheck==PackageManager.PERMISSION_GRANTED)
{
// Log.v(TAG,"true");
return true;
}
else {
//Log.v(TAG,"true");
return false;
}
}
private void RequestPermission() {
Log.v(TAG,"in Request permission");
if (!checkPermission()) {
Log.v(TAG,"in Request permission, check permission false");
if (ActivityCompat.shouldShowRequestPermissionRationale(activity, Per)) {
Toast.makeText(context, "second time aa raha hai", Toast.LENGTH_LONG).show();
Log.v(TAG, "in Request permission, check permission false and not first time");
}
else
{
Log.v(TAG,"in Request permission, check permission false and not first time");
ActivityCompat.requestPermissions(activity,
new String[]{Per},
Request_code);
Toast.makeText(context, "First time aa raha hai", Toast.LENGTH_LONG).show();
}
}
else {
Log.v(TAG,"in Request permission, check permission false");
}
}
}
Content_main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:paddingBottom="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:showIn="@layout/activity_main" tools:context=".MainActivity">
<ListView
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/PlaylistView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:backgroundTint="#accef6"
android:layout_above="@+id/textView" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Large Text"
android:id="@+id/textView"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:layout_marginBottom="68dp" />
</RelativeLayout>
错误我得到的是
02-04 10:02:51.246 12267-12288/com.abhi.music.musicplayer1 E/Surface: getSlotFromBufferLocked: unknown buffer: 0xeac09230
02-04 10:02:51.889 12267-12288/com.abhi.music.musicplayer1 E/Surface: getSlotFromBufferLocked: unknown buffer: 0xeac09310
答案 0 :(得分:3)
使用权限类不是一种好办法。
在您需要权限的活动中,只需致电:
ActivityCompat.requestPermissions(this,
new String[]{Per},
Request_code);
并且在同一个Activity中,相应地处理onRequestPermissionsResult
方法中的请求