应用找不到外部服务-为什么会这样?

时间:2019-06-10 16:08:41

标签: android android-intent android-service android-intentservice

在App A中,我具有以下代码以在App B中启动服务:

public void startAppBService() {
    PackageManager packageManager = getPackageManager();
    Intent serviceIntent = new Intent("com.example.project.appBCommunicator");
    List<ResolveInfo> services = packageManager.queryIntentServices(serviceIntent, 0);
    Log.d("Services", Integer.toString(services.size()));
    if (services.size() > 0) {
        ResolveInfo service = services.get(0);

        serviceIntent.setClassName(service.serviceInfo.packageName, service.serviceInfo.name);
        serviceIntent.setAction("com.example.project.appBReceive");
        serviceIntent.putExtra("foo", "bar");
        serviceIntent.putExtra("appAReceiver", resultReceiver);

        ComponentName cn = startService(serviceIntent);
    }
}

我在App A的onCreate方法中调用此代码。

在App B中,我在这样的清单中注册了我的IntentService

<service
    android:name="com.example.project.appBCommunicator"
    android:enabled="true"
    android:exported="true"
    android:process=":remote">
    <intent-filter>
        <action android:name="com.example.project.appBReceive" />
        />
    </intent-filter>
</service>

我的IntentService的代码是这样的:

public class AppBCommunicator extends IntentService {

    public AppBCommunicator() {
        super("AppBCommunicator");
    }

    public AppBCommunicator(String name) {
        super(name);
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        ResultReceiver rec = intent.getParcelableExtra("appAReceiver");
        ResultReceiver sendingReceiver = receiverForSending(rec);
        String val = intent.getStringExtra("foo");
        Bundle bundle = new Bundle();
        bundle.putString("resultValue", "My Result Value. Passed in: " + val);
        sendingReceiver.send(Activity.RESULT_OK, bundle);
    }

    public static ResultReceiver receiverForSending(ResultReceiver actualReceiver) {
        Parcel parcel = Parcel.obtain();
        actualReceiver.writeToParcel(parcel,0);
        parcel.setDataPosition(0);
        ResultReceiver receiverForSending = ResultReceiver.CREATOR.createFromParcel(parcel);
        parcel.recycle();
        return receiverForSending;
    }
}

由于某种原因,应用A找不到应用B的IntentService(services.size()返回0)。我在做错什么吗?

2 个答案:

答案 0 :(得分:1)

您的Intent是:

Intent serviceIntent = new Intent("com.example.project.appBCommunicator");

在这里,您的操作字符串为com.example.project.appBCommunicator

您的<intent-filter>是:

<intent-filter>
    <action android:name="com.example.project.appBReceive" />
    />
</intent-filter>

在这里,您的操作字符串为com.example.project.appBReceive

您的Intent与您的<intent-filter>不匹配,因为操作字符串不匹配。

答案 1 :(得分:0)

显然,我的解决方法是删除我的IntentService文件,并使用Android Studio自动生成向导以其他名称重新创建它,而不是手动创建它。我不知道为什么会有所不同,但是确实如此。