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

前端之家收集整理的这篇文章主要介绍了Android – 从通知操作按钮调用方法前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我知道您可以使用PendingIntents从操作按钮启动活动.如何在用户单击通知操作按钮时调用方法
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,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(){

    }

}

在Manifest中声明广播接收器

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

希望能帮助到你.

原文链接:https://www.f2er.com/android/317367.html

猜你在找的Android相关文章