Внедрить метод startForeground в Android
Я хочу реализовать метод startForeground()
в классе Service
для предотвращения самозавершения службы.
Может кто-нибудь прислал мне код для реализации этого метода?
Ответы
Ответ 1
Jovan, вот способ создания совместимого кода для 2.0+ и 1.6- (код показывает вам, как определить, какой из них совместим)
http://android-developers.blogspot.com/2010/02/service-api-changes-starting-with.html
Для 2.0+ я собрал некоторый пример кода (используя startForeground). Обратите внимание, что некоторый код теперь устарел, однако Notification.Builder использует уровень API 11 (3.x), что означает, что я не буду использовать его, пока большинство телефонов не будут использовать совместимую версию Android. Так как подавляющее большинство телефонов теперь используют некоторую версию 2.x, я думаю, что это достаточно безопасно, чтобы пропустить проверку совместимости.
final static int myID = 1234;
//The intent to launch when the user clicks the expanded notification
Intent intent = new Intent(this, SomeActivityToLaunch.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent, 0);
//This constructor is deprecated. Use Notification.Builder instead
Notification notice = new Notification(R.drawable.icon_image, "Ticker text", System.currentTimeMillis());
//This method is deprecated. Use Notification.Builder instead.
notice.setLatestEventInfo(this, "Title text", "Content text", pendIntent);
notice.flags |= Notification.FLAG_NO_CLEAR;
startForeground(myID, notice);
поместите этот код в onStartCommand()
вашего сервиса, и вам хорошо идти. (Но вы можете поместить этот раздел кода в любом месте своей службы.)
P.S. чтобы остановить обслуживание на переднем плане, просто используйте stopForeground(true);
в любом месте службы
Ответ 2
Этот код будет использовать лучший вариант для любого API, добавив в ваш проект библиотеку поддержки Android. В Eclipse вы щелкнете правой кнопкой мыши по проекту, перейдите в "Инструменты Android" и нажмите "Добавить поддержку...", чтобы загрузить и добавить его.
final static int myID = 1234;
//The intent to launch when the user clicks the expanded notification
Intent intent = new Intent(this, SomeActivityToLaunch.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendIntent = PendingIntent.getActivity(this, 0, intent, 0);
if (Integer.parseInt(Build.VERSION.SDK) >= Build.VERSION_CODES.DONUT) {
// Build.VERSION.SDK_INT requires API 4 and would cause issues below API 4
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
builder.setTicker("TICKER").setContentTitle("TITLE").setContentText("CONTENT")
.setWhen(System.currentTimeMillis()).setAutoCancel(false)
.setOngoing(true).setPriority(Notification.PRIORITY_HIGH)
.setContentIntent(pendIntent);
Notification notification = builder.build();
} else {
Notification notice = new Notification(R.drawable.icon_image, "Ticker text", System.currentTimeMillis());
notice.setLatestEventInfo(this, "Title text", "Content text", pendIntent);
}
notification.flags |= Notification.FLAG_NO_CLEAR;
startForeground(myID, notification);
Поместите код в метод запуска, который вы используете для своей службы, а затем, когда вы хотите остановить процесс переднего плана, вызовите stopForeground(true);
где угодно в вашей службе
Ответ 3
http://developer.android.com/reference/android/app/Service.html#startForeground%28int,%20android.app.Notification%29
Ответ 4
Я не совсем уверен, что это то, что вы ищете, но все, что вам нужно сделать, это создать объект уведомления (mOngoingNote
ниже) и вызвать startForeground
с помощью идентификатора уведомления вместе с фактическим уведомлением.
startForeground(NOTEMAN_ID, mOngoingNote);