- 今天使用Notification做一个通知消息的时候,突然TMD居然无效,反复的搞整无果,于是乎谷歌了一把,发现跟系统版本有关系,貌似8.0系统以上的系统使用以前的方法实现都无效,万能的百度告诉我需要设置渠道,结果可以正常实现了,废话不多说了,直接上马:
import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;
import android.support.annotation.RequiresApi;
import com.jbh.goldrush.R;
import static android.content.Context.NOTIFICATION_SERVICE;
public class NotificationUtil {
private Context mContext;
private NotificationManager notificationManager;
private int progress = 0 ;
private int notificationId = 0x2154;
private Notification.Builder builder;
private String ContentTitle = "";
private String ContentText = "";
/**
* @param context
*/
public NotificationUtil(Context context){
this.mContext = context;
notificationManager = (NotificationManager) mContext.getSystemService(NOTIFICATION_SERVICE);
sendNotification();
}
@TargetApi(Build.VERSION_CODES.O)
private void sendNotification(){
String channelId = "my_channel_01";
String name="我是渠道名字";
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
@SuppressLint("WrongConstant")
NotificationChannel mChannel = new NotificationChannel(channelId, name, NotificationManager.IMPORTANCE_LOW);
notificationManager.createNotificationChannel(mChannel);
builder = new Notification.Builder(mContext)
.setChannelId(channelId) //设置渠道id
.setContentTitle(ContentTitle)
.setContentText(ContentText)
.setSmallIcon(R.mipmap.app_logo);
LogUtils.TOAST("O");
} else {
builder = new Notification.Builder(mContext)
.setContentTitle(ContentTitle)
.setContentText(ContentText)
.setSmallIcon(R.mipmap.app_logo)
.setOngoing(true)
.setChannelId(channelId);//无效
LogUtils.TOAST("dfasd");
}
notificationManager.notify(notificationId, builder.build());
}
/**
* @param contentText
* @return
*/
public NotificationUtil setContentText(String contentText) {
ContentText = contentText;
return NotificationUtil.this ;
}
/**
*
* @param contentTitle
* @return
*/
public NotificationUtil setContentTitle(String contentTitle) {
ContentTitle = contentTitle;
return NotificationUtil.this ;
}
/**
* @param progress
*/
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
public void setProgress(int progress){
if (builder==null)return;
builder.setProgress(100,progress,false);
builder.setContentTitle("下载中...");
if (progress==100){
builder.setContentTitle("下载完成");
//自动移除
notificationManager.cancel(notificationId);
}else {
notificationManager.notify(notificationId, builder.build());//显示通知
}
}
public void ceShi(){
new Thread(new Runnable() {
@RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
@Override
public void run() {
while (progress++<100){
setProgress(progress);
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}).start();
}