没有启动新活动的通知操作? [英] Notification Action without starting new Activity?
问题描述
我计划有一个包含两个操作的提示通知:一个是批准登录请求,一个是拒绝登录请求.通过单击这些操作中的任何一个,我希望向我的服务器发出 HTTP 请求,最重要的是,不想启动新的 Activity 或根本不想让用户重定向到我的应用.
I plan to have a heads up notification that has two Actions: one to Approve a login request and one to Decline a login request. By clicking on either of these actions I wish to fire off a HTTP request to my server and most importantly do not want to start a new Activity or have the user redirected to my app at all.
Context context = getBaseContext();
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.notificationicon)
.setContentTitle(notificationTitle)
.setContentText("Access Request for " + appName + " : " + otp)
.setDefaults(Notification.DEFAULT_ALL)
.setPriority(NotificationCompat.PRIORITY_HIGH)
.addAction(R.drawable.ic_tick, "Approve", someApproveIntent? );
这是我的通知生成器,环顾四周后,似乎 addAction 方法正在寻找一个新的/pendingIntent,这让我很困惑,因为我在网上找不到任何 Intent 不会导致新活动被触发的示例.
Here is my notification builder and after looking around it seems that the addAction method is looking for a new/pendingIntent, which is confusing me as I cannot find any examples online where Intents do not lead to new Activities being fired off.
我将如何实现一些代码(可能是一种方法)而不是在我的每个操作上启动一个新活动?
How would I implement some code (a method maybe) rather then starting a new Activity on each of my Actions?
推荐答案
如果你不想启动一个 Activity 你也可以封装一个 BroadcastReceiver
或者一个 Service
直接在 PendingIntent
中.
If you don't want to start an activity you can also wrap a BroadcastReceiver
or a Service
directly in a PendingIntent
.
您的通知操作将直接启动服务.
Your notification actions will start a service directly.
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)...
Intent iAction1 = new Intent(context, MyService.class);
iAction1.setAction(MyService.ACTION1);
PendingIntent piAction1 = PendingIntent.getService(context, 0, iAction1, PendingIntent.FLAG_UPDATE_CURRENT);
builder.addAction(iconAction1, titleAction1, piAction1);
// Similar for action 2.
MyService.java
IntentServices 一个接一个地运行.他们在工作线程上完成工作.
MyService.java
IntentServices run in a row one after another. They do the work on a worker thread.
public class MyService extends IntentService {
public static final String ACTION1 = "ACTION1";
public static final String ACTION2 = "ACTION2";
@Override
public void onHandleIntent(Intent intent) {
final String action = intent.getAction();
if (ACTION1.equals(action)) {
// do stuff...
} else if (ACTION2.equals(action)) {
// do some other stuff...
} else {
throw new IllegalArgumentException("Unsupported action: " + action);
}
}
}
AndroidManifest.xml
不要忘记在清单中注册服务.
AndroidManifest.xml
Don't forget to register the service in manifest.
<manifest>
<application>
<service
android:name="path.to.MyService"
android:exported="false"/>
</application>
</manifest>
这篇关于没有启动新活动的通知操作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!