Android 状态栏面板中的通知工具栏?

Android Notification Toolbar in the Status bar panel?

我想知道如何在任何 android 设备的 android 状态栏中实现固定工具栏。 我说的是下面显示的通知中的按钮。下面提供了一个示例。即使用户没有打开应用程序,也可能有这个 运行 吗?

有人能指出我正确的方向吗?是否有库或者我们可以使用提供的本机 android 库来实现它?

作为一个简单的示例,以下代码将在启动时发出持续 NotificationButton 以启动您的应用程序。

首先,在您的清单中,请求获得 BOOT_COMPLETED 广播的权限,并注册一个 Receiver 来处理它。

<manifest ...>

    <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
    ...

    <application ...>
        ...

        <receiver android:name=".BootReceiver">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>
    </application>
</manifest>

BootReceiver 仅使用 static 方法发出 Notification,此示例在 MainActivity 中定义。

public class BootReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        MainActivity.setNotification(context, true);
    }
}

setNotification() 方法使用下面的简单布局为 Notification 创建一个 RemoteViews 实例,并在 Button 上设置一个 PendingIntent为您的应用启动 Intent

public static void setNotification(Context context, boolean enabled) {
    NotificationManager manager =
        (NotificationManager) context.getSystemService(NOTIFICATION_SERVICE);

    if (enabled) {
        final RemoteViews rViews = new RemoteViews(context.getPackageName(),
                                                   R.layout.notification);

        final Intent intent = context.getPackageManager()
            .getLaunchIntentForPackage(context.getPackageName());

        if (intent != null) {
            PendingIntent pi = PendingIntent.getActivity(context,
                                                         0,
                                                         intent,
                                                         0);

            rViews.setOnClickPendingIntent(R.id.notification_button_1, pi); 
        }

        Notification.Builder builder = new Notification.Builder(context);
        builder.setContent(rViews)
            .setSmallIcon(R.drawable.ic_launcher)
            .setWhen(0)
            .setOngoing(true);

        manager.notify(0, builder.build());
    }
    else {
        manager.cancel(0);
    }
}

Notification 的布局只是 ImageView 和水平 LinearLayout 中的 Button

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView android:id="@+id/notification_image"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginRight="10dp"
        android:src="@drawable/ic_launcher" />

    <Button android:id="@+id/notification_button"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:text="Button" />

</LinearLayout>

请注意,自 API 3.1 起,您必须在安装后至少启动一次您的应用才能使其退出 已停止 状态。到那时,BootReceiver 将不会传送广播。