Dos botones de widgets de Android que llaman a la misma actividad con diferentes intenciones

Tengo un homescreenwidget en Android con dos botones. Ambos botones deben llamar a la misma actividad (clase), simplemente utilice una intención diferente, además de los extras de intención, para saber qué botón llamó a la clase. Por ahora sólo button1 está trabajando y llamando a la actividad. También recibo el valor clave en la actividad llamada.

¿Cómo puedo hacer que el segundo botón funcione? Aquí está mi código:

public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { super.onUpdate(context, appWidgetManager, appWidgetIds); for ( int i =0; i<appWidgetIds.length ; i++){ int appWidgetId = appWidgetIds[i]; Intent intent2 = new Intent(context, Main.class); Intent intent1 = new Intent(context, Main.class); // Intent put extras Button 1 String bread1 = "secure"; Bundle basket1 = new Bundle(); basket1.putString("key", bread1); intent1.putExtras(basket1); // Intent put extras Button 2 String bread2 = "insecure"; Bundle basket2 = new Bundle(); basket2.putString("key", bread2); intent2.putExtras(basket2); PendingIntent pending1 = PendingIntent.getActivity(context,0,intent1, 0); PendingIntent pending2 = PendingIntent.getActivity(context, 0, intent2, 0); RemoteViews views1 = new RemoteViews(context.getPackageName(),R.layout.maina); RemoteViews views2 = new RemoteViews(context.getPackageName(),R.layout.maina); views1.setOnClickPendingIntent(R.id.button1, pending1); views2.setOnClickPendingIntent(R.id.button2, pending2); appWidgetManager.updateAppWidget(appWidgetId, views1); appWidgetManager.updateAppWidget(appWidgetId, views2); 

Aquí está el maina.xml

  <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:weightSum="1" android:orientation="vertical"> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" android:id="@+id/tvWidget" android:textAppearance="?android:attr/textAppearanceLarge"></TextView> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="fill_parent" android:weightSum="1" android:orientation="horizontal"> <Button android:text="@string/button1" android:id="@+id/button1" android:layout_height="wrap_content" android:layout_width="wrap_content"></Button> <Button android:text="@string/button2" android:id="@+id/button2" android:layout_height="wrap_content" android:layout_width="wrap_content"></Button> </LinearLayout> </LinearLayout> 

@Arnold ha creado 2 PendingIntent que son ….

 PendingIntent pending1 = PendingIntent.getActivity(context,0,intent1, 0); PendingIntent pending2 = PendingIntent.getActivity(context, 0, intent2, 0); 

Donde PendingIntent.getActivity (Contexto contexto, int requestCode, Intención intención, banderas int) tiene 4 parámetros. Tienes que enviar diferentes " requestCode " para diferentes PendingIntents.

Su código debe ser ….

 PendingIntent pending1 = PendingIntent.getActivity(context,0,intent1, PendingIntent.FLAG_UPDATE_CURRENT); PendingIntent pending2 = PendingIntent.getActivity(context, 1, intent2, PendingIntent.FLAG_UPDATE_CURRENT); 

En la clase principal que necesita para crear este …

 String value; @Override public void onReceive(Context context, Intent intent) { // TODO Auto-generated method stub Bundle b=intent.getExtras(); try{ value=b.getString("key"); } catch (Exception e) { // TODO: handle exception } super.onReceive(context, intent); } 

Con el código onUpdate ….

  @Override public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) { // Get all ids ComponentName thisWidget = new ComponentName(context, main.class); int[] allWidgetIds = appWidgetManager.getAppWidgetIds(thisWidget); for (int widgetId : allWidgetIds) { // Create some random data RemoteViews remoteViews = new RemoteViews(context.getPackageName(), R.layout.main); // Register an onClickListener for 1st button Intent intent = new Intent(context, main.class); intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,allWidgetIds); intent.putExtra("key", "1st Button"); PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); remoteViews.setOnClickPendingIntent(R.id.button1, pendingIntent); // Register an onClickListener for 2nd button............ Intent intent2 = new Intent(context, main.class); intent2.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE); intent2.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS,allWidgetIds); intent2.putExtra("key", "2nd Button"); PendingIntent pendingIntent2 = PendingIntent.getBroadcast(context, 1, intent2, PendingIntent.FLAG_UPDATE_CURRENT); remoteViews.setOnClickPendingIntent(R.id.button2, pendingIntent2); appWidgetManager.updateAppWidget(widgetId, remoteViews); } } 

A continuación, puede comprobar si el valor = 1 º botón o valor = 2 º botón para saber qué botón se ha hecho clic. Debe funcionar … SI no funciona por favor avíseme cuál es el problema …

Tuve un problema similar con el uso de 2 botones en un widget. He establecido OnClickPendingIntents en ambos, distinguido por diferentes setExtra () las llamadas. Pero sólo se llamó la última intención, incluso cuando se hace clic en el primer botón. He encontrado 2 soluciones: – asignar diferentes acciones a ambos PendingIntents – en el segundo PendingEvent establecer el PendingEvent.FLAG_CANCEL_CURRENT flag

Estoy muy poco familiarizado con PendingEvents y Widgets, por lo que no puedo ver los pros y los contras y se adhieren a la primera solución.

Tal vez eso podría ayudarle con su problema, también.

En mi caso:

 remoteViews.setOnClickPendingIntent(R.id.widget_head, touch_man(context)); 

RemoteViews.setOnClickPendingIntent (R.id.widget_head2, touch_woman (contexto));

 public static PendingIntent touch_man(Context context) { Intent intent = new Intent(); intent.setAction("touch_man"); return PendingIntent.getBroadcast(context, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT); } public static PendingIntent touch_woman(Context context) { Intent intent = new Intent(); intent.setAction("touch_woman"); return PendingIntent.getBroadcast(context, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT); } 

En AndroidManifest

 <receiver android:name="Receiver" android:label="widgetBroadcastReceiver" > <intent-filter> <action android:name="touch_man" /> <action android:name="touch_woman"/> </intent-filter> <meta-data android:name="android.appwidget.provider" android:resource="@xml/demo_widget_provider" /> </receiver> 

Esta funcionando.

Su widget solo tendrá una vista remota. Intente cambiar el final de su fragmento de código a:

 RemoteViews remoteView = new RemoteViews(context.getPackageName(),R.layout.maina); remoteView.setOnClickPendingIntent(R.id.button1, pending1); remoteView.setOnClickPendingIntent(R.id.button2, pending2); appWidgetManager.updateAppWidget(appWidgetId, remoteView); 

De no ser así, sería útil ver su diseño en R.layout.maina .

  • Cómo configurar los radios de esquina para el botón en código java?
  • Restaurar el estado del widget de vista de búsqueda de android
  • Android: My App Widget con ListView no se actualiza a través del botón o período de actualización
  • ¿Cuál es la forma correcta de implementar un widget de Android con contenido dibujado dinámicamente?
  • Cómo ocultar la barra inferior del sistema en la tableta android
  • Valor de entrada de entrada del cuadro de diálogo de entrada de Android
  • Error XML en Eclipse mientras se visualiza el diseño gráfico de Xml
  • Teclado Android Entrar / Siguiente Button handler
  • Cómo implementar un ListView con fastscroll y albhabet indexador
  • Android: ¿Cómo cambiar el tamaño del texto en un campo EditarTexto?
  • ¿Cómo puedo calcular la velocidad de fotogramas de desplazamiento?
  • FlipAndroid es un fan de Google para Android, Todo sobre Android Phones, Android Wear, Android Dev y Aplicaciones para Android Aplicaciones.