簡體   English   中英

將另一個 Android 應用程序的服務啟動到我自己的應用程序中

[英]Starting a service of another Android app into my own app

我正在使用am startservice從 shell 運行 android 應用程序的服務。 一切正常。

am startservice -a com.anotherdeveloper.app.SERVICE --ef a 1 --ef b 2

我想知道是否可以在沒有開發人員的情況下啟動另一個 android 應用程序的服務? 根據此鏈接,可以: 如何從另一個 Android 應用程序啟動 android 服務

但我不太明白該怎么做。

這是我在MainActivity中使用的代碼:

Intent intent = new Intent();
intent.setComponent(new ComponentName("com.anotherdeveloper.app", "com.anotherdeveloper.app.SERVICE"));
ComponentName c = getApplicationContext().startForegroundService(intent);

AndroidManifest.xml我添加了這個:

  <service
        android:name="com.anotherdeveloper.app.SERVICE"
        android:enabled="true"
        android:exported="true" />

但它在清單中顯示了一個錯誤,因為 Android Studio 找不到安裝在我手機上的這個應用程序的 package 名稱。


更新

感謝@Martin Marconcini,這是我正在使用的代碼:

  Intent intent = new Intent();
  intent.setComponent(new ComponentName("com.anotherdeveloper.app","com.anotherdeveloper.app.SERVICE"));
  intent.putExtra("cty", 4);
  intent.putExtra("stt", 2);
  startService(intent);

這是AndroidManifest.xml中的服務:

<service name="com.anotherdeveloper.app.General">
  <intent-filter>
    <action name="com.anotherdeveloper.app.SERVICE"/>
  </intent-filter>
  <intent-filter>
    <action name="com.anotherdeveloper.app.SERVICE_ALT"/>
  </intent-filter>
  <intent-filter>
    <action name="com.anotherdeveloper.app.TERMINATE"/>
  </intent-filter>
</service>

簡短回答:它完全取決於第 3 方的決定(服務創建者在相應的android:exported中寫的內容)

更多詳細信息: https://developer.android.com/guide/topics/manifest/service-element

在評論中擴展您的問題:

  1. 是的,如果服務已導出(並且您說是),您可以啟動該服務,所以它應該可以工作。

  2. 要通過 Intent 傳遞參數,您需要使用“Extras”。 這類似於您在adb shell am中使用的-e參數。

Intent i = new Intent();
i.putXXX(key, value)

您將獲得很多選項(針對每種類型)而不是 XXX,例如:

int value = 1;
i.putExtra("Key", value)

// or

String value = "X"
i.putExtra("Key", value)

// or

boolean value = true;
i.putExtra("Key", value)

它們都可以工作(當然要使鍵獨一無二)。

或者,您可以傳遞一個包含一堆的Bundle

        Bundle b = new Bundle();
        b.putString("x", "value");
        b.putInt("x", 1);
        b.putBoolean("x", true);

        Intent i = new Intent();
        i.putExtra("theBundle", b);

本質上,這一切都非常像 Google/Java,一致性不是關鍵。 ;)

(當然,如果你傳遞一個捆綁包,接收者必須知道這一點,這樣它才能從額外內容中“獲取捆綁包”,然后提取每個鍵/值。

換句話說,Bundle 是一個美化的字典,它支持不同的類型,並且所有東西都必須是Parcelable 所以它是一個必須是可打包的鍵/值存儲。

Intent 數據大小(用於附加)有 X 的限制(不記得是 1mb 還是什么),但您不能只序列化 1 TB 的信息並通過 Intent 扔掉它。 記在腦子里。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM