Implementar método startForeground en Android

Quiero implementar el método startForeground() en la clase de Service para evitar la matanza de servicio.

¿Alguien me ha enviado código para implementar este método?

Jovan, aquí hay un método para hacer código compatible para 2.0 + y 1.6- (el código muestra cómo detectar cuál es compatible) http://android-developers.blogspot.com/2010/02/service-api-changes -empezando-con.html

Para 2.0 +, he reunido algunos ejemplos de código (utilizando startForeground). Observe que algunos códigos están ahora obsoletos, sin embargo, Notification.Builder utiliza el nivel 11 (3.x) de la API, lo que significa que no lo utilizaré hasta que la mayoría de los teléfonos utilicen una versión de Android compatible. Dado que la gran mayoría de los teléfonos está ejecutando ahora una versión de 2.x, creo que es lo suficientemente seguro para omitir la comprobación de compatibilidad.

 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() este código dentro de onStartCommand() de su servicio y usted es bueno ir. (Pero podrías poner esta sección de código en cualquier parte de tu servicio.)

PS para detener el servicio de estar en primer plano simplemente use stopForeground(true); En cualquier lugar de su servicio

Este código utilizará la mejor opción disponible para cualquier API añadiendo la biblioteca de soporte de Android a su proyecto. En Eclipse, debería hacer clic con el botón derecho del ratón en el proyecto, ir a Herramientas de Android y hacer clic en la opción "Agregar biblioteca de soporte …" para descargarla y agregarla.

 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); 

Ponga el código en el método de inicio que está utilizando para su servicio, y luego cuando quiera que el proceso de primer plano se detenga, llame a stopForeground(true); En cualquier lugar de su servicio

No estoy exactamente seguro si esto es lo que estás buscando, pero todo lo que tienes que hacer es crear un objeto de notificación ( mOngoingNote adelante) y llamar a startForeground usando un ID de notificación junto con la notificación real.

  startForeground(NOTEMAN_ID, mOngoingNote); 
FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.