我改进了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;
}
@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");