#java #android #android-fileprovider
#java — язык #Android #android-файлообменник #java #android-fileprovider
Вопрос:
Привет, друг, я работаю с mp3-плеером, мой Uri uri = Uri.parse («file:///» song.getGetpath()); отлично работает на устройстве 6.0, но не работает на устройстве 6.0 выше, как исправить с помощью fileprovider, я не знаю, как использовать fileprovider, я новичок, пожалуйста, помогите здесь, мой код синтаксического анализа uri, все мои аудиофайлы находятся на моем телефонном устройстве, и он возвращает нулевой параметр, который не может быть нулевым Uri uri = Uri.parse («file: ///» song. getGetpath());
here my class code
package music.playerforandroid;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;
import android.os.Environment;
import android.os.IBinder;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.provider.ContactsContract;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.ContextCompat;
import android.support.v4.content.FileProvider;
import android.support.v4.media.session.MediaSessionCompat;
import android.util.Log;
import android.view.View;
import android.Manifest;
import android.media.MediaPlayer;
import android.os.Handler;
import android.support.v4.app.NotificationManagerCompat;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;
import java.util.Random;
import android.net.Uri;
import android.content.ContentResolver;
import android.database.Cursor;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.RemoteViews;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
import com.cleveroad.audiovisualization.AudioVisualization;
import com.cleveroad.audiovisualization.VisualizerDbmHandler;
import com.sothree.slidinguppanel.SlidingUpPanelLayout;
import static music.playerforandroid.App.CHANNEL_ID_1;
public class MainActivity extends AppCompatActivity implements SeekBar.OnSeekBarChangeListener {
private BroadcastReceiver broadcastReceiver;
private ArrayList<Song> songList;
private ListView songView;
MediaPlayer mediaPlayer;
private MediaSessionCompat mediaSession;
private int currentSongIndex = 0;
Song song;
private SlidingUpPanelLayout slidingLayout;
Context mContext;
private Utilities utils;
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000;
private AudioVisualization audioVisualization;
private VisualizerDbmHandler handler;
int postion;
int totalduration;
int totalTime;
SeekBar seekBar;
private Handler mHandler = new Handler();
private NotificationManagerCompat notificationManager;
Uri uri;
ImageView rotate;
private long currentsongLength;
TextView elapsedTimeLabel, remainingTimeLabel;
TextView title, artist;
ImageView playchange;
ImageButton like, notlike, dislike, notdislike, next, pervious, repeat, reaptenable;
ImageButton play, pause, play_main, pause_main, shuffle, shufflenable;
private SlidingUpPanelLayout mLayout;
private boolean isShuffle;
private boolean checked;
private NotificationManagerCompat mNotificationManagerCompat;
@Override
protected void onCreate(final Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
songView = findViewById(R.id.song_list);
songList = new ArrayList<Song>();
artist = findViewById(R.id.artist);
title = findViewById(R.id.songname);
elapsedTimeLabel = findViewById(R.id.songtime);
remainingTimeLabel = findViewById(R.id.endTime);
seekBar = findViewById(R.id.seekBar3);
next = findViewById(R.id.next);
pervious = findViewById(R.id.pervious);
like = findViewById(R.id.imageButton2);
notlike = findViewById(R.id.imageButton2new);
dislike = findViewById(R.id.button);
notdislike = findViewById(R.id.buttontwo);
play = findViewById(R.id.play_button);
repeat = findViewById(R.id.repeat);
reaptenable = findViewById(R.id.repeatenable);
pause = findViewById(R.id.pause_button);
play_main = findViewById(R.id.play_button_main);
pause_main = findViewById(R.id.pause_button_main);
like = findViewById(R.id.imageButton2);
notlike = findViewById(R.id.imageButton2new);
dislike = findViewById(R.id.button);
notdislike = findViewById(R.id.buttontwo);
play = findViewById(R.id.play_button);
pause = findViewById(R.id.pause_button);
shuffle = findViewById(R.id.shuffle);
shufflenable = findViewById(R.id.shufflenable);
elapsedTimeLabel = findViewById(R.id.endTime);
remainingTimeLabel = findViewById(R.id.songtime);
play_main = findViewById(R.id.play_button_main);
pause_main = findViewById(R.id.pause_button_main);
mLayout = findViewById(R.id.activity_main);
rotate = findViewById(R.id.rotate);
audioVisualization = findViewById(R.id.visualizer_view);
seekBar.setOnSeekBarChangeListener(this);
utils = new Utilities();
mNotificationManagerCompat = NotificationManagerCompat.from(this);
getSongList();
Collections.sort(songList, new Comparator<Song>() {
public int compare(Song a, Song b) {
return a.getTitle().compareTo(b.getTitle());
}
});
SongAdapter songAdt = new SongAdapter(this, songList);
songView.setAdapter(songAdt);
songView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, final long id) {
play(position);
}
});
broadcastReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (action.equals("music.playerforandroid.ACTION_PAUSE_MUSIC")) {
if (mediaPlayer != null amp;amp; mediaPlayer.isPlaying()) {
mediaPlayer.pause();
rotate.clearAnimation();
}
pause.setVisibility(View.GONE);
play.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "Song is Pause", Toast.LENGTH_SHORT).show();
if (pause_main.getVisibility() == View.VISIBLE) {
pause_main.setVisibility(View.GONE);
play_main.setVisibility(View.VISIBLE);
}
} else if (action.equals("music.playerforandroid.ACTION_PLAY_MUSIC")) {
if (mediaPlayer == null) {
play(0);
} else {
mediaPlayer.start();
play.setVisibility(View.GONE);
pause.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "Song Is now Playing", Toast.LENGTH_SHORT).show();
if (play_main.getVisibility() == View.VISIBLE) {
play_main.setVisibility(View.GONE);
pause_main.setVisibility(View.VISIBLE);
Animation aniRotate = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate);
rotate.startAnimation(aniRotate);
}
}
} else if (action.equals("music.playerforandroid.NEXT_PLAY_MUSIC")) {
if (currentSongIndex < (songList.size() - 1)) {
play(currentSongIndex 1);
currentSongIndex = currentSongIndex 1;
} else {
// play first song
play(0);
currentSongIndex = 0;
}
} else if (action.equals("music.playerforandroid.PERVIOUS_PLAY_MUSIC")) {
if (currentSongIndex > 0) {
play(currentSongIndex - 1);
currentSongIndex = currentSongIndex - 1;
} else {
// play last song
play(songList.size() - 1);
currentSongIndex = songList.size() - 1;
}
}
}
};
repeat.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
repeat.setVisibility(View.GONE);
reaptenable.setVisibility(View.VISIBLE);
shuffle.setVisibility(View.VISIBLE);
shufflenable.setVisibility(View.GONE);
isShuffle = false;
checked = true;
Toast.makeText(getApplicationContext(), "Repeat ON", Toast.LENGTH_SHORT).show();
}
});
reaptenable.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
repeat.setVisibility(View.VISIBLE);
reaptenable.setVisibility(View.GONE);
checked = false;
Toast.makeText(getApplicationContext(), "Repeat OFF", Toast.LENGTH_SHORT).show();
}
});
shuffle.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
reaptenable.setVisibility(View.GONE);
repeat.setVisibility(View.VISIBLE);
checked = false;
isShuffle = true;
shuffle.setVisibility(View.GONE);
shufflenable.setVisibility(View.VISIBLE);
isShuffle = true;
Toast.makeText(getApplicationContext(), "Shuffle ON", Toast.LENGTH_SHORT).show();
}
});
shufflenable.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
shuffle.setVisibility(View.VISIBLE);
shufflenable.setVisibility(View.GONE);
isShuffle = false;
Toast.makeText(getApplicationContext(), "Shuffle OFF", Toast.LENGTH_SHORT).show();
}
});
like.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
notlike.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "You Like the Song", Toast.LENGTH_SHORT).show();
if (notdislike.getVisibility() == View.VISIBLE) {
notdislike.setVisibility(View.GONE);
}
}
});
notlike.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
notlike.setVisibility(View.GONE);
}
});
dislike.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
notdislike.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "You DisLike the Song", Toast.LENGTH_SHORT).show();
if (notlike.getVisibility() == View.VISIBLE) {
notlike.setVisibility(View.GONE);
}
}
});
notdislike.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
notdislike.setVisibility(View.GONE);
}
});
play.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mediaPlayer == null) {
play(0);
} else {
mediaPlayer.start();
}
play.setVisibility(View.GONE);
pause.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "Song Is now Playing", Toast.LENGTH_SHORT).show();
if (play_main.getVisibility() == View.VISIBLE) {
play_main.setVisibility(View.GONE);
pause_main.setVisibility(View.VISIBLE);
Animation aniRotate = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate);
rotate.startAnimation(aniRotate);
}
}
});
pause.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mediaPlayer != null amp;amp; mediaPlayer.isPlaying()) {
mediaPlayer.pause();
rotate.clearAnimation();
}
pause.setVisibility(View.GONE);
play.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "Song is Pause", Toast.LENGTH_SHORT).show();
if (pause_main.getVisibility() == View.VISIBLE) {
pause_main.setVisibility(View.GONE);
play_main.setVisibility(View.VISIBLE);
}
}
});
play_main.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mediaPlayer == null) {
play(0);
} else {
mediaPlayer.start();
}
play_main.setVisibility(View.GONE);
pause_main.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "Song Is now Playing", Toast.LENGTH_SHORT).show();
if (play.getVisibility() == View.VISIBLE) {
play.setVisibility(View.GONE);
pause.setVisibility(View.VISIBLE);
Animation aniRotate = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate);
rotate.startAnimation(aniRotate);
}
}
});
pervious.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (currentSongIndex > 0) {
play(currentSongIndex - 1);
currentSongIndex = currentSongIndex - 1;
} else {
// play last song
play(songList.size() - 1);
currentSongIndex = songList.size() - 1;
}
next.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (currentSongIndex < (songList.size() - 1)) {
play(currentSongIndex 1);
currentSongIndex = currentSongIndex 1;
} else {
// play first song
play(0);
currentSongIndex = 0;
}
}
});
}
});
pause_main.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (mediaPlayer != null amp;amp; mediaPlayer.isPlaying()) {
mediaPlayer.pause();
}
pause_main.setVisibility(View.GONE);
play_main.setVisibility(View.VISIBLE);
Toast.makeText(MainActivity.this, "Song is Pause", Toast.LENGTH_SHORT).show();
if (pause.getVisibility() == View.VISIBLE) {
pause.setVisibility(View.GONE);
play.setVisibility(View.VISIBLE);
rotate.clearAnimation();
}
}
});
}
@Override
public void onBackPressed() {
if (mLayout != null amp;amp;
(mLayout.getPanelState() == SlidingUpPanelLayout.PanelState.EXPANDED || mLayout.getPanelState() == SlidingUpPanelLayout.PanelState.ANCHORED)) {
mLayout.setPanelState(SlidingUpPanelLayout.PanelState.COLLAPSED);
} else {
super.onBackPressed();
}
}
public void getSongList() {
//retrieve song info
ContentResolver musicResolver = getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
if (musicCursor != null amp;amp; musicCursor.moveToFirst()) {
//get columns
int titleColumn = musicCursor.getColumnIndex(android.provider.MediaStore.Audio.Media.TITLE);
int idColumn = musicCursor.getColumnIndex(android.provider.MediaStore.Audio.Media._ID);
int artistColumn = musicCursor.getColumnIndex(android.provider.MediaStore.Audio.Media.ARTIST);
int dataColumn = musicCursor.getColumnIndex(android.provider.MediaStore.Audio.Media.DATA);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
String thisPath = musicCursor.getString(dataColumn);
songList.add(new Song(thisId, thisTitle, thisArtist, thisPath));
}
while (musicCursor.moveToNext());
}
}
public void play(int songindex) {
song = songList.get(songindex);
try {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
//file:///" song.getGetpath()
// final Uri data = FileProvider.getUriForFile(this, "myprovider", new File(song.getGetpath()));
Toast.makeText(getApplicationContext(), "" uri, Toast.LENGTH_SHORT).show();
Uri uri = Uri.parse("file:///" song.getGetpath());
mediaPlayer = MediaPlayer.create(mContext, uri);
title.setText(song.getTitle());
artist.setText(song.getArtist());
show();
handler = VisualizerDbmHandler.Factory.newVisualizerHandler(getApplicationContext(), mediaPlayer);
audioVisualization.linkTo(handler);
mediaPlayer.start();
seekBar.setProgress(0); seekBar.setMax(100);
updateProgressBar();
if (mediaPlayer != null amp;amp; mediaPlayer.isPlaying()) {
play.setVisibility(View.GONE);
pause.setVisibility(View.VISIBLE);
play_main.setVisibility(View.GONE);
pause_main.setVisibility(View.VISIBLE);
Animation aniRotate = AnimationUtils.loadAnimation(getApplicationContext(), R.anim.rotate);
rotate.startAnimation(aniRotate);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
if (checked) {
mediaPlayer.setLooping(true);
mediaPlayer.start();
} else if (isShuffle) {
// shuffle is on - play a random song
Random rand = new Random();
currentSongIndex = rand.nextInt((songList.size() - 1) - 0 1) 0;
play(currentSongIndex);
} else {
// no repeat or shuffle ON - play next song
if (currentSongIndex < (songList.size() - 1)) {
play(currentSongIndex 1);
currentSongIndex = currentSongIndex 1;
} else {
// play first song
play(0);
currentSongIndex = 0;
}
}
}
});
}
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "" e, Toast.LENGTH_SHORT).show();
}
}
public void forward() {
int currentPosition = mediaPlayer.getCurrentPosition();
// check if seekForward time is lesser than song duration
if (currentPosition seekForwardTime <= mediaPlayer.getDuration()) {
// forward song
mediaPlayer.seekTo(currentPosition seekForwardTime);
} else {
// forward to end position
mediaPlayer.seekTo(mediaPlayer.getDuration());
}
}
public void backword() {
int currentPosition = mediaPlayer.getCurrentPosition();
// check if seekBackward time is greater than 0 sec
if (currentPosition - seekBackwardTime >= 0) {
// forward song
mediaPlayer.seekTo(currentPosition - seekBackwardTime);
} else {
// backward to starting position
mediaPlayer.seekTo(0);
}
}
@Override
protected void onDestroy() {
super.onDestroy();
try {
mediaPlayer.release();
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "" e, Toast.LENGTH_SHORT).show();
}
}
public void updateProgressBar() {
mHandler.postDelayed(mUpdateTimeTask, 100);
}
private Runnable mUpdateTimeTask = new Runnable() {
public void run() {
long totalDuration = mediaPlayer.getDuration();
long currentDuration = mediaPlayer.getCurrentPosition();
// Displaying Total Duration time
remainingTimeLabel.setText("" utils.milliSecondsToTimer(totalDuration));
// Displaying time completed playing
elapsedTimeLabel.setText("" utils.milliSecondsToTimer(currentDuration));
// Updating progress bar
int progress = (int) (utils.getProgressPercentage(currentDuration, totalDuration));
//Log.d("Progress", "" progress);
seekBar.setProgress(progress);
// Running this thread after 100 milliseconds
mHandler.postDelayed(this, 100);
}
};
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTimeTask);
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
mHandler.removeCallbacks(mUpdateTimeTask);
int totalDuration = mediaPlayer.getDuration();
int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);
// forward or backward to certain seconds
mediaPlayer.seekTo(currentPosition);
// update timer progress again
updateProgressBar();
}
@Override
protected void onStart() {
super.onStart();
IntentFilter intentFilter=new IntentFilter();
intentFilter.addAction("music.playerforandroid.ACTION_PAUSE_MUSIC");
intentFilter.addAction("music.playerforandroid.ACTION_PLAY_MUSIC");
intentFilter.addAction("music.playerforandroid.NEXT_PLAY_MUSIC");
intentFilter.addAction("music.playerforandroid.PERVIOUS_PLAY_MUSIC");
registerReceiver(broadcastReceiver,intentFilter);
}
public void show(){
Bitmap largeImage = BitmapFactory.decodeResource(getResources(),R.drawable.musicicon);
PendingIntent pausePendingIntent = PendingIntent.getBroadcast(this, 1, new Intent("music.playerforandroid.ACTION_PAUSE_MUSIC"), 0);
PendingIntent playPendingIntent = PendingIntent.getBroadcast(this, 1, new Intent("music.playerforandroid.ACTION_PLAY_MUSIC"), 0);
PendingIntent nextPendingIntent = PendingIntent.getBroadcast(this, 1, new Intent("music.playerforandroid.NEXT_PLAY_MUSIC"), 0);
PendingIntent perviousPendingIntent = PendingIntent.getBroadcast(this, 1, new Intent("music.playerforandroid.PERVIOUS_PLAY_MUSIC"), 0);
Notification channel = new NotificationCompat.Builder(getApplicationContext(), CHANNEL_ID_1)
.setSmallIcon(R.drawable.ic_music)
.setContentTitle(song.getTitle())
.setContentText(song.getArtist())
.setLargeIcon(largeImage)
.addAction(R.drawable.ic_prev, "prev", perviousPendingIntent)
.addAction(R.drawable.ic_play, "play", playPendingIntent)
.addAction(R.drawable.ic_stat_name, "pause", pausePendingIntent)
.addAction(R.drawable.ic_next, "next", nextPendingIntent)
.setStyle(new android.support.v4.media.app.NotificationCompat.MediaStyle().
setShowActionsInCompactView(1, 2, 3))
.build();
mNotificationManagerCompat.notify(1, channel);
}
}
Комментарии:
1. Что за ошибку вы получаете? Можете ли вы опубликовать это?
2. Привет, Сурабхи Чоудхари, он возвращает нулевой java.Nullpointer. Параметр контекста исключения не может быть нулевым, пока он нормально работает на устройствах ниже 7.0
Ответ №1:
Ваше Context
значение равно нулю.
Попробуйте изменить
mediaPlayer = MediaPlayer.create(mContext, uri);
Для
mediaPlayer = MediaPlayer.create(this, uri);
Ответ №2:
У меня была эта проблема раньше, это происходит потому, что MediaPlayer.create(...)
метод возвращает нулевой объект при неудачной попытке создания, поэтому вы должны постоянно проверять, равен ли он нулю:
do {
mediaPlayer = MediaPlayer.create(mContext, uri);
} while (mediaPlayer == null);
или используйте другой метод: mediaPlayer = new MediaPlayer()
, затем setDataSource(...)
, затем подготовьте и запустите.
Комментарии:
1. Да, это правильно, вы должны проверить, не равен ли проигрыватель нулю, но он
mContext
равен нулю, потому что он никогда не инициализировал его, он устанавливаетContext mContext
и все.2. @mahasongs Это может означать, что процесс создания прошел успешно: если вы уверены, что он всегда будет успешным на 6,0, вы можете добавить условие, касающееся версии Android ниже 6,0
3. @HB. Да, это кажется правильным. вы можете опубликовать это как ответ, чтобы решить эту проблему. Я сохраню свой здесь для всех остальных.