How to start android service from another Android app

前端 未结 2 1113
梦如初夏
梦如初夏 2020-12-04 18:39

I\'m having a problem starting a service from another Android app (API 17). However, if I do run \'am\' from the shell, the service starts fine.

# am startse         


        
相关标签:
2条回答
  • 2020-12-04 18:43

    You should be able to start your service like this:

    Intent i = new Intent();
    i.setComponent(new ComponentName("com.xxx.yyy", "com.xxx.yyy.SyncService"));
    ComponentName c = ctx.startService(i);
    

    You don't need to set ACTION or CATEGORY if you are specifying a specific component. Make sure that your service is properly defined in the manifest.

    0 讨论(0)
  • 2020-12-04 19:08

    Start your service like this

    Intent intent = new Intent();
    intent.setComponent(new ComponentName("pkg", "cls"));
    ComponentName c = getApplicationContext().startForegroundService(intent);
    

    btw you actually need to use the applicationId, instead of the pkg. it can be found in the app gradle. I was struggling with that mistake for hours!

       defaultConfig {
            applicationId "com.xxx.zzz"
    }
    

    the cls is the name of your service declared in the manifest. example: com.xxx.yyy.yourService.

     <service android:name="com.xxx.yyy.yourService"
    android:exported="true"/>
    
    0 讨论(0)
提交回复
热议问题