繁体   English   中英

没有启动新活动的通知操作?

[英]Notification Action without starting new Activity?

我计划有一个包含两个操作的提示通知:一个用于批准登录请求,另一个用于拒绝登录请求。 通过单击这些操作中的任何一个,我希望向我的服务器发出 HTTP 请求,最重要的是不想启动新的 Activity 或根本不想让用户重定向到我的应用程序。

        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 不会导致新活动被触发的示例。

我将如何实现一些代码(可能是一种方法)而不是在我的每个操作上启动一个新的活动?

如果您不想启动 Activity,您还可以将BroadcastReceiverService直接包装在PendingIntent

无论您在哪里构建通知...

您的通知操作将直接启动服务。

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.

我的服务

IntentServices 一个接一个地连续运行。 他们在工作线程上完成工作。

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

不要忘记在清单中注册服务。

<manifest>
  <application>
    <service
        android:name="path.to.MyService"
        android:exported="false"/>
  </application>
</manifest>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM