package com.noti.activity;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.RemoteViews;
public class Main extends Activity {
/** Called when the activity is first created. */
private Button btn;//使用系統的notification布局
private Button btn1;//使用自訂布局
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
btn = (Button) findViewById(R.id.btn);
btn1 = (Button) findViewById(R.id.btn1);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showNotification();
}
});
btn1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
showMyNotification();
}
});
}
public void showNotification(){
獲得系統的NotificationManager對象
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//執行個體化一個的notification
Notification notification = new Notification(R.drawable.image1, "notice", System.currentTimeMillis());
Intent intent = new Intent(Main.this,OtherActivity.class);//點擊這個notification觸發的Intent
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 1);
notification.setLatestEventInfo(this, "title","a message", pendingIntent);//顯示notification的布局和觸發器
notificationManager.notify(R.id.btn, notification);//發出通知,根據Id判斷是否為新的通知
}
public void showMyNotification(){
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
Notification notification = new Notification(R.drawable.icon, "notice", System.currentTimeMillis());
//要實現自訂布局,首先自己定義一個 布局檔案notification.xml,如放一個ImageView 和 TextView,用這個布局檔案產生 //RemoteViews的執行個體
RemoteViews contentview = new RemoteViews(getPackageName(), R.layout.notification);
contentview.setImageViewResource(R.id.image, R.drawable.image1);
contentview.setTextViewText(R.id.text, "hello world");
//將視圖賦值給notification
notification.contentView = contentview;
notification.contentIntent = pendingIntent;
//以上代碼代替系統的setLatestEventInfo()方法
Intent intent = new Intent(Main.this,OtherActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 1);
notificationManager.notify(R.id.btn, notification);
}
}