Android 之 Notification 通知消息
NotificationManager是显示在手机状态栏的消息,如短息提醒等,做得大点,可以做消息推送等。下面的实例程序示范了如何通过NotificationManager来发送、取消Notification,本程序的界面很简单,只是包含了两个按钮,分别用于发送Notification和取消Notification,主要的java代码如下:
notification.java:
package com.example.notification;
import android.os.Bundle;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
static final int NOTIFICATION_ID = 0x1123;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button b1=(Button)findViewById(R.id.b1);
b1.setOnClickListener((View.OnClickListener) this);
Button b2=(Button)findViewById(R.id.b2);
b2.setOnClickListener((View.OnClickListener) this);
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.b1:
Intent intent = new Intent();
intent.setClass(MainActivity.this, other.class);
PendingIntent pi = PendingIntent.getActivity(MainActivity.this, 0, intent, 0);
Notification notify = new Notification();
notify.icon = R.drawable.no;
notify.tickerText = "自己做的消息呀";
notify.when = System.currentTimeMillis();
notify.defaults = Notification.DEFAULT_ALL;
notify.setLatestEventInfo(MainActivity.this, "站内信", "五一放假通知", pi);
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, notify);
break;
case R.id.b2:
NotificationManager notificationmanager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
notificationmanager.cancel(NOTIFICATION_ID);
break;
}
}
}
other.java
package com.example.notification;
import android.app.Activity;
import android.os.Bundle;
public class other extends Activity
{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.otherx);
}
}
运行效果图:
点击开始推送后:
附件是源码,需要的请下载。