android - 如何以编程方式在设备中运行已安装应用程序的服务

标签 android android-service

我有一个函数来获取正在运行的服务:

public ArrayList<String> getRunningServices() {

    ActivityManager activityMg = (ActivityManager)context.getSystemService(context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningServiceInfo> serviceList = activityMg.getRunningServices(100);
    ArrayList<String> serviceName = new ArrayList<String>();

 for (int i=0; i<serviceList.size(); i++) {
       ActivityManager.RunningServiceInfo currentService = serviceList.get(i);
       boolean serviceNam = currentService.started;
       if (serviceNam == true) {
           serviceName.add(currentService.service.getPackageName());
    }

     }

    return serviceName;

}

现在我想运行其中一项服务(如果它已停止)。

要运行已安装的应用程序,我必须使用如下代码的 Intent :

      Intent intent = context.getPackageManager().getLaunchIntentForPackage(nameOfPakage);
    context.startActivity(intent);

但我只想运行这个应用程序或另一个应用程序的服务。

我有一个应用程序包的字符串名称,我想启动它的服务。

这可能吗?

最佳答案

您好,下面是从另一个应用程序启动服务。

Intent intent = new Intent();
String pkg = currentService.service.getPackageName();
String cls = currentService.service.getPackageName() + "." + currentService.service.getClassName();
intent.setComponent(new ComponentName(pkg, cls));
startService(intent);

关于android - 如何以编程方式在设备中运行已安装应用程序的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28272122/

相关文章:

Android 在出错时显示来自服务的对话框

android - 关闭应用程序时如何停止Android服务

安卓 11 : starting a service of another app

java - Firebase 连接问题

android - 将 SimpleXmlConverter 与 Retrofit 2.0 一起使用时出现 IllegalArgumentException : Unable to create converter for java. util.List<ModelClass>

java - Android 异步类返回 null

java - 将 OnQueryTextListener 附加到 SearchView 会给出 NullPointerException

java - RxJava 和 GreenRobot 事件总线

android - 安全异常 : Not allowed to start Service

android - 使用 am startservice 重新启动 SystemUI