gpt4 book ai didi

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

转载 作者:可可西里 更新时间:2023-11-01 19:10:11 26 4
gpt4 key购买 nike

我知道您可以使用 PendingIntents 从操作按钮启动 Activity 。如何做到在用户单击通知操作按钮时调用 a 方法?

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!");
}

最佳答案

单击操作按钮时不能直接调用方法。

您必须将 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(){

}

}

在 list 中声明广播接收器

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

希望对您有所帮助。

关于Android - 从通知操作按钮调用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41312669/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com