我在通知中添加了一个按钮
但是我不知道如何在点击按钮时调用函数。
我尝试了这样的方法https://code.google.com/p/languagepickerwidget/source/browse/trunk/trunk/src/org/gnvo/langpicker/LangPicker.java,因为它也使用RemoteViews对象,但是当我点击按钮时什么也没发生。
这就是我目前拥有的:
private void createNotification(){
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager notificationManager = (NotificationManager) getSystemService(ns);
Notification notification = new Notification(R.drawable.ic_launcher, null, System.currentTimeMillis());
RemoteViews notificationView = new RemoteViews(getPackageName(), R.layout.notification_switch);
//the intent that is started when the notification is clicked (works)
Intent notificationIntent = new Intent(this, SettingsActivity.class);
PendingIntent pendingNotificationIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.contentView = notificationView;
notification.contentIntent = pendingNotificationIntent;
notification.flags |= Notification.FLAG_NO_CLEAR;
//this is the intent that is supposed to be called when the button is clicked
Intent switchIntent = new Intent(this, switchButtonListener.class);
PendingIntent pendingSwitchIntent = PendingIntent.getBroadcast(this, 0, switchIntent, 0);
notificationView.setOnClickPendingIntent(R.id.buttonswitch, pendingSwitchIntent);
notificationManager.notify(1, notification);
}
public static class switchButtonListener extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Log.d("TAG", "test");
}
}
我可以使用按钮启动一个 Activity,但我没有成功调用一个简单的函数。最好的方法是什么?
编辑: 我发现我需要在 AndroidManifest.xml 中注册 "switchButtonListener"。
<receiver android:name="SettingsActivity$switchButtonListener" />
来源:Android Activity with no GUI
现在它可以工作了。