Android Notification的基本应用 (8.1)

来源:互联网 发布:熟练使用办公软件 编辑:程序博客网 时间:2024/05/29 18:43

效果:点击按钮,然后发送一条通知,点击通知,程序打开Mainactivity

思路:

1 获取通知管理器NotificationManager

2设置PendingIntent(点击通知之后的处理,例如打开应用)

3.设置通知的具体显示内容等

4.NotificationManager发送通知

代码如下:

public class NotificationActvity extends Activity implements View.OnClickListener{    private Button sendNotification;    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.notification);        sendNotification=(Button)findViewById(R.id.send_notification);        sendNotification.setOnClickListener(this);    }    @Override    public void onClick(View v) {        switch (v.getId()){            case R.id.send_notification:                //获取通知管理                NotificationManager notificationManager= (NotificationManager) getSystemService(NOTIFICATION_SERVICE);                Intent intent = new Intent(this, MainActivity.class);                // 获得PendingIntent    延迟执行的Intent                PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);                //设置通知到来时的振动时间 此数组依次是静音时长,振动时长,此处是振动两次,中间间隔1秒                // 要在声明文件中声明振动的权限  <uses-permission android:name="android.permission.VIBRATE"/>                long [] vibrates = {0,1000,1000,1000};                //               创建通知对象   notification. setLatestEventInfo()  这个方式是API level11以下的方式,               //   API level16 以上已经淘汰了这种方式,改用一下的方式                Notification notification = new Notification.Builder(this)                        .setAutoCancel(true)                        .setContentTitle("您有一条新消息")                        .setContentText("今天深圳气温是24-28度")                        .setContentIntent(pendingIntent)//设置点击通知之后启动的意图,此处的意图是跳转到MainActivity界面                        .setSmallIcon(R.drawable.ic_launcher)                        .setWhen(System.currentTimeMillis())                        .setAutoCancel(true)//点击通知之后,通知取消                        .setVibrate(vibrates)                        .build();                notification.flags |= Notification.FLAG_AUTO_CANCEL; // FLAG_AUTO_CANCEL表明当通知被用户点击时,通知将被清除。                // 通过通知管理器来发起通知。如果id不同,则每click,在statu那里增加一个提示                notificationManager.notify(1, notification);                break;        }    }}


0 0
原创粉丝点击