您的位置:首页 > 其它

通知栏(Notification)的基本使用

2017-09-18 19:27 218 查看
通知是Android系统中比较有特色的一个功能,当某个应用程序希望向用户发出一些提示信息,而应用程序又不在前台运行时,可以通过通知来实现。发送一个通知,手机的最上方会出现通知的图标,下拉状态栏的时候,可以看到通知的详细内容。

一.通知的基本使用:

(1).先获取通知的管理者对象,通过下面的方式获取

NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

(2).开启通知前,需要一个Notification的对象,由于版本的兼容,采用V4包下的NotificationCompat类来获取

Notification notification = new NotificationCompat.Builder(this).build();
(3).发送一个通知(一个id对应一个通知)

manager.notify(1,notification);
二.构建一个丰富多样的通知显示代码:

布局代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

<Button
android:id="@+id/btn_send"
android:text="发送一条通知"
android:textColor="#ff0000"
android:layout_width="match_parent"
android:layout_height="wrap_content"/>
</LinearLayout>


页面逻辑实现:

public class MainActivity extends AppCompatActivity{

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
findViewById(R.id.btn_send).setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendNotification();

4000
}
});
}

private void sendNotification() {
//1.获取通知管理者对象
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//如果需要通知可点击,需要使用PendingIntent(延迟意图)
Intent intent = new Intent(MainActivity.this,NotificationActivity.class);
//参数:(上下文,请求码(通常填0,不常用),意图对象,行为(通常填0))
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, 0);
//2.获取一个notification对象实例
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle("银行到账")//设置标题
.setContentText("工商银行为你转入10000000000,你卡上余额为10000003460。")//设置内容
.setWhen(System.currentTimeMillis())//设置通知的时间
.setSmallIcon(R.drawable.zhifu_icon_payply)//设置小图标
.setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.zhifu_icon_payply))//设置大图标
.setContentIntent(pendingIntent)//延迟处理的意图,当点击通知时
.setAutoCancel(true)//设置当用户点击面板时通知自动取消
//.setSound(Uri.fromFile(new File(".....")))//设置声音播放
//.setLights(Color.GREEN,1000,1000)//设置LED闪烁灯
.setDefaults(NotificationCompat.DEFAULT_ALL)//使用默认的通知选项
.setPriority(NotificationCompat.PRIORITY_MAX)//设置通知的优先级
.build();
//3.开启通知
manager.notify(1,notification);
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: