Android - 从通知操作按钮调用方法

34

我知道你可以使用PendingIntents从操作按钮启动Activity。如何使得当用户点击通知操作按钮时调用某个方法?

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!");
}
1个回答

67

当您单击操作按钮时,您无法直接调用方法。

您必须使用PendingIntent与BroadcastReceiver或Service来执行此操作。这是使用BroadcastReciever的PendingIntent示例。

首先让我们构建一个通知

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);
    ...

}

现在将接收此Intent的接收器

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(){

    }

}

在清单文件中声明广播接收器

<receiver android:name=".ActionReceiver" />
希望它有所帮助。

谢谢,这很有道理。然而,我有点困惑为什么你把 intentAction 传递给了 addAction。难道不应该是 pIntentlogin 吗? - Faizan Syed
更新了。我的错! :) - Prince Bansal
11
这应该是关于Android开发者指南的教程。 - Prime624
我如何从广播接收器访问createNotif方法的this对象? - Donald Duck
大多数情况下,您将使用firebaseExtender,它将具有getBaseContext() @DonaldDuck。 - Nandha Kumar
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接