Handling buttons inside android notifications

前端 未结 1 609
失恋的感觉
失恋的感觉 2020-11-27 04:11

I added a button inside a notification

\"\"

but I don\'t know how to have it call a function when it\'

相关标签:
1条回答
  • 2020-11-27 05:05

    I found out that I had to register "switchButtonListener" in AndroidManifest.xml

    <receiver android:name="SettingsActivity$switchButtonListener" />
    

    Source: Android Activity with no GUI


    Later I found out that I can also use code like this to achieve the same thing without modifying the manifest.

    switchButtonListener = new SwitchButtonListener();
    registerReceiver(switchButtonListener, new IntentFilter(SWITCH_EVENT));
    

    .

    public class switchButtonListener extends BroadcastReceiver {
    @Override
        public void onReceive(Context context, Intent intent) {
            Log.d("TAG", "test");
        }
    
    }
    

    .

    Intent switchIntent = new Intent(LangService.SWITCH_EVENT);
    PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(context, 0, switchIntent, 0);
    
    notificationView.setOnClickPendingIntent(R.id.buttonswitch, pendingSwitchIntent);
    


    Note that this way I can declare the switchButtonListener class without the static attribute (if not static, it would crash in the previous example) giving me much more flexibility.
    Don't forget to call unregisterReceiver() later.

    0 讨论(0)
提交回复
热议问题