2012-09-11 20 views
7

Quiero disparar el receptor de difusión desde la notificación. Cuando hago clic en un botón que se encuentra en la notificación que muestra este error:cómo disparar el receptor de difusión desde la notificación

"Unable to instantiate receiver com.example.testservice.myBroad: java.lang.ClassCastException: com.example.testservice.myBroad cannot be cast to android.content.BroadcastReceiver"

* informado/editado y su trabajo ahora * 1) Hola chicos pueden ayudar por favor para manejar 2 botones de notificación para transmitir reciver ¿Cómo puedo pasar un valor extra del disparador de transmisión de notificación al receptor que, si se presionó o pauso su botón de reproducción? 2) ahora mi botón funciona pero cuando hago clic en el texto de notificación no me lleva a mi actividad. cualquier ayuda

que escribir el código de 2 botón con la intención adicional en

RemoteViews layout = new RemoteViews(getPackageName(), R.layout.notification); 
      layout.setTextViewText(R.id.notification_title, getString(R.string.app_name)); 
      Intent clickIntent = new Intent(); 
      clickIntent.putExtra("button","pause"); 
      clickIntent.setAction(ACTION_DIALOG); 

      PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), pendingRequestCode, clickIntent, pendingFlag); 
      layout.setOnClickPendingIntent(R.id.notification_button,pendingIntent); 
      builder.setContent(layout); 


      layout = new RemoteViews(getPackageName(), R.layout.notification); 
      layout.setTextViewText(R.id.notification_title, getString(R.string.app_name)); 
      Intent click = new Intent(); 
      clickIntent.putExtra("Button","play"); 
      clickIntent.setAction(ACTION_DIALOG); 

      PendingIntent pi1 = PendingIntent.getBroadcast(getApplicationContext(), pendingRequestCode, click, pendingFlag); 
      layout.setOnClickPendingIntent(R.id.notification_button1,pi1); 
      builder.setContent(layout); 

archivo receptor myBroad

Bundle extrasBundle = intent.getExtras(); 
    String str = (String) extrasBundle.get("button");  
    Toast.makeText(context, str, Toast.LENGTH_SHORT).show(); 

    context.stopService(new Intent(context, myPlayService.class)); 

Aquí está mi código:

void showNotification() { 
    int pendingRequestCode = 0; 
     int pendingFlag = 0; 

     final Resources res = getResources(); 
     final NotificationManager notificationManager = (NotificationManager) getSystemService(
       NOTIFICATION_SERVICE); 
     Intent intent = new Intent(MainActivity.this,myBroad.class); 
     PendingIntent pi= PendingIntent.getActivity(this, 0, intent, 0); 
     Notification.Builder builder = new Notification.Builder(this) 
       .setSmallIcon(R.drawable.ic_action_search) 
       .setAutoCancel(true) 
       .setTicker("this is notification") 
       .setContentIntent(getDialogPendingIntent("Tapped the notification entry.")); 


      // Sets a custom content view for the notification, including an image button. 
      RemoteViews layout = new RemoteViews(getPackageName(), R.layout.notification); 
      layout.setTextViewText(R.id.notification_title, getString(R.string.app_name)); 
      Intent clickIntent = new Intent(); 
      clickIntent.setAction(ACTION_DIALOG); 

      PendingIntent pendingIntent = PendingIntent.getBroadcast(getApplicationContext(), pendingRequestCode, clickIntent, pendingFlag); 
      layout.setOnClickPendingIntent(R.id.notification_button,pendingIntent); 
      builder.setContent(layout); 

      // Notifications in Android 3.0 now have a standard mechanism for displaying large 
      // bitmaps such as contact avatars. Here, we load an example image and resize it to the 
      // appropriate size for large bitmaps in notifications. 
      Bitmap largeIconTemp = BitmapFactory.decodeResource(res, 
        R.drawable.notification_default_largeicon); 
      Bitmap largeIcon = Bitmap.createScaledBitmap(
        largeIconTemp, 
        res.getDimensionPixelSize(android.R.dimen.notification_large_icon_width), 
        res.getDimensionPixelSize(android.R.dimen.notification_large_icon_height), 
        false); 
      largeIconTemp.recycle(); 

      builder.setLargeIcon(largeIcon); 

     notificationManager.notify(NOTIFICATION_DEFAULT, builder.getNotification()); 
} 


    PendingIntent getDialogPendingIntent(String dialogText) { 
     return PendingIntent.getActivity(
       this, 
       dialogText.hashCode(), // Otherwise previous PendingIntents with the same 
             // requestCode may be overwritten. 
       new Intent(ACTION_DIALOG) 
         .putExtra(Intent.EXTRA_TEXT, dialogText) 
         .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK), 
       0); 
    } 

myBroad.class

public class myBroad extends BroadcastReceiver{ 

@Override 
public void onReceive(Context context, Intent intent) { 
    // TODO Auto-generated method stub 
    Toast.makeText(context, "received", Toast.LENGTH_SHORT).show(); 

    context.stopService(new Intent(context, myPlayService.class)); 

} 

}

archivo de manifiesto es:

<application 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <activity 
     android:name=".MainActivity" 
     android:label="@string/title_activity_main" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 


      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
      </activity> 

    <receiver android:name=".myBroad"> 
     <intent-filter > 
<action android:name="android.intent.action.MEDIA_BUTTON"/> 
    </intent-filter> 

     </receiver> 

    <service android:name="com.example.testservice.myPlayService" android:icon="@drawable/ic_action_search" android:label="@string/app_name" android:enabled="true"/> 


</application> 

Respuesta

3

Debido myBroad es un objeto de actividad, y no un objeto de difusión ...

En lugar de extender (herencia) de la actividad, y luego crear una clase interna que amplíe el receptor de difusión, y luego heredar directamente del receptor de difusión.

+0

sus obras muchas gracias .. –

+0

puede ayudarle .. quiero hacer una pausa en la música del servicio cuando se presiona esta notificación button..can que me guía. ¿cómo puedo acceder al método de servicio cuando recibo el receptor de difusión –

0

La excepción lo dice claramente: su myBroad tiene que extender BroadcastReceiver, no Activity como lo hace ahora.

PD: debería considerar cambiar a la convención de nomenclatura adecuada. Por lo tanto, debe ser MyBroad (clase) pero myBroad (objeto de esa clase). es decir .:

MyBroad myBroad = new MyBroad(); 
+0

puedo ayudar ... quiero pausar la música del servicio cuando presiono este botón de notificación..pueden guiarme. ¿Cómo puedo acceder al método de servicio cuando recibo el receptor de difusión? –

+0

¿Cómo puedo reconocer en el receptor de difusión si el botón de pausa está presionado o el botón Reproducir? también cuando presioné el texto de notificación, no me puso en actividad.cualquier ayuda –

1

En el método de getDialogPendingIntent se debe utilizar en lugar de PendingIntent.getBroadcastPendingIntent.getActivity. Esto hará que su PendingIntent presione una transmisión .

Y solucionar este problema:

public class myBroad extends BroadcastReceiver

+0

sí, he usado getbroadcast para el botón –

+0

no funciona después de crear extender por broadcastreciver puede ayudar ... quiero pausar la música del servicio cuando presiono este botón de notificación..puede guiarme. ¿Cómo puedo acceder al método de servicio cuando recibo el receptor de difusión? –

+0

¿Cómo puedo reconocer en el receptor de difusión si está presionado el botón de pausa o el botón Reproducir? también cuando presioné el texto de notificación no me puso en actividad ... cualquier ayuda –

Cuestiones relacionadas