简介
- 这是一种具有全局效果的通知
- 最典型的例子就是QQ了
- 一般比较重要的通知,我们都是使用这个来通知用户的
使用
记得要导入包哦!
compile 'com.android.support:support-v4:+'
实例:
public class MainActivity extends AppCompatActivity
{
private NotificationManager notificationManager;
private NotificationCompat.Builder notificationCompat;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
notificationManager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notificationCompat=new NotificationCompat.Builder(this);
notificationCompat.setContentText("内容");
notificationCompat.setContentTitle("标题");
notificationCompat.setSmallIcon(R.drawable.ic_launcher);
findViewById(R.id.mainButton1).setOnClickListener(new OnClickListener(){
@Override
public void onClick(View p1)
{
notificationManager.notify(1, notificationCompat.build());
}
});
}
}
效果图:
怎么回事?怎么和QQ的效果不一样呢?别着急,我们继续往下看,在里面再添加这两段代码,然后我们再试试!
notificationCompat.setPriority(NotificationCompat.PRIORITY_MAX);
notificationCompat.setDefaults(NotificationCompat.DEFAULT_ALL);
效果图:
嘿嘿,已经可以了,接下来,让我们为它设置一个点击事件吧!
- Notification不仅仅能够对用户进行通知,还能够与用户发生互动
- 我们可以通过PendingIntent为我们的Notification设置点击事件
- PendingIntent可选的主要有getActivity、getBroadcast、getService
添加下面的两段代码
Intent in=new Intent(Intent.ACTION_VIEW,Uri.parse("https://m.baidu.com"));
PendingIntent pendingIntent=PendingIntent.getActivity(this,0,in,0);
//为Notification整体设置一个点击事件
notificationCompat.setContentIntent(pendingIntent);
完整代码:
public class