android - 如何在不对 Activity 类进行硬编码的情况下从服务库中的 Notification 启动主 Activity

标签 android

我在服务中使用以下代码打开 main/launcher Activity,代码工作正常,直到我将这个项目声明为库并创建了另外两个使用这个库的项目。

所以在服务的onStartCommand中写了这段代码。

 final Notification notification = new Notification(R.drawable.ic_launcher, null, 0);   

    String notifTitle = "Service";
    String notifMessage = "Running";

    final Intent notificationIntent = new Intent(this,   MainActivity.class);
    notificationIntent.putExtra("extra", "value");
    notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP
                            | Intent.FLAG_ACTIVITY_SINGLE_TOP);
    notificationIntent.setAction("android.intent.action.MAIN");
    notificationIntent.addCategory("android.intent.category.LAUNCHER");

    final PendingIntent contentIntent = PendingIntent
                            .getActivity(this, 0, notificationIntent,0);



    notification.setLatestEventInfo(this, notifTitle, notifMessage, contentIntent);     
    startForeground(17, notification);

MainActivity.class 是库的一部分,使用这个库的两个项目有他们的主要 Activity MainActivityA , MainActivityB 扩展库的 MainActivity 。

现在的问题是,当我单击服务通知时,MainActivityA 或 MainActivityB 应该会启动,但现在什么也没有发生,但以前当库本身就是一个项目时它会起作用

任何想法都会很感激,

谢谢,

最佳答案

有几种方法可以解决这个问题。

您可以在 list 中的 Activity 上声明 Intent Filter 并广播 Intent,但如果用户在其设备上安装了这两个版本,这可能会出现问题。 (支持库中有一个本地广播,您可以使用 docs )

我个人会使用 Android 的资源系统来动态加载类名。 Intents 赋予您设置 ComponentName 的能力,这与给它一个 Activity 类的硬编码引用是一样的。

Intent i = new Intent();
String mPackage = ctx.getPackageName();
String mClass = ctx.getResources().getString(R.string.notification_class_name);
i.setComponent(new ComponentName(mPackage,mPackage+mClass));

库项目的值可以被使用它们的项目覆盖,因此在这两个项目中,您在 strings.xml 中都有一个值对应于该应用程序的通知 Activity 。

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <string name="notification_class_name">.MainActivityA</string>
</resources>

然后您可以将此 Intent 与您的 pendingIntent 一起使用,它将打开当前应用程序内的 Activity 。

关于android - 如何在不对 Activity 类进行硬编码的情况下从服务库中的 Notification 启动主 Activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13557654/

相关文章:

java - Android - 在相机中设置指南

android - 无法使用 picasso 库加载解析图像。 "imgUrl is cannot be resolved to a symbhol"

android - Eclipse 卡在 99% 启动到手机

android - 在android上保存多个图像文件的位置

android - 如何在 Android 中使用 Intent 播放视频?

android - 依赖项、模块的问题。如何正确引用该库?

android - 我应该为 Android 应用程序使用哪个 Eclipse 版本?

安卓布局问题。缺少三点菜单按钮

android - 将数据附加到android中的url

android - 在 Android 中发送包含哈希 # 符号的 ACTION_CALL Intent