gpt4 book ai didi

java - 从 Activity 的 java 类 npt 调用 Android 通知

转载 作者:行者123 更新时间:2023-11-30 02:15:32 24 4
gpt4 key购买 nike

如何从 Java 类开始通知?我从一个 Activity 开始通知但是当我尝试从 java 类中执行它时它不起作用,因为它需要一个上下文(这指的是我的类上下文)这是我的函数代码,它从 Activity 开始通知:

 public  void sendNotification(){
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_camera)
.setContentTitle("Someone on your door")
.setContentText("Open the camera to see!");

// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, CameraActivity.class);

// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(CameraActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(CAMERA_NOTIFICATION, mBuilder.build());

}

预先感谢您的帮助

最佳答案

为您的 java 类创建一个参数化的构造函数,将 Context 作为参数并从您的 Activity 中调用它。你如何从 Activity 中调用你的 java 类。您可能通过使其对象 n 调用默认构造函数来调用您的 java 类,我猜是这样的:

错误的方式

JavaClass obj = new JavaClass();

正确的方式

`JavaClass obj = new JavaClass(MainActivity.this); // MainActivity.this is` context

关于java - 从 Activity 的 java 类 npt 调用 Android 通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29430288/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com