program story

서비스 의도는 명시 적이어야 함 : 의도

inputbox 2020. 11. 20. 08:56
반응형

서비스 의도는 명시 적이어야 함 : 의도


브로드 캐스트 수신기 (MyStartupIntentReceiver)를 통해 서비스를 호출하는 앱이 있습니다. 서비스를 호출하기위한 broadcast receiver의 코드는 다음과 같습니다.

public void onReceive(Context context, Intent intent) {
    Intent serviceIntent = new Intent();
    serviceIntent.setAction("com.duk3r.eortologio2.MyService");
    context.startService(serviceIntent);
}

문제는 Android 5.0 Lollipop에서 다음 오류가 발생한다는 것입니다 (이전 버전의 Android에서는 모든 것이 정상적으로 작동 함).

Unable to start receiver com.duk3r.eortologio2.MyStartupIntentReceiver: java.lang.IllegalArgumentException: Service Intent must be explicit: Intent { act=com.duk3r.eortologio2.MyService }

서비스를 명시 적으로 선언하고 정상적으로 시작하려면 무엇을 변경해야합니까? 다른 유사한 스레드에서 몇 가지 답변을 시도했지만 메시지를 제거했지만 서비스가 시작되지 않았습니다.


앱의 서비스, 활동 등에 대한 모든 의도는 항상이 형식을 따라야합니다.

Intent serviceIntent = new Intent(context,MyService.class);
context.startService(serviceIntent);

또는

Intent bi = new Intent("com.android.vending.billing.InAppBillingService.BIND");
bi.setPackage("com.android.vending");

암시 적 의도 (현재 코드에있는 것)는 보안 위험으로 간주됩니다.


packageName작품을 설정하십시오 .

intent.setPackage(this.getPackageName());

암시 적 의도를 명시 적 의도로 변환 한 다음 서비스를 시작합니다.

        Intent implicitIntent = new Intent();
        implicitIntent.setAction("com.duk3r.eortologio2.MyService");
        Context context = getApplicationContext();
        Intent explicitIntent = convertImplicitIntentToExplicitIntent(implicitIntent, context);
        if(explicitIntent != null){
            context.startService(explicitIntent);
            }


    public static Intent convertImplicitIntentToExplicitIntent(Intent implicitIntent, Context context) {
            PackageManager pm = context.getPackageManager();
            List<ResolveInfo> resolveInfoList = pm.queryIntentServices(implicitIntent, 0);

            if (resolveInfoList == null || resolveInfoList.size() != 1) {
                return null;
            }
            ResolveInfo serviceInfo = resolveInfoList.get(0);
            ComponentName component = new ComponentName(serviceInfo.serviceInfo.packageName, serviceInfo.serviceInfo.name);
            Intent explicitIntent = new Intent(implicitIntent);
            explicitIntent.setComponent(component);
            return explicitIntent;
        }

이 시도. 그것은 나를 위해 작동합니다. 여기 MonitoringService 는 내 서비스 클래스입니다. 중지 또는 시작할 서비스를 나타내는 두 가지 작업이 있습니다. broadcast receiver 에서 해당 값 AIRPLANE_MODE_CHANGED에 따라 보냅니다 .

@Override
public void onReceive(Context context, Intent intent) {   
    String action = intent.getAction();

    if(Intent.ACTION_AIRPLANE_MODE_CHANGED.equalsIgnoreCase(action)){
         boolean isOn = intent.getBooleanExtra("state", false);
         String serviceAction = isOn? MonitoringService.StopAction : MonitoringService.StartAction;
         Intent serviceIntent = new Intent(context, MonitoringService.class);
         serviceIntent.setAction(serviceAction);
         context.startService(serviceIntent);
    }
}

참고 : 다음 코드를 추가하여 ManageLocationListenerReceiver 라는 브로드 캐스트 수신기를 트리거 합니다.

<receiver
     android:name=".ManageLocationListenerReceiver"
     android:enabled="true"
     android:exported="true">
     <intent-filter>
         <action android:name="android.intent.action.AIRPLANE_MODE" />
     </intent-filter>
</receiver>

컨텍스트 종속성을 제거하기 위해 Shahidul의 답변을 개선했습니다.

public class ServiceUtils {
    public static void startService(String intentUri) {
        Intent implicitIntent = new Intent();
        implicitIntent.setAction(intentUri);
        Context context = SuperApplication.getContext();
        Intent explicitIntent = convertImplicitIntentToExplicitIntent(implicitIntent, context);
        if(explicitIntent != null){
            context.startService(explicitIntent);
        }
    }

    private static Intent convertImplicitIntentToExplicitIntent(Intent implicitIntent, Context context) {
        PackageManager pm = context.getPackageManager();
        List<ResolveInfo> resolveInfoList = pm.queryIntentServices(implicitIntent, 0);

        if (resolveInfoList == null || resolveInfoList.size() != 1) {
            return null;
        }
        ResolveInfo serviceInfo = resolveInfoList.get(0);
        ComponentName component = new ComponentName(serviceInfo.serviceInfo.packageName, serviceInfo.serviceInfo.name);
        Intent explicitIntent = new Intent(implicitIntent);
        explicitIntent.setComponent(component);
        return explicitIntent;
    }
}

SuperApplication 클래스 내부 :

public class SuperApplication extends Application {
    private static MyApp instance;

    public static SuperApplication getInstance() {
        return instance;
    }

    public static Context getContext(){
        return instance;
        // or return instance.getApplicationContext();
    }

    @Override
    public void onCreate() {
        instance = this;
        super.onCreate();
    }
}

매니페스트에서 :

<application
    android:name="com.example.app.SuperApplication "
    android:icon="@drawable/icon"
    android:label="@string/app_name"
    .......
    <activity
        ......

그런 다음 전화하십시오.

ServiceUtils.startService("com.myservice");

참고 URL : https://stackoverflow.com/questions/27842430/service-intent-must-be-explicit-intent

반응형