java - 使用 PendingIntent 达到我的方法

标签 java android android-studio notifications

我有一个可以发出通知的 Android 应用程序。我可以毫无问题地生成通知和按钮。我的问题是按钮的操作。我希望按钮调用一个方法,例如文本打印方法。我正在使用 addAction(icon, "title",endingIntent)。

public void sendNotification(Context context) {

    NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);

    Intent intent = new Intent(context.getApplicationContext(), SomeClass.class);
    PendingIntent pendingIntent = PendingIntent.getActivity(context.getApplicationContext(), (int) System.currentTimeMillis(), intent, 0);

    NotificationCompat.Builder builder = (NotificationCompat.Builder) new NotificationCompat.Builder(context)
            .setSmallIcon(R.drawable.icon)
            // This creates the button and it is using a pending intent.
            .addAction(R.drawable.icon, "Print something", printPendingIntent)
            // Clicking on notification takes you back to the App.
            .setContentIntent(pendingIntent)
            .setAutoCancel(true)
            .setContentTitle("My Title")
            .setContentText("Some text");

    notificationManager.notify(NOTIFICATION_ID, builder.build());
}

所以问题出在 printPendingIntent 中,(如您所见,没有编写任何代码), 如何使用此待处理 Intent 访问/调用方法?

感谢您的回答,如果问题不够清晰和详细,我们深表歉意。

最佳答案

添加intent.putExtra("key","printmethod");然后使用 getIntent().getExtras("Key"); 接收 SomeClass 中的数据如果该值匹配,那么您可以在该 Activity 中调用所需的方法。

关于java - 使用 PendingIntent 达到我的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33039196/

相关文章:

javascript - 差异时区浏览器和 Java

android - 如何根据时间查看昼夜循环?

android - 带有操作栏但没有标题的 Activity ?

Android 模拟器控制按钮(返回、主页、任务)不起作用

android - 等待阻塞 GC ProfileSaver

java - 在Java中将字符串从蛇大小写转换为 Camel 大小写

java - 对于开发人员来说,GraalVM 19.3 的 CE 版本和 EE 版本有什么区别?

java.lang.ClassCastException : On custom composite component

android - Windows 上 Android Studio 的默认 SDK 位置在哪里?

java - Android Studio 通过不同的 Activity 计时