安卓:我如何注册未运行的应用程序,以服务?应用程序

2023-09-08 08:34:21 作者:美人迟暮

背景:Android提供了备份数据的一个很好的方法。有备份应用程序的数据每当执行一个全系统的备份,应用程序应该有一个备份代理指定为它的一个属性的应用程序代码,在应用中体现。

Background: Android provides a nice method of backing up data. To have the data of an application backed up whenever a system-wide backup is performed, an application should have a backup agent specified as an attribute of it's application tag, in the applications manifest.

<application android:label="MyApplication"
         android:backupAgent="MyBackupAgent">

问:我想用类似的机制的文件检索服务,我创造。我的问题是,一个人如何编程扫描在他们的应用程序标记指定属性的应用程序,并启动与该属性关联的对象?这可能吗?

Question: I would like to use a similar mechanism for a file retrieval service I am creating. My question is, how does one programatically scan for applications with a given attribute in their application tag, and launch the object associated with that attribute? Is this possible?

请注意,该目标应用程序可以不必运行

Note that the target application may not necessarily be running.

推荐答案

我想通了这一点。寻找到Android源后,我看到它是不可能的发放标准标签的属性。相反,元数据可以用于实现类似的结果。

I figured this out. After looking into the Android source I see that it is not possible to extend the attributes of standard tags. Instead, meta-data can be used to achieve a similar result.

我设计的解决方案是,包括在,我想用我的服务注册应用程序的元数据标记。例如:

The solution I devised was to include a meta-data tag in applications that I want 'registered' with my service. For example:

的Andr​​oidManifest.xml(目标应用程序(多个))

AndroidManifest.xml (of target application(s))

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >

    <meta-data android:name="MyAttribute" android:value="myvalue" />

我公司开发的服务扫描已安装的软件包,以发现那些相关的元数据:

The service I developed scans the installed packages to find those with the relevant meta-data:

List<PackageInfo> packages = getPackageManager().getInstalledPackages(PackageManager.GET_META_DATA);
for (int a = packages.size();-1; a >= 0; a--) { 
    PackageInfo pkg = packages.get(a);       
    ApplicationInfo ai = packages.get(a).pkg.applicationInfo;
    boolean remove = true;
    if (ai.metaData != null && ai.metaData.get("LogRetrievalAgent") != null) {
    remove = ai.metaData.get("LogRetrievalAgent").toString().compareTo("test") != 0;
    }

    if (remove) {
        packages.remove(pkg);
    }
}