关于Service的启动的小细节

2017-04-22  本文已影响0人  DorisSunny

Service启动方式

显式启动方式

Intent intent = new  Intent(MainActivity.this,SecondActivity.class);  
startActivity(intent);

隐式启动方式

Intent intent = new Intent();
intent.setAction("com.update.reboot");
startActivity(intent);

//AndroidMainfest.xml
  <service android:name=".service.UpdateRebootService">
           <intent-filter>
               <action android:name="com.update.reboot"/>
           </intent-filter>
       </service>

这是Service隐式和显式启动的代码范例。不同应用之前只能用隐式启动,同一个应用两种方式都可以。

在Android5.0以上,Service的调用必须用显式调用,否则会报错。不过Android5.0 以上的显式调用除了,上述的显示启动方式之外,对于不同包之前或者不同应用之间,要启动Service,则用下面这种启动方式:

Android 5.0以上另一种显式启动方式(适用于不同应用之间)

Intent intent = new Intent();
intent.setAction("com.update.reboot");
intent.setPackage("packagename");//注意是对应的应用包名
startActivity(intent);

//AndroidMainfest.xml
  <service android:name=".service.UpdateRebootService">
           <intent-filter>
               <action android:name="com.update.reboot"/>
           </intent-filter>
       </service>

其实和隐式启动相比,只是多了一句指定包名了而已,不过也恰恰正因为指定了包名,所以被称之为显式启动.

上一篇下一篇

猜你喜欢

热点阅读