В качестве простого примера, следующий код будет выдавать при загрузке постоянной Notification
с Button
, чтобы запустить приложение.
Во-первых, в вашем манифесте запросите разрешение на трансляцию BOOT_COMPLETED
и зарегистрируйте приемник для его обработки.
<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
просто выдает Notification
с использованием static
метода, который определен в MainActivity
для этого примера.
public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
MainActivity.setNotification(context, true);
}
}
setNotification()
Метод создает RemoteViews
экземпляр для Notification
с помощью простого макета ниже, и устанавливает PendingIntent
на Button
с запуском 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
и Button
в горизонтальном LinearLayout
.
<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
не будет доставлен в эфир.
Вы можете просто создать постоянное «уведомление» с пользовательским «представлением», которое запускается в загрузочном приемнике. Нет необходимости в библиотеке. –
Можете ли вы привести мне пример или ссылку? :) @MikeM. – Dinuka