//启动activity时,通过线程休眠5秒后,发送通知,点击通知进入通知界面,查看通知信息
import android.app.Activity;
import android.app.Notification;import android.app.Notification.Builder;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.BitmapFactory;
import android.os.Bundle;
public class MainActivity extends Activity {
private final int NOTIFICATION_BASE_NUMBER =120;
private NotificationManager nm = null;
private PendingIntent contentIntent = null;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 设置5秒后发送一个消息,这里可以进行相关的数据检测,查看系统是否含有通知信息,如果含有,那么发送消息,否则不放松
// 还可以添加判断,通过获取系统时间,每天发送一次消息,
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
showNotification();
}
}).start();
}
protected void onStop() {
clearNotification();
super.onStop();
}
@Override
protected void onStart() {
super.onStart();
}
private void showNotification() {
Builder builder = null;
Notification n = null;
nm = (NotificationManager) this.getSystemService(NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(this, NotificationActivity.class);
contentIntent = PendingIntent.getActivity(MainActivity.this, 0,
notificationIntent, 0);
Resources res = MainActivity.this.getResources();
builder = new Notification.Builder(MainActivity.this);
builder.setContentIntent(contentIntent)
.setSmallIcon(R.drawable.ic_launcher)
// 设置状态栏里面的图标(小图标)
.setLargeIcon(
BitmapFactory.decodeResource(res,
R.drawable.ic_launcher))// 下拉下拉列表里面的图标(大图标)
.setTicker("this is bitch!")
// //设置状态栏的显示的信息
.setWhen(System.currentTimeMillis())// 设置时间发生时间
.setAutoCancel(true)// 设置可以清除
.setContentTitle("通知")// 设置下拉列表里的标题
.setContentText("这是一个测试通知!");// 设置上下文内容
n = builder.build();// 获取一个Notification
n.defaults = Notification.DEFAULT_SOUND;// 设置为默认的声音
nm.notify(NOTIFICATION_BASE_NUMBER, n);
}
// 删除通知
private void clearNotification() {
// 启动后删除之前我们定义的通知
NotificationManager notificationManager = (NotificationManager) this
.getSystemService(NOTIFICATION_SERVICE);
notificationManager.cancel(0);
}
}