gpt4 book ai didi

android - 对通知点击执行操作

转载 作者:行者123 更新时间:2023-11-29 00:08:12 24 4
gpt4 key购买 nike

我有一个在服务中使用持久通知并在后台运行的应用程序。当此服务正在运行时,我需要能够在单击通知时调用方法/执行某些操作。但是,我不确定如何实现它。 我通读了许多类似的问题/答案,但没有一个回答清楚或适合我的目的。 This SO 问题接近我想要实现的目标,但选择的答案很难理解。

我的服务/通知是在我的 BackgroundService 类的 onCreate() 方法中启动的...

Notification notification = new Notification();
startForeground(1, notification);
registerReceiver(receiver, filter);

这个服务是从我的主要 Activity 的按钮点击启动的:

final Intent service = new Intent(Main.this, BackgroundService.class);

bStart.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

if((counter % 2) == 0){

bStart.setText("STOP");
startService(service);

}else {
bStart.setText("BEGIN");
stopService(service);
}

counter++;

}

感谢任何建议

最佳答案

您必须为此使用 BroadcastReceiver。看看下面的代码。将其放入您的 Service

private MyBroadcastReceiver mBroadcastReceiver;
@Override
onCreate() {
super.onCreate();
mBroadcastReceiver = new MyBroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addCategory(Intent.CATEGORY_DEFAULT);
// set the custom action
intentFilter.addAction("do_something");

registerReceiver(mBroadcastReceiver, intentFilter);
}



// While making notification
Intent i = new Intent("do_something");
PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, i, 0);
notification.contentIntent = pendingIntent;




public class MyBroadcastReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
switch(action) {
case "do_something":
doSomething();
break;
}
}
}

public void doSomething() {
//Whatever you wanna do on notification click
}

这样,当您的 Notification 被点击时,doSomething() 方法将被调用。

关于android - 对通知点击执行操作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32257067/

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