Android Widget Click y Broadcast Receiver no funciona
El siguiente código debe describir una aplicación en la que una vez que se hace clic en el botón widget, envía una intención que debe ser recibida por TestReceiver. Sin embargo, al ejecutar mi código inferior, el onReceive de TestReceiver nunca se llama.
¿Podría alguien decirme qué estoy haciendo mal?
- BOOT_COMPLETED no funciona en Android
- Recuperar el código de solicitud de la emisión de radio de alarma
- servicio androide para realizar un seguimiento de las llamadas salientes y SMS en segundo plano
- Android - ¿Cómo obtener una lista de todos los filtros de intención disponibles?
- Incorrecto timestamp en las notificaciones futuras
Código de widget
public class Widget extends AppWidgetProvider { public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { final int N = appWidgetIds.length; // Perform this loop procedure for each App Widget that belongs to this provider for (int i=0; i<N; i++) { int appWidgetId = appWidgetIds[i]; // Create an Intent to launch ExampleActivity //Intent intent = new Intent(context.getApplicationContext(), TestReceiver.class); Intent intent = new Intent(); intent.setAction(TestReceiver.TEST_INTENT); intent.setClassName(TestReceiver.class.getPackage().getName(), TestReceiver.class.getName()); PendingIntent pendingIntent = PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); // Get the layout for the App Widget and attach an on-click listener to the button RemoteViews views; views = new RemoteViews(context.getPackageName(), R.layout.main); views.setOnClickPendingIntent(R.id.btnTest, pendingIntent); // Tell the AppWidgetManager to perform an update on the current App Widget appWidgetManager.updateAppWidget(appWidgetId, views); } }
}
Código del receptor:
public class TestReceiver extends BroadcastReceiver { public static final String TEST_INTENT= "MyTestIntent"; @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub Toast.makeText(context, "Test", Toast.LENGTH_SHORT); if(intent.getAction()==TEST_INTENT) { System.out.println("GOT THE INTENT"); Toast.makeText(context, "Test", Toast.LENGTH_SHORT); } } }
Manifiesto:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.test.intenttest" android:versionCode="1" android:versionName="1.0"> <application android:icon="@drawable/icon" android:label="@string/app_name"> <receiver android:name=".TestReceiver" android:label="@string/app_name"> <intent-filter> <action android:name="MyTestIntent"> </action> </intent-filter> </receiver> <receiver android:label="@string/app_name" android:name="Widget"> <intent-filter> <action android:name="android.appwidget.action.APPWIDGET_UPDATE" /> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/widget" /> </receiver> </application> <uses-sdk android:minSdkVersion="3" /> </manifest>
- Difusión en contacto agregar / cambiar?
- Android: ¿Debo usar BroadcastReceiver vs Messenger vs BindService vs Handler
- ¿Es posible registrar un receptor en un caso de prueba?
- ¿Cómo suprimir la notificación push se muestra cuando la aplicación se está ejecutando?
- Repetir alarmas cada lunes en Android usig AlarmManager / BroadcastReceiver
- Android IntentService no puede instanciar clase; Sin constructor vacío
- Cómo anular el registro de escuchas y detener el servicio desde dentro de broadcastreceiver
- Inesperado resultados diferentes de la misma entrada de cadena
Probablemente funcione, pero te .show()
añadir .show()
al final de tu Toast 🙂
== pruebas de igualdad de referencia (si son el mismo objeto).
.equals () prueba la igualdad de valor (si son lógicamente "iguales").
Los valores de cadena se comparan usando '==' no 'iguales'
Esto " if(intent.getAction()==TEST_INTENT)
" cambia esto " if(intent.getAction().equals(TEST_INTENT))
"
Y por supuesto Toast.makeText(context, "Test", Toast.LENGTH_SHORT).show();
Todo el código:
package *********; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class TestReceiver extends BroadcastReceiver { public static final String TEST_INTENT= "MyTestIntent"; @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub Toast.makeText(context, "Test holaaa", Toast.LENGTH_SHORT).show(); if(intent.getAction() == TEST_INTENT) // if(intent.getAction().equals(TEST_INTENT)) { System.out.println("GOT THE INTENT"); Toast.makeText(context, "Test Goooo", Toast.LENGTH_SHORT).show(); } } }
- YouTubePlayerFragment no se puede transmitir a android.support.v4.app.Fragment
- Los datos no se insertan en la base de datos Sqlite en android