Notification是Android中用于消息通知的机制,具体形式是,有消息来后,会在Android手机顶部的状态栏中显示提示信息,如,各自APP的消息通知。
使用Notification基本有以下几个步骤
1 获取NotificationManager
NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
该对象用来后面发送消息
2 创建NotificationCompat.Builder
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
该对象主要是对消息的外观进行封装
3 对Builder设置相关的Notification属性,必要属性如下:
builder.setContentTitle("标题"); builder.setContentText("内容:Android很好玩"); builder.setSmallIcon(R.mipmap.ic_launcher); builder.setContentIntent(pendingIntent);
4 使用Builder创建通知
Notification notification = builder.build();
5 发送通知
notificationManager.notify(199, notification);
如此,一个基本通知消息就发送出去了。
参考:http://blog.csdn.net/u012124438/article/details/53574649
测试源码:
package com.example.xxh.notifymsg; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.content.Intent; import android.net.Uri; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.support.v7.app.NotificationCompat; import android.view.View; import android.widget.Button; public class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button btn = (Button)findViewById(R.id.btn); btn.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sendSimpleNotification(); } }); } private void sendSimpleNotification() { Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel: 10086")); PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); NotificationManager notificationManager = (NotificationManager)getSystemService(NOTIFICATION_SERVICE); NotificationCompat.Builder builder = new NotificationCompat.Builder(this); builder.setContentTitle("标题"); builder.setContentText("内容:Android很好玩"); builder.setSmallIcon(R.mipmap.ic_launcher); builder.setContentIntent(pendingIntent); Notification notification = builder.build(); notification.flags = Notification.FLAG_SHOW_LIGHTS | Notification.FLAG_INSISTENT | Notification.FLAG_AUTO_CANCEL; notificationManager.notify(199, notification); } }