Iniciar la actividad del servicio cuando se hace clic en la notificación
Lo sé, hay toneladas de estos aquí, pero he estado intentando soluciones todo el día y no he llegado a ninguna parte. Ni el ejemplo en los documentos de google, ni ninguna de las otras 5 maneras que he encontrado aquí han funcionado para mí en absoluto. Como es el caso típico, cuando hago clic en la notificación, cierra la barra de estado y no aparece nada nuevo en pantalla. Estoy creando la notificación de un servicio y necesito la notificación para activar una nueva actividad que aún no se ha creado. También necesitaré una manera de pasar la información a esa actividad a través de la intención.
Y sí … esto es java para Android
- Java.lang.NoSuchMethodError: android.app.Notification $ Builder.build
- ¿Cómo resulta un resultado de servicio a una actividad
- Desplazamiento del texto del cuerpo en la notificación de Android
- Abrir diálogo desde la notificación
- Inicie correctamente la Actividad de la Notificación independientemente del estado de la aplicación
Lo que sigue son los restos rotos de mi código.
package com.bobbb.hwk2; import java.io.FileOutputStream; import android.app.Notification; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.database.Cursor; import android.net.Uri; import android.os.IBinder; import android.provider.ContactsContract; import android.widget.Toast; public class contactBackup extends Service { private NotificationManager nManager; private static final int NOTIFY_ID = 1100; @Override public void onCreate() { super.onCreate(); String ns = Context.NOTIFICATION_SERVICE; nManager = (NotificationManager)getSystemService(ns); } @Override public void onStart(Intent intent, int startId) { super.onStart(intent, startId); // inform user that service has started Toast.makeText(getApplicationContext(), R.string.service_started,Toast.LENGTH_LONG).show(); String data = lookUpContacts(); if( saveToSDCard(getResources().getString(R.string.backup_file_name),data) ) { Context context = getApplicationContext(); // create the statusbar notification Intent nIntent = new Intent(this,contactViewer.class);//Intent nIntent = new Intent(Intent.ACTION_MAIN); nIntent.setClass(context,contactViewer.class); //nIntent.putExtra("data",data); Notification msg = new Notification(R.drawable.icon,"All contacts records have been written to the file.",System.currentTimeMillis()); // start notification //PendingIntent pIntent = PendingIntent.getService(getApplicationContext(),0,nIntent,PendingIntent.FLAG_UPDATE_CURRENT|Intent.FLAG_FROM_BACKGROUND); PendingIntent pIntent = PendingIntent.getActivity(this,0,nIntent,0); msg.flags = Notification.FLAG_AUTO_CANCEL; msg.setLatestEventInfo(context, "success", "All contacts records have been written to the file.", pIntent); nManager.notify(NOTIFY_ID,msg); } } @Override public void onDestroy() { nManager.cancel(NOTIFY_ID); super.onDestroy(); } @Override public IBinder onBind(Intent intent) { return null; } // function returns string containing information // from contacts public String lookUpContacts() { ... } public boolean saveToSDCard(String fileName, String data) { ... } }
Sólo puedo esperar que lo que está causando mi problema es algo fijable y no más de los problemas locos que he estado recibiendo con eclipse (que nadie más parece haber visto nunca>: U)
Si usted puede ayudarme a resolver este problema, por favor comparta. Si no puede ayudar con este problema específico, pero se siente obligado a decir cosas no relacionadas sobre la publicación, estilos, temas o buenas prácticas, entonces NO
Gracias: D
- Crear notificación cronometrada (por ejemplo, para eventos) en Android
- Actualización de la barra de progreso de la descarga en el área de notificación de AsynTask
- ¿Cuál es la diferencia entre: notification.flags y notification.defaults?
- Quitar u ocultar la barra de notificaciones en android
- Icono que no se muestra en la notificación: se muestra un cuadrado blanco en su lugar
- Android: recibe todas las notificaciones por código
- Android: Iniciar el primer plano no mostrará la notificación correctamente
- Uid ... no tiene android.permission.UPDATE_APP_OPS_STATS
Editar:
Vas a tener que añadir una bandera para FLAG_ACTIVITY_NEW_TASK:
nIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Esto se debe a que se está iniciando desde fuera de la aplicación (desde la barra de notificación del sistema).
Esto es lo que sucede cuando la gente se fatiga. XD La única razón por la que ninguno de los tutoriales que cansé funcionó es porque escribí mal mi nombre de actividad en el manifiesto. Gracias por pasar
Simplemente agregue el siguiente en contactBackup (clase de servicio),
Intent nIntent = new Intent(this,contactViewer.class);//Intent nIntent = new Intent(Intent.ACTION_MAIN); nIntent.setClass(context,contactViewer.class); nIntent.putExtra("data",data); nIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); Notification msg = new Notification(R.drawable.icon,"All contacts records have been written to the file.",System.currentTimeMillis()); // start notification //PendingIntent pIntent = PendingIntent.getService(getApplicationContext(),0,nIntent,PendingIntent.FLAG_UPDATE_CURRENT|Intent.FLAG_FROM_BACKGROUND); PendingIntent pIntent = PendingIntent.getActivity(this,0,nIntent,0); msg.flags = Notification.FLAG_AUTO_CANCEL; msg.setLatestEventInfo(context, "success", "All contacts records have been written to the file.", pIntent); nManager.notify(NOTIFY_ID,msg);
Entonces obtener valor en la clase contactViewer,
como,
String s=getIntent().getStringExtra("data");