如何在不打开另一个应用程序的情况下将数据从一个应用程序传递到另一个应用程序?

How to pass data from one app to another app without opening the latter?

我想从应用程序 A 触发应用程序 B。

为了实现这一点,我在 A

中写了以下内容
PackageManager pm = getPackageManager();
Intent intent = pm.getLaunchIntentForPackage("com.somepackage.appb");
intent.putExtra("secret", "message");
startActivity(intent);

然而,这会打开不需要的应用程序 B。

请提出解决方法以避免 B 打开并在后台从应用程序 A 接收数据。

在应用程序 B 中写一个 BroadcastReceiver 并在您的清单中声明它。

在应用程序 A 中,制作一个带有附加功能的意图以该接收器为目标,并使用该意图调用 sendBroadcast

应用程序 B:

清单

<application>
    ...
    <receiver android:name=".IncomingReceiver" android:enabled="true">
        <intent-filter>
            <action android:name="jason.wei.custom.intent.action.TEST"></action>
        </intent-filter>
    </receiver>
</application>

IncomingReceiver.java

public class IncomingReceiver extends BroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String CUSTOM_INTENT = "jason.wei.custom.intent.action.TEST";
        if (intent.getAction().equals(CUSTOM_INTENT)) {
            System.out.println("GOT THE INTENT");
            Toast.makeText(context, "GOT THE INTENT", Toast.LENGTH_LONG).show();
        }
    }
}

应用程序 A:

String CUSTOM_INTENT = "jason.wei.custom.intent.action.TEST";
Intent i = new Intent();
i.setAction(CUSTOM_INTENT);
sendBroadcast(i);

您可以使用 SharedPreferences.

如您所见,有很多方法可以做到这一点...我自己更喜欢创建一种服务,它可以在不与应用程序 B 交互的情况下更新数据