新人学习,仅供参考!
package com.example.administrator.settingactivity.util;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.provider.MediaStore;
import android.widget.RemoteViews;
import com.example.administrator.settingactivity.R;
import com.example.administrator.settingactivity.activity.HelpActivity;
/**
* Created by Administrator on 2017/1/10.
*/
public class NotificationUtil {
//通知管理类
private static NotificationManager manager;
//通知
private static Notification notification;
//id
private static final int ID=1;
//是否开启通知
public static boolean isOpenNotification(Context context){
SharedPreferences sharedPreferences=context.getSharedPreferences("notification",context.MODE_PRIVATE);
return sharedPreferences.getBoolean("open",true);
}
/**
* 记录通知开启状态 重要记住部分
*/
public static void setOpenNotification(Context context,boolean open){
SharedPreferences sharedPreferences=context.getSharedPreferences("notification",context.MODE_PRIVATE);
SharedPreferences.Editor editor=sharedPreferences.edit();
editor.putBoolean("open",open);
editor.commit();
}
/**
* 取消通知
*/
public static void cancle(Context context) {
if(manager==null){
manager= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
manager.cancel(ID);
}
/**
* 显示通知
*/
public static void showNotification(Context context) {
if (notification==null){
notification = new Notification();//初始化
}
//标志
notification.flags=Notification.FLAG_NO_CLEAR;
//图标
notification.icon= R.mipmap.ic_launcher;
//提示内容
notification.tickerText="新消息";
//声音
notification.sound= Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI,"6");
//震动
notification.defaults |=Notification.DEFAULT_VIBRATE;
notification.when = System.currentTimeMillis();
//加载布局
notification.contentView = new RemoteViews(context.getPackageName(),R.layout.layout_notification_appincon);
//点击方式
notification.contentIntent= PendingIntent.getActivity(context,1,new Intent(context,HelpActivity.class),PendingIntent.FLAG_UPDATE_CURRENT);
//获取通知
if (manager==null){
manager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
}
manager.notify(ID,notification);
}
}