通知使用的时候不用直接实例化,要用到通知管理器获取系统服务 mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
public class MainActivity extends Activity {private Button button;
private Button button2;
private NotificationManager mNotificationManager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
button = (Button) findViewById(R.id.button1);
button2 = (Button) findViewById(R.id.button2);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Notification.Builder mBuilder = new Notification.Builder(
MainActivity.this);
// 创建意图,当点击通知时,跳转到MyActivity
Intent resultIntent = new Intent(MainActivity.this,
MyActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(
MainActivity.this, 0, resultIntent, 0);
mBuilder.setContentIntent(pendingIntent);
// 设置通知的属性信息
mBuilder.setSmallIcon(R.drawable.image5);
mBuilder.setContentTitle("通知");
mBuilder.setContentText("Hello WOrld!");
mBuilder.setTicker("有通知来了");
// 创建通知并执行通知
Notification notification = mBuilder.build();
mNotificationManager.notify(0, notification);
}
});
button2.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
mNotificationManager.cancel(0);//取消通知,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;
}
}