Live Activities:提高Android应用的实时交互性

 

目录

一、什么是 Live Activities?

二、Live Activities 的优势

三、使用 Live Activities 的前提条件

四、如何实现 Live Activities?

4.1 配置 Android 项目

4.2 添加通知权限

4.3 创建 Live Activity 类

4.4 启动 Live Activity

4.5 启动和停止定时更新

4.6 权限请求

4.7 处理权限请求结果

五、总结


深入解析 Android 14 的 Live Activities 功能

在 Android 14 发布时,Google 引入了一个全新的功能——Live Activities。这个功能允许应用在通知栏、锁屏等区域实时展示动态内容,通过持续更新通知来提升用户体验,尤其适用于需要实时更新的数据场景,例如体育赛事、外卖配送进度、航班信息等。今天我们将一起深入了解 Live Activities 的工作原理,并展示如何在 Android 应用中实现它。

一、什么是 Live Activities?

Live Activities 是 Android 14 中新增的功能,允许应用通过动态更新通知展示实时信息。与传统的静态通知不同,Live Activities 使得通知内容可以在实时变化的同时提供更丰富的交互体验。用户无需打开应用,即可在通知栏和锁屏界面查看实时数据,这为应用提供了一个更加流畅和实时的用户体验。

二、Live Activities 的优势

  1. 实时更新:应用可以持续将最新数据呈现给用户,免去手动刷新或打开应用的麻烦。
  2. 提升用户参与度:实时通知增加了用户与应用的互动,增强了应用的可见性和参与感。
  3. 节省时间与精力:用户无需频繁切换应用或浏览多个界面,所有关键信息随时一目了然。

三、使用 Live Activities 的前提条件

要在 Android 应用中实现 Live Activities,需确保以下条件:

  • Android 14 或更高版本:Live Activities 是 Android 14 新增的功能,因此需要 Android 14 及以上版本才能使用。
  • 开发环境支持:需要使用 Android Studio 4.2 或更高版本,并确保已安装相关 SDK 工具。
  • 通知权限:应用必须具备 POST_NOTIFICATIONS 权限,才能在锁屏和通知栏中显示 Live Activities。

四、如何实现 Live Activities?

接下来,我们将详细介绍如何在 Android 应用中实现 Live Activities,包括配置项目、创建 Live Activity 服务和启动实时通知的步骤。本篇文章使用java实现,因为博主不会kotlin(哭)

4.1 配置 Android 项目

首先,确保项目使用的是 Android 14 或更高版本。在 build.gradle 文件中,配置 compileSdkVersion 为 34(即 Android 14):

android {
    compileSdkVersion 34 // Android 14
    defaultConfig {
        minSdkVersion 24 // 支持 Android 14 及更高版本
    }
}

如果使用的是 build.gradle.kts,则:

android {
    compileSdk = 34 // Android 14
    defaultConfig {
        minSdk = 24 // 支持 Android 7.0 (API 24) 及更高版本
    }
}
4.2 添加通知权限

AndroidManifest.xml 中添加 POST_NOTIFICATIONS 权限,允许应用展示通知:

<uses-permission android:name="android.permission.POST_NOTIFICATIONS" />
4.3 创建 Live Activity 类

接下来,我们需要创建一个 LiveActivityService 类,用于展示和更新实时的通知。以下是一个实现示例,其中我们模拟了一个体育赛事的实时比分更新。

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.content.Context;
import android.os.Build;

public class LiveActivityService {

    // 定义常量,用于通知频道的 ID
    private static final String CHANNEL_ID = "live_activity_channel";
    private NotificationManager notificationManager; // 用于管理通知的 NotificationManager
    private Context context; // 添加成员变量 context,用于存储上下文对象

    // 构造函数,用于初始化 context 和 notificationManager
    public LiveActivityService(Context context) {
        this.context = context;
        notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
        
        // 如果 Android 版本大于等于 Oreo (Android 8.0),创建通知频道
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(
                    CHANNEL_ID, // 通知频道的唯一标识符
                    "Live Activities Channel", // 频道名称
                    NotificationManager.IMPORTANCE_HIGH // 设置为高优先级
            );
            notificationManager.createNotificationChannel(channel); // 注册通知频道
        }
    }

    // 更新实时活动通知的方法
     public void updateLiveActivity(String liveData) {
        Log.d("LiveActivityService", "Updating live activity with data: " + liveData);
        Notification notification = new Notification.Builder(context, CHANNEL_ID)
                .setContentTitle("Live Activity")
                .setContentText(liveData)
                .setSmallIcon(R.drawable.ic_live_activity)
                .setOngoing(true)
                .build();

        notificationManager.notify(1, notification);
    }
}
4.4 启动 Live Activity

