Notification的使用

1、在LV16之前的用法

public class MainActivity extends Activity {

  private NotificationManager notificationManager;

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
  }

  
  
  public void test1(View v){
    //Toast.makeText(this, "點擊我了", Toast.LENGTH_LONG).show();
    showNotification("來短信了", "5554", "I love you", R.drawable.ic_launcher, R.drawable.ic_launcher);
    
  }
  
  
  public void showNotification(String tickerText,String contentTitle,String contentText,int iconId,int notiId){
    //2步建立一個Notification
    Notification notification = new Notification();
    //設置通知 消息  圖標
    notification.icon=iconId;
    //設置發出消息的內容   這個指的是剛推送出的內容
    notification.tickerText=tickerText;
    //設置發出通知的時間
    notification.when=System.currentTimeMillis();
    
    //設置顯示通知時的默認的發聲、振動、Light效果
    notification.defaults = Notification.DEFAULT_VIBRATE;//振動
    
    //Notification notification = new Notification(R.drawable.ic_launcher, "有新的消息", System.currentTimeMillis());
    
    //3步:PendingIntent  android系統負責維護
    
    PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, getIntent(), 0);
    
    //4步:設置更加詳細的信息
    notification.setLatestEventInfo(this, contentTitle, contentText, pendingIntent);
    
    //5步:使用notificationManager對象的notify方法 顯示Notification消息   須要制定 Notification的標識
    notificationManager.notify(notiId, notification);
    
 
  }
  
  
  public void clearNoti(View v){
    notificationManager.cancel(notiId);//清除具體的Notifaction
    notificationManager.cancelAll();//清除全部
  }

}
View Code

2、在LV16之後的用法

//設置Intent跳轉
Intent intent = new Intent(this,OtherActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT);
        //利用Notification.Builder建立Notification
        Notification.Builder notification = new Notification.Builder(this);
        notification.setAutoCancel(true);
        notification.setSmallIcon(R.mipmap.ic_launcher);
        notification.setContentTitle("Hello World");
        notification.setContentText("I am a ET");
        notification.setContentIntent(pendingIntent);
        //建立Notification
        Notification notification1 = notification.build();
        //獲取Notification管理器
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //執行
        manager.notify(0,notification1)
View Code
相關文章
相關標籤/搜索