Надеюсь, у вас все хорошо. У меня возникли проблемы с созданием службы уведомлений.
У меня есть аудиоприложение с recyclerviews и его класс адаптера, содержащий средства просмотра. Из onBindviewholder я создал метод onclicklistener, который открывает активность игрока.
Я хотел бы, чтобы когда вы нажимали на любой элемент recyclerview, он запускал звук вместе с уведомлением переднего плана.
Пожалуйста, дайте свои ответы в письменном коде, так как я новичок в жаргоне кода. Заранее спасибо.
Вот мой код: Активность игрока
public class Player extends AppCompatActivity implements MediaPlayer.OnCompletionListener {
TextView song_name, duration_played, total_duration;
ImageView nextbtn,prevbtn,shufflebtn,repeatbtn;
SeekBar seekBar;
FloatingActionButton playpausebtn;
Uri uri;
int position=-1;
int finalTime;
private cardhelper currentItem;
static MediaPlayer mMediaplayer;
static List<cardhelper>macam = new ArrayList<>();
private Handler handler = new Handler();
private Thread playThread, prevThread,nextThread;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
initViews();
getIntentMethod();
song_name.setText(macam.get(position).getSurah());
mMediaplayer.setOnCompletionListener(this);
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mMediaplayer!=null && fromUser){
mMediaplayer.seekTo(progress * 1000);
}
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
Player.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if (mMediaplayer!=null){
int mCurrentposition = mMediaplayer.getCurrentPosition()/1000;
seekBar.setProgress(mCurrentposition);
duration_played.setText(formattedTime(mCurrentposition));
finalTime = mMediaplayer.getDuration()/1000;
total_duration.setText(formattedTime(finalTime));
}
handler.postDelayed(this, 1000);
}
});
shufflebtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (shuffleboolean){
shuffleboolean=false;
shufflebtn.setImageResource(R.drawable.ic_shuffle);
}else{
shuffleboolean=true;
shufflebtn.setImageResource(R.drawable.ic_shuffle_on);
}
}
});
repeatbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (repeatBoolean){
repeatBoolean=false;
repeatbtn.setImageResource(R.drawable.ic_repeat);
}else{
repeatBoolean=true;
repeatbtn.setImageResource(R.drawable.ic_repeat_on);
}
}
});
}
@Override
protected void onResume() {
playThreadbtn();
nextThreadbtn();
prevThreadbtn();
super.onResume();
}
private void playThreadbtn() {
playThread= new Thread(){
@Override
public void run() {
super.run();
playpausebtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
playpausebtnClicked();
}
});
}
};
playThread.start();
}
private void playpausebtnClicked() {
if (mMediaplayer.isPlaying()){
playpausebtn.setImageResource(R.drawable.ic_play);
mMediaplayer.pause();
seekBar.setMax(mMediaplayer.getDuration()/1000);
Player.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if (mMediaplayer!=null){
int mCurrentposition = mMediaplayer.getCurrentPosition()/1000;
seekBar.setProgress(mCurrentposition);
}
handler.postDelayed(this, 1000);
}
});
}else{
playpausebtn.setImageResource(R.drawable.ic_baseline_pause_24);
mMediaplayer.start();
seekBar.setMax(mMediaplayer.getDuration()/1000);
Player.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if (mMediaplayer!=null){
int mCurrentposition = mMediaplayer.getCurrentPosition()/1000;
seekBar.setProgress(mCurrentposition);
}
handler.postDelayed(this, 1000);
}
});
}
}
private void nextThreadbtn() {
nextThread= new Thread(){
@Override
public void run() {
super.run();
nextbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
nextbtnClicked();
}
});
}
};
nextThread.start();
}
private void nextbtnClicked() {
if (mMediaplayer.isPlaying()){
mMediaplayer.stop();
mMediaplayer.release();
if (shuffleboolean && !repeatBoolean){
position= getRandom(macam.size() - 1);
}
else if (! shuffleboolean && ! repeatBoolean){
position=((position + 1)% macam.size());
}
//else position will be position..
int cardhelper= macam.get(position).getAudio();
mMediaplayer= MediaPlayer.create(getApplicationContext(), cardhelper);
song_name.setText(macam.get(position).getSurah());
seekBar.setMax(mMediaplayer.getDuration()/1000);
Player.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if (mMediaplayer!=null){
int mCurrentposition = mMediaplayer.getCurrentPosition()/1000;
seekBar.setProgress(mCurrentposition);
}
handler.postDelayed(this, 1000);
}
});
mMediaplayer.setOnCompletionListener(this);
playpausebtn.setBackgroundResource(R.drawable.ic_baseline_pause_24);
mMediaplayer.start();
}else {
mMediaplayer.stop();
mMediaplayer.release();
if (shuffleboolean && !repeatBoolean){
position= getRandom(macam.size() - 1);
}
else if (! shuffleboolean && ! repeatBoolean){
position=((position + 1)% macam.size());
}
int cardhelper= macam.get(position).getAudio();
mMediaplayer= MediaPlayer.create(getApplicationContext(), cardhelper);
song_name.setText(macam.get(position).getSurah());
seekBar.setMax(mMediaplayer.getDuration()/1000);
Player.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if (mMediaplayer!=null){
int mCurrentposition = mMediaplayer.getCurrentPosition()/1000;
seekBar.setProgress(mCurrentposition);
}
handler.postDelayed(this, 1000);
}
});
mMediaplayer.setOnCompletionListener(this);
playpausebtn.setBackgroundResource(R.drawable.ic_play);
}
}
private int getRandom(int i) {
Random random = new Random();
return random.nextInt(i+ 1);
}
private void prevThreadbtn() {
prevThread= new Thread(){
@Override
public void run() {
super.run();
prevbtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
prevbtnClicked();
}
});
}
};
prevThread.start();
}
private void prevbtnClicked() {
if (mMediaplayer.isPlaying()){
mMediaplayer.stop();
mMediaplayer.release();
position=((position-1) < 0 ? (macam.size() -1 ): (position - 1));
int cardhelper= macam.get(position).getAudio();
mMediaplayer= MediaPlayer.create(getApplicationContext(), cardhelper);
song_name.setText(macam.get(position).getSurah());
seekBar.setMax(mMediaplayer.getDuration()/1000);
Player.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if (mMediaplayer!=null){
int mCurrentposition = mMediaplayer.getCurrentPosition()/1000;
seekBar.setProgress(mCurrentposition);
}
handler.postDelayed(this, 1000);
}
});
mMediaplayer.setOnCompletionListener(this);
playpausebtn.setBackgroundResource(R.drawable.ic_baseline_pause_24);
mMediaplayer.start();
}else {
mMediaplayer.stop();
mMediaplayer.release();
position=((position-1) < 0 ? (macam.size() -1 ): (position - 1));
int cardhelper= macam.get(position).getAudio();
mMediaplayer= MediaPlayer.create(getApplicationContext(), cardhelper);
song_name.setText(macam.get(position).getSurah());
seekBar.setMax(mMediaplayer.getDuration()/1000);
Player.this.runOnUiThread(new Runnable() {
@Override
public void run() {
if (mMediaplayer!=null){
int mCurrentposition = mMediaplayer.getCurrentPosition()/1000;
seekBar.setProgress(mCurrentposition);
}
handler.postDelayed(this, 1000);
}
});
mMediaplayer.setOnCompletionListener(this);
playpausebtn.setBackgroundResource(R.drawable.ic_play);
}
}
private String formattedTime(int mCurrentposition) {
String totalout = "";
String totalNew = "";
String seconds = String.valueOf(mCurrentposition % 60);
String minutes = String.valueOf(mCurrentposition / 60);
totalout = minutes + ":" + seconds;
totalNew = minutes + ":" + "0" + seconds;
if (seconds.length() == 1){
return totalNew;
}
else {
return totalout;
}
}
private void getIntentMethod() {
position= getIntent().getIntExtra("position",-1);
macam=cardalbums;
macam=malbie;
if (macam!=null ){
playpausebtn.setImageResource(R.drawable.ic_baseline_pause_24);
currentItem = cardalbums.get(position);
currentItem = malbie.get(position);
}
if (mMediaplayer!=null){
mMediaplayer.stop();
mMediaplayer.release();
mMediaplayer= MediaPlayer.create(getApplicationContext(),currentItem.getAudio());
mMediaplayer.start();
}else{
mMediaplayer= MediaPlayer.create(getApplicationContext(),currentItem.getAudio());
mMediaplayer.start();
}
seekBar.setMax(mMediaplayer.getDuration()/ 1000);
}
private void initViews() {
song_name=findViewById(R.id.textTitle);
duration_played=findViewById(R.id.textCurrentTime);
total_duration=findViewById(R.id.textTotalTime);
nextbtn=findViewById(R.id.buttonNext);
prevbtn=findViewById(R.id.buttonPrevious);
shufflebtn=findViewById(R.id.buttonShuffle);
repeatbtn=findViewById(R.id.buttonRepeat);
seekBar=findViewById(R.id.playerSeekbar);
playpausebtn=findViewById(R.id.buttonPlay);
}
@Override
public void onCompletion(MediaPlayer mp) {
nextbtnClicked();
if (mMediaplayer!=null){
int cardhelper= macam.get(position).getAudio();
mMediaplayer= MediaPlayer.create(getApplicationContext(), cardhelper);
mMediaplayer.start();
mMediaplayer.setOnCompletionListener(this);
}
}
}
Класс адаптера фрагмента
public class musicadapter extends RecyclerView.Adapter<musicadapter.cardViewHolder>implements Filterable {
List<cardhelper> mcardalbums;
List<cardhelper>filteredData;
Filter filter;
int audio;
int position;
Context mcontext;
musicadapter(Context mcontext, List<cardhelper> mcardalbums) {
this.mcardalbums = mcardalbums;
this.mcontext=mcontext;
this.filteredData=mcardalbums;
}
@Override
public cardViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
View v= LayoutInflater.from(parent.getContext()).inflate(R.layout.card_design, parent, false);
cardViewHolder cvh= new cardViewHolder(v);
return cvh;
}
@Override
public void onBindViewHolder(@NonNull cardViewHolder holder, int position) {
cardhelper currentItem = mcardalbums.get(position);
holder.surah.setText(currentItem.getSurah());
holder.count.setText(currentItem.getNumOfSongs());
holder.itemView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent(mcontext, Player.class);
intent.putExtra("position", position);
mcontext.startActivity(intent);
}
});
}
@Override
public int getItemCount() {
return mcardalbums.size();
}
@Override
public Filter getFilter() {
return new Filter() {
@SuppressWarnings("unchecked")
@Override
protected void publishResults(CharSequence constraint, FilterResults results) {
mcardalbums = (List<cardhelper>) results.values;
notifyDataSetChanged();
}
@Override
protected FilterResults performFiltering(CharSequence constraint) {
List<cardhelper> filteredResults = null;
if (constraint.length() == 0) {
filteredResults = filteredData;
} else {
filteredResults = getFilteredResults(constraint.toString().toLowerCase());
}
FilterResults results = new FilterResults();
results.values = filteredResults;
return results;
}
};
}
protected List<cardhelper> getFilteredResults(String constraint) {
List<cardhelper> results = new ArrayList<>();
for (cardhelper item : filteredData) {
if (item.getSurah().toLowerCase().contains(constraint)) {
results.add(item);
}
}
return results;
}
public static class cardViewHolder extends RecyclerView.ViewHolder {
TextView count,surah;
@SuppressLint("ResourceType")
public cardViewHolder(View itemView) {
super(itemView);
count = itemView.findViewById(R.id.card_count);
surah = itemView.findViewById(R.id.card_surah);
}
}
}
поэтому после нескольких недель исследований я узнал, как это сделать. Пожалуйста, имейте в виду, что я новичок, но вот что я получил из своего наблюдения:
public void showNotification(int playpausebtn) {
final Bitmap icon = BitmapFactory.decodeResource(getResources(), R.drawable.new_disc);
macam= (ArrayList<cardhelper>) malbie;
macam= (ArrayList<cardhelper>) cardalbums;
if (macam != null) {
currentItem = malbie.get(position);
currentItem = cardalbums.get(position);
}
Intent previousIntent = new Intent(ACTION_PREVIOUS);
previousIntent.setAction(ACTION_PREVIOUS);
PendingIntent ppreviousIntent = PendingIntent.getBroadcast(this, 1, previousIntent, 0);
Intent playIntent = new Intent(ACTION_PLAY);
playIntent.setAction(ACTION_PLAY);
PendingIntent pplayIntent = PendingIntent.getBroadcast(this, 2, playIntent, 0);
Intent nextIntent = new Intent(ACTION_NEXT);
nextIntent.setAction(ACTION_NEXT);
PendingIntent pnextIntent = PendingIntent.getBroadcast(this, 3, nextIntent, 0);
// Create a new MediaSession
final MediaSession mediaSession = new MediaSession(this, "debug tag");
// Update the current metadata
mediaSession.setMetadata(new MediaMetadata.Builder()
.putBitmap(MediaMetadata.METADATA_KEY_ALBUM_ART, icon)
.putString(MediaMetadata.METADATA_KEY_ARTIST, "Pink Floyd")
.putString(MediaMetadata.METADATA_KEY_TITLE, "The Great Gig in the Sky")
.build());
// Indicate you're ready to receive media commands:
Intent intentOpenApp = new Intent(getApplicationContext(), Userxui.class);
PendingIntent pendingIntentOpenApp = PendingIntent.getActivity(getApplicationContext(), 0,
intentOpenApp, 0);
// Create a new Notification
NotificationCompat.Builder noti = new NotificationCompat.Builder(getApplicationContext(), "CHANNEl_ID");
// Hide the timestamp
noti.setShowWhen(false);
noti.setLargeIcon(icon);
noti.setVisibility(androidx.core.app.NotificationCompat.VISIBILITY_PUBLIC);
// Set the Notification style
noti.setContentTitle(currentItem.getSurah());
noti.addAction(R.drawable.ic_previous, "previous", ppreviousIntent);
noti.addAction(playpausebtn, "pause", pplayIntent);
noti.addAction(R.drawable.ic_next, "next", pnextIntent);
noti.setStyle(new androidx.media.app.NotificationCompat.MediaStyle()
.setShowActionsInCompactView(0, 1, 2)
.setMediaSession(MediaSessionCompat.Token.fromToken(mediaSession.getSessionToken())));
noti.setContentIntent(pendingIntentOpenApp);
noti.setSmallIcon(R.drawable.only);
noti.setOnlyAlertOnce(true);
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel = new NotificationChannel(
CHANNEL_ID,
"Siraa",
NotificationManager.IMPORTANCE_HIGH);
notificationManager.createNotificationChannel(channel);
noti.setChannelId(CHANNEL_ID);
}
notificationManager.notify(0, noti.build());
}
public static final String ACTION_PLAY = "action_play";
public static final String ACTION_NEXT = "action_next";
public static final String ACTION_PREVIOUS = "action_previous";
public static final String CHANNEL_ID = "Channel1";
NotificationManager notificationManager;
3. Зарегистрируйте эти действия внутри приемника широковещательной рассылки с фильтрами намерений:
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_PLAY);
filter.addAction(ACTION_NEXT);
filter.addAction(ACTION_PREVIOUS);
receiver=new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String actioname = intent.getAction();
if (actioname!=null){
switch (actioname){
case ACTION_PLAY:
Toast.makeText(context,"Click play",Toast.LENGTH_SHORT).show();
\\\ implement whatever
playpausebtnClicked();
break;
case ACTION_NEXT:
Toast.makeText(context,"Clicked next",Toast.LENGTH_SHORT).show();
nextbtnClicked();
break;
case ACTION_PREVIOUS:
Toast.makeText(context,"Clicked previous",Toast.LENGTH_SHORT).show();
prevbtnClicked();
break;
}
}
}
};
registerReceiver(receiver,filter);
и откройте метод в моем событии нажатия кнопки. Вот и не нужно прописывать в файле манифеста. Надеюсь, это помогло.