If you get this error should be paid attention to 2 items and them order:
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
builder = new NotificationCompat.Builder(context, id);
Also NotificationManager notifManager and NotificationChannel mChannel are created only once.
There are required setters for Notification:
- builder.setContentTitle() // required
- .setSmallIcon() // required
- .setContentText() // required
See example:
private NotificationManager notifManager;
public void createNotification(String aMessage, Context context) {
final int NOTIFY_ID = 0; // ID of notification
String id = context.getString(R.string.default_notification_channel_id); // default_channel_id
String title = context.getString(R.string.default_notification_channel_title); // Default Channel
Intent intent;
PendingIntent pendingIntent;
NotificationCompat.Builder builder;
if (notifManager == null) {
notifManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = notifManager.getNotificationChannel(id);
if (mChannel == null) {
mChannel = new NotificationChannel(id, title, importance);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
notifManager.createNotificationChannel(mChannel);
}
builder = new NotificationCompat.Builder(context, id);
intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
builder.setContentTitle(aMessage) // required
.setSmallIcon(android.R.drawable.ic_popup_reminder) // required
.setContentText(context.getString(R.string.app_name)) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setTicker(aMessage)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
}
else {
builder = new NotificationCompat.Builder(context, id);
intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
builder.setContentTitle(aMessage) // required
.setSmallIcon(android.R.drawable.ic_popup_reminder) // required
.setContentText(context.getString(R.string.app_name)) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setTicker(aMessage)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setPriority(Notification.PRIORITY_HIGH);
}
Notification notification = builder.build();
notifManager.notify(NOTIFY_ID, notification);
}
Solution 1
Per the Migration MediaStyle notifications to support Android O blog post:
In order to use notifications in O, you must use notification channels.
If you target API 26 or higher, you must add a notification channel to all of your notifications. The blog post goes through the suggested settings you should use for media notifications.
Solution 2
1.Create a notification channel before showing notification(I prefer activity onCreate()
)
private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
CharSequence name = getString(R.string.channel_name);
String description = getString(R.string.channel_desc);
int importance = NotificationManager.IMPORTANCE_DEFAULT;
NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
channel.setDescription(description);
// Register the channel with the system; you can't change the importance
// or other notification behaviors after this
NotificationManager notificationManager = getSystemService(NotificationManager.class);
notificationManager.createNotificationChannel(channel);
}
}
2.Build and Show notification via NotificationCompact
instead Notification
to support API version below 27. Must supply notification_id
(integer id, to distinguish between different notifications in you app)
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,CHANNEL_ID)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText(message)
.setContentTitle(Notification_title)
.setAutoCancel(true)
.setSound(defaultSoundUri)
.setContentIntent(pendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if(notificationManager!=null)
notificationManager.notify(NOTIFICATION_ID, notificationBuilder.build());//integer id, to distinguish between different notifications.
Related videos on Youtube
01 : 03 : 10
How to Show Toast Message under Flow Builder using LWC?
01 : 20
Android : Failed to post notification on channel «null» Target Api is 26
01 : 19
How To Fix Developer Warning For Package
05 : 47
Flutter : How to show Toast Message
01 : 10
Failed to post notification on channel null Target Api is 26 — Android
23 : 08
How to show toast message in Salesforce flow | #SalesforceFlow #SFDC
10 : 51
How to display a toast message on Lightning Aura page.
01 : 00
Samsung Galaxy S10 / S10+: How to Enable / Disable Show Notification Channel Warnings
Comments
-
i was made up my mp3 player.
it’s working but i always got a toast message
enter image description here
so i think i need to notification channel in my code.
but i don’t know how to add code. help me !!
here is my code
public class MusicController extends MediaController { public MusicController(Context c){ super(c); } public void hide(){} } public class MusicService extends Service implements MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener, MediaPlayer.OnCompletionListener { //media player private MediaPlayer player; //song list private ArrayList<Song> songs; //current position private int songPosn; //binder private final IBinder musicBind = new MusicBinder(); //title of current song private String songTitle=""; //notification id private static final int NOTIFY_ID=1; //shuffle flag and random private boolean shuffle=false; private Random rand; public void onCreate(){ //create the service super.onCreate(); //initialize position songPosn=0; //random rand=new Random(); //create player player = new MediaPlayer(); //initialize initMusicPlayer(); } public void initMusicPlayer(){ //set player properties player.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK); player.setAudioStreamType(AudioManager.STREAM_MUSIC); //set listeners player.setOnPreparedListener(this); player.setOnCompletionListener(this); player.setOnErrorListener(this); } //pass song list public void setList(ArrayList<Song> theSongs){ songs=theSongs; } //binder public class MusicBinder extends Binder { MusicService getService() { return MusicService.this; } } //activity will bind to service @Override public IBinder onBind(Intent intent) { return musicBind; } //release resources when unbind @Override public boolean onUnbind(Intent intent){ player.stop(); player.release(); return false; } //play a song public void playSong(){ //play player.reset(); //get song Song playSong = songs.get(songPosn); //get title songTitle=playSong.getTitle(); //get id long currSong = playSong.getID(); //set uri Uri trackUri = ContentUris.withAppendedId( android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, currSong); //set the data source try{ player.setDataSource(getApplicationContext(), trackUri); } catch(Exception e){ Log.e("MUSIC SERVICE", "Error setting data source", e); } player.prepareAsync(); } //set the song public void setSong(int songIndex){ songPosn=songIndex; } @Override public void onCompletion(MediaPlayer mp) { //check if playback has reached the end of a track if(player.getCurrentPosition()>0){ mp.reset(); playNext(); } } @Override public boolean onError(MediaPlayer mp, int what, int extra) { Log.v("MUSIC PLAYER", "Playback Error"); mp.reset(); return false; } @Override public void onPrepared(MediaPlayer mp) { //start playback mp.start(); //notification Intent notIntent = new Intent(this, MainActivity.class); notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP); PendingIntent pendInt = PendingIntent.getActivity(this, 0, notIntent, PendingIntent.FLAG_UPDATE_CURRENT); Notification.Builder builder = new Notification.Builder(this); builder.setContentIntent(pendInt) .setSmallIcon(R.drawable.android_music_player_play) .setTicker(songTitle) .setOngoing(true) .setContentTitle("Playing") .setContentText(songTitle); Notification not = builder.build(); startForeground(NOTIFY_ID, not); } //playback methods public int getPosn(){ return player.getCurrentPosition(); } public int getDur(){ return player.getDuration(); } public boolean isPng(){ return player.isPlaying(); } public void pausePlayer(){ player.pause(); } public void seek(int posn){ player.seekTo(posn); } public void go(){ player.start(); } //skip to previous track public void playPrev(){ songPosn--; if(songPosn<0) songPosn=songs.size()-1; playSong(); } //skip to next public void playNext(){ if(shuffle){ int newSong = songPosn; while(newSong==songPosn){ newSong=rand.nextInt(songs.size()); } songPosn=newSong; } else{ songPosn++; if(songPosn>=songs.size()) songPosn=0; } playSong(); } @Override public void onDestroy() { stopForeground(true); } //toggle shuffle public void setShuffle(){ if(shuffle) shuffle=false; else shuffle=true; } } public class MainActivity extends Activity implements MediaPlayerControl { //song list variables private ArrayList<Song> songList; private ListView songView; //service private MusicService musicSrv; private Intent playIntent; //binding private boolean musicBound=false; //controller private MusicController controller; //activity and playback pause flags private boolean paused=false, playbackPaused=false; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) { if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) { requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1); return; }} //retrieve list view songView = (ListView)findViewById(R.id.song_list); //instantiate list songList = new ArrayList<Song>(); //get songs from device getSongList(); //sort alphabetically by title Collections.sort(songList, new Comparator<Song>(){ public int compare(Song a, Song b){ return a.getTitle().compareTo(b.getTitle()); } }); //create and set adapter SongAdapter songAdt = new SongAdapter(this, songList); songView.setAdapter(songAdt); //setup controller setController(); } //connect to the service private ServiceConnection musicConnection = new ServiceConnection(){ @Override public void onServiceConnected(ComponentName name, IBinder service) { MusicBinder binder = (MusicBinder)service; //get service musicSrv = binder.getService(); //pass list musicSrv.setList(songList); musicBound = true; } @Override public void onServiceDisconnected(ComponentName name) { musicBound = false; } }; //start and bind the service when the activity starts @Override protected void onStart() { super.onStart(); if(playIntent==null){ playIntent = new Intent(this, MusicService.class); bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE); startService(playIntent); } } //user song select public void songPicked(View view){ musicSrv.setSong(Integer.parseInt(view.getTag().toString())); musicSrv.playSong(); if(playbackPaused){ setController(); playbackPaused=false; } controller.show(0); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { //menu item selected switch (item.getItemId()) { case R.id.action_shuffle: musicSrv.setShuffle(); break; case R.id.action_end: stopService(playIntent); musicSrv=null; System.exit(0); break; } return super.onOptionsItemSelected(item); } //method to retrieve song info from device public void getSongList(){ //query external audio ContentResolver musicResolver = getContentResolver(); Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI; Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null); //iterate over results if valid if(musicCursor!=null && 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); //add songs to list do { long thisId = musicCursor.getLong(idColumn); String thisTitle = musicCursor.getString(titleColumn); String thisArtist = musicCursor.getString(artistColumn); songList.add(new Song(thisId, thisTitle, thisArtist)); } while (musicCursor.moveToNext()); } } @Override public boolean canPause() { return true; } @Override public boolean canSeekBackward() { return true; } @Override public boolean canSeekForward() { return true; } @Override public int getAudioSessionId() { return 0; } @Override public int getBufferPercentage() { return 0; } @Override public int getCurrentPosition() { if(musicSrv!=null && musicBound && musicSrv.isPng()) return musicSrv.getPosn(); else return 0; } @Override public int getDuration() { if(musicSrv!=null && musicBound && musicSrv.isPng()) return musicSrv.getDur(); else return 0; } @Override public boolean isPlaying() { if(musicSrv!=null && musicBound) return musicSrv.isPng(); return false; } @Override public void pause() { playbackPaused=true; musicSrv.pausePlayer(); } @Override public void seekTo(int pos) { musicSrv.seek(pos); } @Override public void start() { musicSrv.go(); } //set the controller up private void setController(){ controller = new MusicController(this); //set previous and next button listeners controller.setPrevNextListeners(new View.OnClickListener() { @Override public void onClick(View v) { playNext(); } }, new View.OnClickListener() { @Override public void onClick(View v) { playPrev(); } }); //set and show controller.setMediaPlayer(this); controller.setAnchorView(findViewById(R.id.song_list)); controller.setEnabled(true); } private void playNext(){ musicSrv.playNext(); if(playbackPaused){ setController(); playbackPaused=false; } controller.show(0); } private void playPrev(){ musicSrv.playPrev(); if(playbackPaused){ setController(); playbackPaused=false; } controller.show(0); } @Override protected void onPause(){ super.onPause(); paused=true; } @Override protected void onResume(){ super.onResume(); if(paused){ setController(); paused=false; } } @Override protected void onStop() { controller.hide(); super.onStop(); } @Override protected void onDestroy() { stopService(playIntent); musicSrv=null; super.onDestroy(); } }
how can i fix it ? ! help me !
-
read about notification’s channels in android 8 … also aleady asked — feel free to use internet search for finding similar question
-
You should find answer in @Amit Vaghela link.
-
Recents
Related
How to completely solve Android8.0 (API26 +) and the above version of the simulator Run Notad Times Developer Warning for Package «com.example.my» failed to post notification on channel ‘Default’ See log for more detail
Error problem
—- Andr Wind QQ1652102745
First, run the notification bar (Notification) error in the simulator Demo:
PS: Declaring that my mainActivity program code is not any problem, this error occurred.
Second, the normal operation after solving the problem:
1 Effect 1 (Android8.0 API26 below version of the effect)NOTIFICAMPAT.BUILDER class to implement the announcement
②Effect 2 (Android 8.0 API26 and above) renderingsNotificationCompat.Builder classTo achieve the announcement
Third, solution:
1, analyze the reason
This error is mainly because we generally use the NotificationsCompat.Builder class to implement the announcement.
NotificationCompat.Builder builder=new NotificationCompat.Builder(getApplicationContext(),"default");
Run the notification bar on your phone before Android8.0 (API26) Either shields the notification bar (prevent harassment), or all normal operation notification bar. We don’t have problems with NOTIFICAPMPAT.BUILDER class.
Since Android 8.0 (API26), in order to make users better experience, then new channel functions (that is, NotificationChannel class)The channel function (that is, the NotificationChannel class) enables the user to have the right to choose, the user can set the shield-independent navigation notice, and the user can set an important notice.
NotificationChannel Mchannel = New NotificationChannel (ID, "123", Importance); // Establish a notification bar channel class (you need to have ID, important properties)
That is to say we realize the fence function in Android8.0 (API26) and above.NOTIFICATIONCOMPAT.BUILDER class, it will not function properly, which will cause us to appear error:
Developer warning for package «com.example.my»Failed to post notification on channel ‘default’ See log for more details
Error problem
2, solution:
1 If your emulator runs system version is used android8.0 or lessNOTIFICAMPAT.BUILDER class to implement the announcement
Layout design Source code: https://www.cnblogs.com/adf520/p/12601872.html
2-1, MainActivity.java function realizes source code
1 package com.example.my; 2 3 import androidx.annotation.RequiresApi; 4 import androidx.appcompat.app.AppCompatActivity; 5 import androidx.core.app.NotificationCompat; 6 7 import android.app.Notification; 8 import android.app.NotificationChannel; 9 import android.app.NotificationManager; 10 import android.content.Context; 11 import android.content.ContextWrapper; 12 import android.content.Intent; 13 import android.content.pm.PackageManager; 14 import android.graphics.Bitmap; 15 import android.graphics.BitmapFactory; 16 import android.graphics.Color; 17 import android.os.Build; 18 import android.os.Bundle; 19 import android.provider.Settings; 20 import android.text.Layout; 21 import android.view.LayoutInflater; 22 import android.view.View; 23 import android.widget.Button; 24 import android.widget.CheckBox; 25 import android.widget.TextView; 26 import android.widget.Toast; 27 28 public class MainActivity extends AppCompatActivity implements View.OnClickListener { 29 CheckBox cb1,cb2,cb3; 30 Button pay; 31 int count=0; 32 @RequiresApi(api = Build.VERSION_CODES.O) 33 @Override 34 protected void onCreate(Bundle savedInstanceState) { 35 super.onCreate(savedInstanceState); 36 setContentView(R.layout.activity_main); 37 38 cb1=findViewById(R.id.cb1); 39 cb2=findViewById(R.id.cb2); 40 cb3=findViewById(R.id.cb3); 41 pay=findViewById(R.id.pay); 42 pay.setOnClickListener(this); 43 44 45 } 46 47 @RequiresApi(api = Build.VERSION_CODES.O) 48 @Override 49 public void onClick(View v) { 50 if (cb1.isChecked()) 51 count+=45; 52 if (cb2.isChecked()) 53 count+=60; 54 if (cb3.isChecked()) 55 count+=55; 56 57 58 // final NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);//Notification Bar Manager (get system service) 59 // String id = "channel_1"; //Custom Set Channel ID Property 60 // String description = "123";//Custom Set Channel Description Property 61 // int importance = NotificationManager.IMPORTANCE_HIGH;//Notification bar management Important prompt message sound setting 62 // /** 63 // * Oreo does not have priority, use importance 64 // * Importance_none Close Notification 65 // * Importance_min opens the notification, not popping, but no prompt sound, no display in the status bar 66 // * Importance_low opens notifications, no pop-up, does not post a tone, display in the status bar 67 // * Importance_default opens notifications, no pop-up, prompt tone, display in the status bar 68 // * Importance_high opens notification, pop-up, issue a tone, display in the status bar 69 // */ 70 // NotificationChannel mChannel = new NotificationChannel(id, "123", importance);//Establish a notification bar channel class (you need to have ID, important properties) 71 //// mchannel.setdescription (description); // Configure the properties of the notification channel 72 //// mchannel.EnableLights (TRUE); // Setting the flashlight when notification (if Android device supports) 73 //// mchannel.setlightcolor (color.red); // Set the flash color is red 74 //// mchannel.enablevibration (TRUE); // Setting the vibration when the notification (if Android device supports) 75 //// mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400}); 76 // manager.createNotificationChannel(mChannel);////Finally create this notification channel in NotificationManager 77 // Notification notification = new Notification.Builder(this, id)//Create a Notification object. 78 // .SETCONTENTTITLE ("Payment Notice") //Set notification title 79 // .setSmallIcon(R.drawable.q)//Set notification small icon 80 // .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.q))//Set notification big icon 81 // .SETCONTENTTEXT ("You have paid" + count + "yuan")//Set the notification content 82 // .setAutoCancel(true)//Set automatic deletion notification 83 // .build();//Run 84 // 85 // manager.notify((int) System.currentTimeMillis(),notification); //Notification column retain multiple notifications 86 // count=0;//Empty amount 87 88 // 89 // LayoutInflater inflater=getLayoutInflater(); 90 // View layout=inflater.inflate(R.layout.activity_main2,null); 91 // TextView tv= layout.findViewById(R.id.tv); 92 // TV.Settext ("You pay" + count + "yuan"); 93 // Toast toast=new Toast(MainActivity.this); 94 // toast.setView(layout); 95 // toast.setDuration(Toast.LENGTH_SHORT); 96 // toast.show(); 97 // count=0; 98 99 100 101 //Step 1: Create a notification constructor NotificationCompat.Builder object. 102 NotificationCompat.Builder builder=new NotificationCompat.Builder(getApplicationContext(),"default"); 103 //Step 2: Call the method settings of the NotificationCompat.Builder object notification related content. 104 builder.setSmallIcon(R.drawable.q);//Set notification small icon 105 builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.q));//Set notification big icon 106 builder.setContentTitle("Payment Notification");//Set notification title 107 builder.setContentText("You have paid"+count+"yuan");//Set the notification content 108 builder.setAutoCancel(true);//Set automatic deletion notification 109 Notification notification=builder.build();//: Create a Notification object. 110 NotificationManager manager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);//Notification Bar Manager (get system service) 111 // manager.notify(1,notification); //Notification bar keeps single notice 112 manager.notify((int) System.currentTimeMillis(),notification); //Notification column retain multiple notifications 113 count=0;//Empty amount 114 116 117 } 118 }
2 If your simulator runs system version is Android 8.0 and aboveNotificationChannel class to implement the announcement
2-1, MainActivity.java function realizes source code
1 package com.example.my; 2 3 import androidx.annotation.RequiresApi; 4 import androidx.appcompat.app.AppCompatActivity; 5 import androidx.core.app.NotificationCompat; 6 7 import android.app.Notification; 8 import android.app.NotificationChannel; 9 import android.app.NotificationManager; 10 import android.content.Context; 11 import android.content.ContextWrapper; 12 import android.content.Intent; 13 import android.content.pm.PackageManager; 14 import android.graphics.Bitmap; 15 import android.graphics.BitmapFactory; 16 import android.graphics.Color; 17 import android.os.Build; 18 import android.os.Bundle; 19 import android.provider.Settings; 20 import android.text.Layout; 21 import android.view.LayoutInflater; 22 import android.view.View; 23 import android.widget.Button; 24 import android.widget.CheckBox; 25 import android.widget.TextView; 26 import android.widget.Toast; 27 28 public class MainActivity extends AppCompatActivity implements View.OnClickListener { 29 CheckBox cb1,cb2,cb3; 30 Button pay; 31 int count=0; 32 @RequiresApi(api = Build.VERSION_CODES.O) 33 @Override 34 protected void onCreate(Bundle savedInstanceState) { 35 super.onCreate(savedInstanceState); 36 setContentView(R.layout.activity_main); 37 38 cb1=findViewById(R.id.cb1); 39 cb2=findViewById(R.id.cb2); 40 cb3=findViewById(R.id.cb3); 41 pay=findViewById(R.id.pay); 42 pay.setOnClickListener(this); 43 44 45 } 46 47 @RequiresApi(api = Build.VERSION_CODES.O) 48 @Override 49 public void onClick(View v) { 50 if (cb1.isChecked()) 51 count+=45; 52 if (cb2.isChecked()) 53 count+=60; 54 if (cb3.isChecked()) 55 count+=55; 56 57 58 final NotificationManager manager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);//Notification Bar Manager (get system service) 59 String id = "channel_1"; //Custom Set Channel ID Property 60 String description = "123";//Custom Set Channel Description Property 61 int importance = NotificationManager.IMPORTANCE_HIGH;//Notification bar management Important prompt message sound setting 62 /** 63 * Oreo does not have priority, use importance 64 * Importance_none Close Notification 65 * Importance_min opens the notification, not popping, but no prompt sound, no display in the status bar 66 * Importance_low opens notifications, no pop-up, does not post a tone, display in the status bar 67 * Importance_default opens notifications, no pop-up, prompt tone, display in the status bar 68 * Importance_high opens notification, pop-up, issue a tone, display in the status bar 69 */ 70 NotificationChannel mChannel = new NotificationChannel(id, "123", importance);//Establish a notification bar channel class (you need to have ID, important properties) 71 // mChannel.setDescription(description); // Configuration Notification Channel properties 72 // mChannel.enableLights(true);// Set the flashlight when notification (if Android device supports) 73 // mChannel.setLightColor(Color.RED);//Set the flash color for red 74 // mChannel.enableVibration(true); // Set the vibration when notification (if Android device supports) 75 // mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400}); 76 manager.createNotificationChannel(mChannel);//// Finally create this notification channel in NotificationManager 77 Notification notification = new Notification.Builder(this, id)//Create a Notification object. 78 .setContentTitle("Payment Notification") //Set notification title 79 .setSmallIcon(R.drawable.q)//Set notification small icon 80 .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.q))//Set notification big icon 81 .setContentText("You have paid"+count+"yuan")//Set the notification content 82 .setAutoCancel(true)//Set automatic deletion notification 83 .build();//run 84 85 manager.notify((int) System.currentTimeMillis(),notification); //Notification column retain multiple notifications 86 count=0;//Empty amount 87 88 // 89 // LayoutInflater inflater=getLayoutInflater(); 90 // View layout=inflater.inflate(R.layout.activity_main2,null); 91 // TextView tv= layout.findViewById(R.id.tv); 92 // TV.Settext ("You pay" + count + "yuan"); 93 // Toast toast=new Toast(MainActivity.this); 94 // toast.setView(layout); 95 // toast.setDuration(Toast.LENGTH_SHORT); 96 // toast.show(); 97 // count=0; 98 99 100 101 // //Step 1: Create a notification constructor NotificationCompat.Builder object. 102 // NotificationCompat.Builder builder=new NotificationCompat.Builder(getApplicationContext(),"default"); 103 // //Step 2: Call the method settings of the NotificationCompat.Builder object notification related content. 104 // builder.setSmallIcon(R.drawable.q);//Set notification small icon 105 // builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.q));//Set notification big icon 106 // Builder.SetContentTitle ("Payment Notice");//Set notification title 107 // Builder.setContentText ("You have paid" + count + "yuan");//Set the notification content 108 // builder.setAutoCancel(true);//Set automatic deletion notification 109 // Notification notification=builder.build();//: Create a Notification object. 110 // NotificationManager manager= (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);//Notification Bar Manager (get system service) 111 //// manager.notify (1, notification); // Notification bar keeps a single notice 112 // manager.notify((int) System.currentTimeMillis(),notification); //Notification column retain multiple notifications 113 // count=0;//Empty amount 114 115 116 117 } 118 }
The above code is only a reference, I hope to bring you help, I am Antife, thank you for your attention and support, there is a problem welcome to leave a message below; see the next one answer.
i was made up my mp3 player.
it’s working but i always got a toast message
enter image description here
so i think i need to notification channel in my code.
but i don’t know how to add code. help me !!
here is my code
public class MusicController extends MediaController {
public MusicController(Context c){
super(c);
}
public void hide(){}
}
public class MusicService extends Service implements
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener {
//media player
private MediaPlayer player;
//song list
private ArrayList<Song> songs;
//current position
private int songPosn;
//binder
private final IBinder musicBind = new MusicBinder();
//title of current song
private String songTitle="";
//notification id
private static final int NOTIFY_ID=1;
//shuffle flag and random
private boolean shuffle=false;
private Random rand;
public void onCreate(){
//create the service
super.onCreate();
//initialize position
songPosn=0;
//random
rand=new Random();
//create player
player = new MediaPlayer();
//initialize
initMusicPlayer();
}
public void initMusicPlayer(){
//set player properties
player.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
//set listeners
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
//pass song list
public void setList(ArrayList<Song> theSongs){
songs=theSongs;
}
//binder
public class MusicBinder extends Binder {
MusicService getService() {
return MusicService.this;
}
}
//activity will bind to service
@Override
public IBinder onBind(Intent intent) {
return musicBind;
}
//release resources when unbind
@Override
public boolean onUnbind(Intent intent){
player.stop();
player.release();
return false;
}
//play a song
public void playSong(){
//play
player.reset();
//get song
Song playSong = songs.get(songPosn);
//get title
songTitle=playSong.getTitle();
//get id
long currSong = playSong.getID();
//set uri
Uri trackUri = ContentUris.withAppendedId(
android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,
currSong);
//set the data source
try{
player.setDataSource(getApplicationContext(), trackUri);
}
catch(Exception e){
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
player.prepareAsync();
}
//set the song
public void setSong(int songIndex){
songPosn=songIndex;
}
@Override
public void onCompletion(MediaPlayer mp) {
//check if playback has reached the end of a track
if(player.getCurrentPosition()>0){
mp.reset();
playNext();
}
}
@Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.v("MUSIC PLAYER", "Playback Error");
mp.reset();
return false;
}
@Override
public void onPrepared(MediaPlayer mp) {
//start playback
mp.start();
//notification
Intent notIntent = new Intent(this, MainActivity.class);
notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendInt = PendingIntent.getActivity(this, 0,
notIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentIntent(pendInt)
.setSmallIcon(R.drawable.android_music_player_play)
.setTicker(songTitle)
.setOngoing(true)
.setContentTitle("Playing")
.setContentText(songTitle);
Notification not = builder.build();
startForeground(NOTIFY_ID, not);
}
//playback methods
public int getPosn(){
return player.getCurrentPosition();
}
public int getDur(){
return player.getDuration();
}
public boolean isPng(){
return player.isPlaying();
}
public void pausePlayer(){
player.pause();
}
public void seek(int posn){
player.seekTo(posn);
}
public void go(){
player.start();
}
//skip to previous track
public void playPrev(){
songPosn--;
if(songPosn<0) songPosn=songs.size()-1;
playSong();
}
//skip to next
public void playNext(){
if(shuffle){
int newSong = songPosn;
while(newSong==songPosn){
newSong=rand.nextInt(songs.size());
}
songPosn=newSong;
}
else{
songPosn++;
if(songPosn>=songs.size()) songPosn=0;
}
playSong();
}
@Override
public void onDestroy() {
stopForeground(true);
}
//toggle shuffle
public void setShuffle(){
if(shuffle) shuffle=false;
else shuffle=true;
}
}
public class MainActivity extends Activity implements MediaPlayerControl {
//song list variables
private ArrayList<Song> songList;
private ListView songView;
//service
private MusicService musicSrv;
private Intent playIntent;
//binding
private boolean musicBound=false;
//controller
private MusicController controller;
//activity and playback pause flags
private boolean paused=false, playbackPaused=false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
if (checkSelfPermission(Manifest.permission.READ_EXTERNAL_STORAGE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},1);
return;
}}
//retrieve list view
songView = (ListView)findViewById(R.id.song_list);
//instantiate list
songList = new ArrayList<Song>();
//get songs from device
getSongList();
//sort alphabetically by title
Collections.sort(songList, new Comparator<Song>(){
public int compare(Song a, Song b){
return a.getTitle().compareTo(b.getTitle());
}
});
//create and set adapter
SongAdapter songAdt = new SongAdapter(this, songList);
songView.setAdapter(songAdt);
//setup controller
setController();
}
//connect to the service
private ServiceConnection musicConnection = new ServiceConnection(){
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
MusicBinder binder = (MusicBinder)service;
//get service
musicSrv = binder.getService();
//pass list
musicSrv.setList(songList);
musicBound = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
//start and bind the service when the activity starts
@Override
protected void onStart() {
super.onStart();
if(playIntent==null){
playIntent = new Intent(this, MusicService.class);
bindService(playIntent, musicConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
}
}
//user song select
public void songPicked(View view){
musicSrv.setSong(Integer.parseInt(view.getTag().toString()));
musicSrv.playSong();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
//menu item selected
switch (item.getItemId()) {
case R.id.action_shuffle:
musicSrv.setShuffle();
break;
case R.id.action_end:
stopService(playIntent);
musicSrv=null;
System.exit(0);
break;
}
return super.onOptionsItemSelected(item);
}
//method to retrieve song info from device
public void getSongList(){
//query external audio
ContentResolver musicResolver = getContentResolver();
Uri musicUri = android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI;
Cursor musicCursor = musicResolver.query(musicUri, null, null, null, null);
//iterate over results if valid
if(musicCursor!=null && 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);
//add songs to list
do {
long thisId = musicCursor.getLong(idColumn);
String thisTitle = musicCursor.getString(titleColumn);
String thisArtist = musicCursor.getString(artistColumn);
songList.add(new Song(thisId, thisTitle, thisArtist));
}
while (musicCursor.moveToNext());
}
}
@Override
public boolean canPause() {
return true;
}
@Override
public boolean canSeekBackward() {
return true;
}
@Override
public boolean canSeekForward() {
return true;
}
@Override
public int getAudioSessionId() {
return 0;
}
@Override
public int getBufferPercentage() {
return 0;
}
@Override
public int getCurrentPosition() {
if(musicSrv!=null && musicBound && musicSrv.isPng())
return musicSrv.getPosn();
else return 0;
}
@Override
public int getDuration() {
if(musicSrv!=null && musicBound && musicSrv.isPng())
return musicSrv.getDur();
else return 0;
}
@Override
public boolean isPlaying() {
if(musicSrv!=null && musicBound)
return musicSrv.isPng();
return false;
}
@Override
public void pause() {
playbackPaused=true;
musicSrv.pausePlayer();
}
@Override
public void seekTo(int pos) {
musicSrv.seek(pos);
}
@Override
public void start() {
musicSrv.go();
}
//set the controller up
private void setController(){
controller = new MusicController(this);
//set previous and next button listeners
controller.setPrevNextListeners(new View.OnClickListener() {
@Override
public void onClick(View v) {
playNext();
}
}, new View.OnClickListener() {
@Override
public void onClick(View v) {
playPrev();
}
});
//set and show
controller.setMediaPlayer(this);
controller.setAnchorView(findViewById(R.id.song_list));
controller.setEnabled(true);
}
private void playNext(){
musicSrv.playNext();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
private void playPrev(){
musicSrv.playPrev();
if(playbackPaused){
setController();
playbackPaused=false;
}
controller.show(0);
}
@Override
protected void onPause(){
super.onPause();
paused=true;
}
@Override
protected void onResume(){
super.onResume();
if(paused){
setController();
paused=false;
}
}
@Override
protected void onStop() {
controller.hide();
super.onStop();
}
@Override
protected void onDestroy() {
stopService(playIntent);
musicSrv=null;
super.onDestroy();
}
}
how can i fix it ? ! help me !
On Android 8.1 API 27 notification does not display
I get Toast on Android 8.1 API 27:
Developer warning for package «my_package_name»
Failed to post notification on …
Logcat includes next strings:
Notification: Use of stream types is deprecated for operations other
than volume controlW/Notification: See the documentation of setSound() for what to use
instead with android.media.AudioAttributes to qualify your playback
use caseE/NotificationService: No Channel found for pkg=my_package_name
The full information in the Toast and in Logcat can help in the localization this problem.
Solution 1:
If you get this error should be paid attention to 2 items and them order:
NotificationChannel mChannel = new NotificationChannel(id, name, importance);
builder = new NotificationCompat.Builder(context, id);
Also NotificationManager notifManager and NotificationChannel mChannel are created only once.
There are required setters for Notification:
- builder.setContentTitle() // required
- .setSmallIcon() // required
- .setContentText() // required
See example:
private NotificationManager notifManager;
public void createNotification(String aMessage, Context context) {
final int NOTIFY_ID = 0; // ID of notification
String id = context.getString(R.string.default_notification_channel_id); // default_channel_id
String title = context.getString(R.string.default_notification_channel_title); // Default Channel
Intent intent;
PendingIntent pendingIntent;
NotificationCompat.Builder builder;
if (notifManager == null) {
notifManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
int importance = NotificationManager.IMPORTANCE_HIGH;
NotificationChannel mChannel = notifManager.getNotificationChannel(id);
if (mChannel == null) {
mChannel = new NotificationChannel(id, title, importance);
mChannel.enableVibration(true);
mChannel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
notifManager.createNotificationChannel(mChannel);
}
builder = new NotificationCompat.Builder(context, id);
intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
builder.setContentTitle(aMessage) // required
.setSmallIcon(android.R.drawable.ic_popup_reminder) // required
.setContentText(context.getString(R.string.app_name)) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setTicker(aMessage)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
}
else {
builder = new NotificationCompat.Builder(context, id);
intent = new Intent(context, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
builder.setContentTitle(aMessage) // required
.setSmallIcon(android.R.drawable.ic_popup_reminder) // required
.setContentText(context.getString(R.string.app_name)) // required
.setDefaults(Notification.DEFAULT_ALL)
.setAutoCancel(true)
.setContentIntent(pendingIntent)
.setTicker(aMessage)
.setVibrate(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400})
.setPriority(Notification.PRIORITY_HIGH);
}
Notification notification = builder.build();
notifManager.notify(NOTIFY_ID, notification);
}
Solution 2:
Andy’s answer is working however I wanted to avoid to deprecated Builder and follow the FireBase Quickstart Project. I just added code before notify from manager.
String channelId = "default_channel_id";
String channelDescription = "Default Channel";
// Since android Oreo notification channel is needed.
//Check if notification channel exists and if not create one
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
NotificationChannel notificationChannel = notificationManager.getNotificationChannel(channelId);
if (notificationChannel == null) {
int importance = NotificationManager.IMPORTANCE_HIGH; //Set the importance level
notificationChannel = new NotificationChannel(channelId, channelDescription, importance);
notificationChannel.setLightColor(Color.GREEN); //Set if it is necesssary
notificationChannel.enableVibration(true); //Set if it is necesssary
notificationManager.createNotificationChannel(notificationChannel);
}
}
//notificationManager.notify as usual
Edit:
They removed the channel exist check from example I am not sure why.
Solution 3:
I have set channel id, but notification still not shown.
Finally i found my problem is had not invoke «setContentText()» method.
It was really help me that @Andy Sander mentioned «required setters»!
here are required setters for Notification on Android 8 Oreo API 26 and later:
builder.setContentTitle() // required
.setSmallIcon() // required
.setContentText() // required
.setChannelId(id) // required for deprecated in API level >= 26 constructor .Builder(this)