Notification
package com.example.mynotification;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.RemoteViews;
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
private Button mButton1,mButton2,mButton3;
private NotificationManager manager;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button mButton1= (Button) findViewById(R.id.button1);
Button mButton2= (Button) findViewById(R.id.button2);
Button mButton3= (Button) findViewById(R.id.button3);
mButton1.setOnClickListener(this);
mButton2.setOnClickListener(this);
mButton3.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()){
case R.id.button1:
Notification.Builder builder=new Notification.Builder(this);
//设置提示内容
builder.setTicker("你有一个新消息");
//设置图标
builder.setSmallIcon(R.mipmap.ic_launcher);
builder.setContentTitle("MyNotification");
builder.setContentText("发生了一个通知");
//设置当前时间
builder.setWhen(System.currentTimeMillis());
//将Intent进行包装,1和0是自己随便写的。
//不知道会在哪里发生跳转,自己设置,当需要发生跳转的时候进行点击
PendingIntent pendingIntent=PendingIntent.getActivity(this,1,
new Intent(MainActivity.this,MainActivity.class),0);
builder.setContentIntent(pendingIntent);
manager.notify(1,builder.build());
break;
case R.id.button2:
//自定义通知
Notification notification=new Notification();
notification.icon=R.mipmap.ic_launcher;
notification.flags=Notification.FLAG_NO_CLEAR;
RemoteViews remoteViews=new RemoteViews(getPackageName(),R.layout.my_notification);
remoteViews.setTextViewText(R.id.textview,"发来的短信息");
PendingIntent pendingIntent1=PendingIntent.getActivity(this,1,
new Intent(MainActivity.this,MainActivity.class),0);
notification.contentView=remoteViews;
notification.contentIntent=pendingIntent1;
manager.notify(2,notification);
break;
case R.id.button3:
//清除Notification
manager.cancel(1);
break;
default:
break;
}
}
}