web-dev-qa-db-fra.com

Android - Méthodes d'appel à partir du bouton d'action de notification

Je sais que vous pouvez lancer des activités à partir des boutons d'action à l'aide de PendingIntents. Comment faire en sorte que la méthode a soit appelée lorsque l'utilisateur clique sur le bouton d'action de notification?

public static void createNotif(Context context){
    ...
    drivingNotifBldr = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.steeringwheel)
            .setContentTitle("NoTextZone")
            .setContentText("Driving mode it ON!")
            //Using this action button I would like to call logTest
            .addAction(R.drawable.smallmanwalking, "Turn OFF driving mode", null)
            .setOngoing(true);
    ...
}

public static void logTest(){
    Log.d("Action Button", "Action Button Worked!");
}
14
Faizan Syed

Vous ne pouvez pas appeler directement des méthodes lorsque vous cliquez sur des boutons d'action.

Vous devez utiliser PendingIntent avec BroadcastReceiver ou Service pour effectuer cette opération. Voici un exemple de PendingIntent avec BroadcastReciever.

permet d'abord de créer une notification

public static void createNotif(Context context){

    ...
    //This is the intent of PendingIntent
    Intent intentAction = new Intent(context,ActionReceiver.class);

    //This is optional if you have more than one buttons and want to differentiate between two
    intentAction.putExtra("action","actionName");

    pIntentlogin = PendingIntent.getBroadcast(context,1,intentAction,PendingIntent.FLAG_UPDATE_CURRENT);
    drivingNotifBldr = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.steeringwheel)
            .setContentTitle("NoTextZone")
            .setContentText("Driving mode it ON!")
            //Using this action button I would like to call logTest
            .addAction(R.drawable.smallmanwalking, "Turn OFF driving mode", pIntentlogin)
            .setOngoing(true);
    ...

}

Maintenant le récepteur qui recevra cette intention

public class ActionReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {

        //Toast.makeText(context,"recieved",Toast.LENGTH_SHORT).show();

        String action=intent.getStringExtra("action");
        if(action.equals("action1")){
            performAction1();
        }
        else if(action.equals("action2")){
            performAction2();

        }
        //This is used to close the notification tray
        Intent it = new Intent(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        context.sendBroadcast(it);
    }

    public void performAction1(){

    }

    public void performAction2(){

    }

}

Déclarez le récepteur de diffusion dans le manifeste

<receiver Android:name=".ActionReceiver" />

J'espère que cela aide.

33
Prince Bansal