在我的其中一个应用中,我想为用户增加使用res / raw文件夹中的声音设置铃声的可能性。
由于我不知道该怎么做,我在这个网站上找到了一段代码。
我创建了我的项目的克隆,我想在将它调整到我的应用程序之前测试这段代码
这是代码:
File file = new File(Environment.getExternalStorageDirectory(),
"/myRingtonFolder/Audio/");
if (!file.exists()) {
file.mkdirs();
}
String path = Environment.getExternalStorageDirectory()
.getAbsolutePath() + "/myRingtonFolder/Audio/";
File f = new File(path + "/"+ name + ".mp3");
Uri mUri = Uri.parse("android.resource://"
+ context.getPackageName() + "/raw/" + name);
ContentResolver mCr = context.getContentResolver();
AssetFileDescriptor soundFile;
try {
soundFile = mCr.openAssetFileDescriptor(mUri, "r");
} catch (FileNotFoundException e) {
soundFile = null;
}
try {
byte[] readData = new byte[1024];
FileInputStream fis = soundFile.createInputStream();
FileOutputStream fos = new FileOutputStream(f);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
}
fos.close();
} catch (IOException io) {
}
ContentValues values = new ContentValues();
values.put(MediaStore.MediaColumns.DATA, f.getAbsolutePath());
values.put(MediaStore.MediaColumns.TITLE, name);
values.put(MediaStore.MediaColumns.MIME_TYPE, "audio/mp3");
values.put(MediaStore.MediaColumns.SIZE, f.length());
values.put(MediaStore.Audio.Media.ARTIST, R.string.app_name);
values.put(MediaStore.Audio.Media.IS_RINGTONE, true);
values.put(MediaStore.Audio.Media.IS_NOTIFICATION, true);
values.put(MediaStore.Audio.Media.IS_ALARM, true);
values.put(MediaStore.Audio.Media.IS_MUSIC, true);
Uri uri = MediaStore.Audio.Media.getContentUriForPath(f
.getAbsolutePath());
Uri newUri = mCr.insert(uri, values); //errror here
try {
RingtoneManager.setActualDefaultRingtoneUri(context,
RingtoneManager.TYPE_RINGTONE, newUri);
Settings.System.putString(mCr, Settings.System.RINGTONE,
newUri.toString());
} catch (Throwable t) {
}
问题是我收到此错误:
FATAL EXCEPTION: main
Process: com.mtoy.tiboxinshape, PID: 27721
java.lang.NullPointerException: Attempt to invoke virtual method 'java.io.FileInputStream android.content.res.AssetFileDescriptor.createInputStream()' on a null object reference
at com.mtoy.tiboxinshape.SoundAdaptateur$2.onLongClick(SoundAdaptateur.java:117)
at android.view.View.performLongClick(View.java:5243)
at android.widget.TextView.performLongClick(TextView.java:9225)
at android.view.View$CheckForLongPress.run(View.java:21127)
at android.os.Handler.handleCallback(Handler.java:739)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5417)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
我知道问题来自这一行:Uri newUri = mCr.insert(uri, values);
。我试图在我的清单中添加权限,但我仍然收到此错误
你能帮我找到问题吗。
答案 0 :(得分:0)
使用23个Android版本,您需要在代码中询问授权,而不仅仅是在manifest.xml中。一切都在这里解释: https://developer.android.com/training/permissions/requesting.html