activity_main.xml 文件中,我们创建了两个按钮,一个用于启动实时更新,另一个用于停止更新:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/singleButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Update" />

    <Button
        android:id="@+id/stopButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Stop Update" />
</LinearLayout>

大致呈现以下效果

 

MainActivity 中,我们初始化 LiveActivityService 并设置按钮的点击事件处理以及授权:

 
    // 使用 Data Binding 绑定布局文件
    private ActivityMainBinding binding;

    // 用于延迟任务的 Handler
    private Handler handler = new Handler(Looper.getMainLooper());

    // 定义一个 Runnable 对象,用于定期更新 Live Activity
    private Runnable runnable;

    // LiveActivityService 实例,用于更新 Live Activity
    private LiveActivityService liveActivityService;

    // 请求权限的请求码
    private static final int REQUEST_CODE_NOTIFICATION_PERMISSION = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // 使用 Data Binding 初始化布局
        binding = ActivityMainBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());

        // 初始化 LiveActivityService
        liveActivityService = new LiveActivityService(this);

        // 获取单击按钮的引用
        Button singleButton = binding.singleButton;
        singleButton.setOnClickListener(view -> {
            liveActivityService.updateLiveActivity("New Score: 2 - 1");
            startUpdatingLiveActivity();
           
        });

        // 获取停止按钮的引用
        Button stopButton = binding.stopButton;
        stopButton.setOnClickListener(view -> {
            // 停止定时更新 Live Activity
            stopUpdatingLiveActivity();
        });
    }
4.5 启动和停止定时更新

为了定期更新通知内容,我们使用 Handler 来创建一个定时更新任务:

private void startUpdatingLiveActivity() {
        // 定义一个 Runnable 对象,用于定期更新 Live Activity
        runnable = new Runnable() {
            @Override
            public void run() {
                // 更新 Live Activity 的内容
                liveActivityService.updateLiveActivity("Updated Score: " + System.currentTimeMillis());
                // 延迟 5 秒后再次执行此 Runnable
                handler.postDelayed(this, 5000);
            }
        };
        // 立即执行 Runnable
        handler.postDelayed(runnable, 0);
    }

    // 停止定时更新 Live Activity 的方法
    private void stopUpdatingLiveActivity() {
        // 检查 Runnable 是否为空
        if (runnable != null) {
            // 移除所有延迟的任务
            handler.removeCallbacks(runnable);
            // 将 Runnable 置为 null(可选)
            runnable = null;
        }
    }
4.6 权限请求

看起来代码已经完成了,此时启动程序,点击按钮确毫无反应,这是为什么?我们打开日志,会发现live activities却在正常运行

这是因为从 Android 13 开始,POST_NOTIFICATIONS 是一个运行时权限。需要确保用户在运行时授予了该权限 我们在onCreate里补全singleButton

 singleButton.setOnClickListener(view -> {
            // 检查是否已经授予 POST_NOTIFICATIONS 权限
            if (ContextCompat.checkSelfPermission(this, Manifest.permission.POST_NOTIFICATIONS)
                    != PackageManager.PERMISSION_GRANTED) {
                // 如果未授予权限,请求权限
                ActivityCompat.requestPermissions(this,
                        new String[]{Manifest.permission.POST_NOTIFICATIONS},
                        REQUEST_CODE_NOTIFICATION_PERMISSION);
            } else {
                // 如果已授予权限,更新 Live Activity 并开始定时更新
                liveActivityService.updateLiveActivity("New Score: 2 - 1");
                startUpdatingLiveActivity();
            }
        });

此时运行程序,则会弹出权限授予请求,当然点击allow

然后就能看见live activities了!

4.7 处理权限请求结果

onRequestPermissionsResult 方法中,我们处理权限请求的结果,并在用户授予权限后开始实时更新:

  @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults); // 调用父类的实现

        // 检查请求码是否匹配
        if (requestCode == REQUEST_CODE_NOTIFICATION_PERMISSION) {
            // 检查权限请求结果
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                // 如果用户授予了权限,更新 Live Activity 并开始定时更新
                liveActivityService.updateLiveActivity("New Score: 2 - 1");
                startUpdatingLiveActivity();
            } else {
                // 用户拒绝了权限请求
                // 可以在这里提示用户手动开启权限
            }
        }
    }

五、总结

Live Activities 是 Android 14 引入的一项强大功能,允许应用通过动态通知展示实时更新的信息。通过这一功能,用户无需打开应用即可获取最新的实时数据,大大提升了应用的可用性和互动性。通过简单的代码实现,我们可以在体育赛事、订单跟踪等场景中为用户提供更加流畅和实时的信息展示。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Phenylalanine_苯丙氨酸

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值