gpt4 book ai didi

android - 如何在 Notification Click 上调用非 Activity 方法

转载 作者:塔克拉玛干 更新时间:2023-11-03 00:45:15 25 4
gpt4 key购买 nike

我有一个 java 类 MyClass,它包含一个名为 callMethod 的方法。我想在用户点击通知时调用这个方法

下面是我用来生成通知的代码

public class MainActivity extends AppCompatActivity {

Button button;
NotificationManager mNotifyMgr;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
mNotifyMgr = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, new Intent(MainActivity.this, MyClass.class), PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification =
new NotificationCompat.Builder(MainActivity.this)
.setContentTitle("Notification")
.setSmallIcon(R.drawable.ic_launcher)
.setContentText("Downloaded")
.setContentIntent(pendingIntent)
.build();

mNotifyMgr.notify(1,notification);
}
});
}
}

下面是MyClass的实现

public class MyClass {
public void callMethod(){
System.out.println("Notification clicked");
}
}

请帮忙,我现在陷入这个问题有一段时间了

最佳答案

你可以这样做:

在创建 PendingIntent 以放入 Notification 时:

Intent notificationIntent = new Intent(MainActivity.this, MyClass.class);
notificationIntent.putExtra("fromNotification", true);
PendingIntent pendingIntent = PendingIntent.getActivity(MainActivity.this, 0, notificationIntent,
PendingIntent.FLAG_UPDATE_CURRENT);

现在,在 MyClass.onCreate() 中:

if (getIntent().hasExtra("fromNotification")) {
callMethod();
}

关于android - 如何在 Notification Click 上调用非 Activity 方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39996870/

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