4

我知道您可以使用PendingIntents從操作按鈕啓動活動。你如何做到這一點,以便當用戶點擊通知操作按鈕時調用方法?Android - 來自通知操作的調用方法按鈕

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

回答

8

當您單擊操作按鈕時,不能直接調用方法。

您必須使用PendingIntent與BroadcastReceiver或Service來執行此操作。這是一個PendingIntent與BroadcastReciever的例子。

首先讓構建通知

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

} 

現在將接收這個意圖

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"></receiver> 
接收機

希望它有幫助。

+0

謝謝,這很有道理。不過,我對你爲什麼將'intentAction'傳遞給'addAction'有點困惑。它會是'pIntentlogin'嗎? –

+0

已更新。我的錯! :) –

+0

非常感謝你! –