代码之家  ›  专栏  ›  技术社区  ›  Christian

如何将一个应用程序的意图发送到另一个应用程序?

  •  0
  • Christian  · 技术社区  · 6 年前

    我有一节课 IntentService 其中 com.mypackage.app1.receiver (第一个应用程序):

    public class IntentService extends Service {
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
            Log.w("INTENT SERVICE", "Received request to start intent");
            return super.onStartCommand(intent, flags, startId);
        }
    
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            Log.w(TAG, "onBind");
            return null;
        }
    }
    

    在清单中我注册:

    <service android:name=".IntentService" >
        <intent-filter>
            <action android:name="com.mypackage.START_INTENT"/>
            <category android:name="com.mypackage.category.DEFAULT"/>
            <data android:mimeType="text/plain"/>
        </intent-filter>
    </service>
    

    在我的另一个应用程序中 SenderActivity 在里面 com.mypackage.app2.sender 只需在打开和关闭时立即发送意图:

    public class SenderActivity extends AppCompatActivity {
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Intent intent = new Intent("com.learningleaflets.START_INTENT");
            intent.setPackage("com.mypackage");
            startService(intent);
            finish();
        }
    }
    

    不幸的是,目前的意图是 发送活动 发送未被接收 维护服务 是的。我该怎么做才能收到?

    1 回复  |  直到 6 年前
        1
  •  2
  •   CommonsWare    6 年前

    替换:

    <service android:name=".IntentService" >
        <intent-filter>
            <action android:name="com.mypackage.START_INTENT"/>
            <category android:name="com.mypackage.category.DEFAULT"/>
            <data android:mimeType="text/plain"/>
        </intent-filter>
    </service>
    

    使用:

    <service android:name=".IntentService" >
        <intent-filter>
            <action android:name="com.learningleaflets.START_INTENT"/>
        </intent-filter>
    </service>
    

    与你的 Intent 你正在使用的 startService() .

    另外,因为有一个名为 IntentService ,我建议您将服务的名称更改为其他名称。