使用通知在手机上

本文介绍了Android系统中的通知功能,通过一个项目演示如何创建和使用通知,包括使用NotificationCompat.Builder创建兼容各版本的Notification对象,以及利用PendingIntent实现点击通知后的响应。还涉及到布局文件和MainActivity.java的代码修改,以及NotificationCompat.Builder的常用API设置。
摘要由CSDN通过智能技术生成

通知是Android系统中比较有特色的一个功能,当某个应用程序需要向用户发送一条提示信息的时候,而该程序又不在前台运行,就可以借助通知来实现。发送通知后,状态栏会显示一个特制的图标,下拉状态栏可以看到通知的详细内容。

我们通过一个项目来看下通知是怎么使用的吧!

布局文件activity_main.xml代码

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">

<Button
    android:id="@+id/send_notice"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:text="发送通知"/>

</LinearLayout>

一个按钮,用于发送这条通知。

MainActivity.java代码

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

private Button send;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    send = findViewById(R.id.send_notice);
    send.setOnClickListener(this);
}

@Override
public void onClick(View v) {
    switch (v.getId()){
        case R.id.send_notice:
            //得到一个NotificationManager,用于管理通知
            NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);

            //需添加的代码
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O){
                String channelId = "default";
                String channelName = "默认通知";
                m
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值