2 Android应用程序之间共享SQLite数据库? [英] Share SQLite database between 2 android apps?

查看:306
本文介绍了2 Android应用程序之间共享SQLite数据库?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要2应用程序之间共享一个数据库。我知道,该数据库将在/数据/数据​​/ MY_PACKAGE /数据库中创建/。由于包名不同是它可以定义的路径,一包的名字,当我创建的任何应用程序的数据库? 谢谢。

I need to share a single database between 2 apps. I know that the database will be created on /data/data/MY_PACKAGE/databases/ . Since the packages names are different is it possible to define the path to one package name when I create the database on either app? Thanks.

推荐答案

您当然可以共享一个2应用程序之间的数据库。

You certainly can share a single database between 2 apps.

为了共享应用程序之间的数据(只要它们由同一发行商发行的),你需要在这两个应用程序的Andr​​oidManifest.xml中指定一个共享的用户ID。

In order to share data between apps (provided they are issued by the same publisher) you will need to specify a shared user id in the AndroidManifest.xml of both apps.

<manifest xmlns:android="http://schemas.android.com/apk/res/android" android:sharedUserId="my.app" ... >

(它的无证,而是共享用户ID需要是一个字符串与至少一个点隔板)

(It's undocumented, but the shared user id need to be a string with at least one dot separator)

剩下的就是简单,你不需要乱用数据库路径周围。只要使用同一个DBAdapter在这两个应用程序。在承载数据库的应用程序,调用与本地环境的DBAdapter。

The rest is easy, and you don't need to mess around with the database path. Just use the same DBAdapter in both apps. In the app that hosts the database, call the DBAdapter with the native context.

DBadapter hostDBAdapter = new DbAdapter(getApplicationContext());
performerDBadapter.open();

在所述第二应用程序,访问该数据库与数据库托管应用程序的上下文中。
首先,定义共享上下文:

In the second app, access the database with the context of the database hosting app.
First, define the shared context:

Context sharedContext = null;
    try {
        sharedContext = this.createPackageContext("replace.with.host.package.name", Context.CONTEXT_INCLUDE_CODE);
        if (sharedContext == null) {
            return;
        }
    } catch (Exception e) {
        String error = e.getMessage(); 
        return;
        }   

然后打开与共享的背景下DBAdapter:

Then open the DBAdapter with the shared context:

DbAdapter sharedDBadapter = new PerformerDbAdapter(sharedContext);
sharedDBadapter.open();

最后要注意,如果你的数据库存在previous来设置共享用户ID清单中,您将需要卸载/重新安装一个物理设备上的应用程序,否则你将自己锁定你的数据库( sqlite的错误1​​4)。模拟器,在另一方面,可能被证明是更宽容。底线,如果您的应用程序发布在Android市场上,设置在事后一个共享的用户ID将无法正常工作。

As a final note, if your database exists previous to setting the shared user id in the manifest, you will need to uninstall/reinstall the apps on a physical device, lest you will lock yourself out of your database (sqlite error 14). The emulator, on the other hand, might prove to be more forgiving. Bottom line, if your apps are published on the Android market, setting a shared user id in an afterthought will not work.

希望这有助于。

这篇关于2 Android应用程序之间共享SQLite数据库?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