我有一个应用程序,它在服务中使用持久通知并在后台运行。在此服务运行时,我需要能够在单击通知时调用方法/执行某些操作。但是,我不确定如何实现这一点。我已经阅读了许多类似的问题/答案,但是没有一个答案明确或适合我的目的。 这个SO 问题接近我想要达到的目标,但选择的答案很难理解。
我的服务/通知在我的 BackgroundService 类的 onCreate() 方法中启动...
Notification notification = new Notification();
startForeground(1, notification);
registerReceiver(receiver, filter);
Run Code Online (Sandbox Code Playgroud)
这个服务是从我的主要活动的按钮点击启动的:
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++;
}
Run Code Online (Sandbox Code Playgroud)
任何建议表示赞赏
BroadcastReceiver为此,您必须使用 a 。看看下面的代码。把它放在你的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
}
Run Code Online (Sandbox Code Playgroud)
这样,doSomething()当您Notification单击时将调用该方法。
| 归档时间: |
|
| 查看次数: |
6170 次 |
| 最近记录: |