第一篇、Android学习之AIDL学习:
跨应用启动服务Serivce
一、跨应用启动服务Service:前言
在之前的学习中,我们了解到,当一个应用中的Activity 想要启动另个应用中的Activity可以通过隐式Intent的方式,通过
给Activity配置一个Action实现该功能。那么我们是否可以给Service配置个action来启动service呢。在Android5.0之前
是可以的,但是,在android5.0之后就不可以了。我们只能通过显式Intent启动服务。但是,我们又无法获取另一个应用的类
的定义。所以,我们需要采用另一种方式实现对另一个应用服务的调用。
###二、实现
首先,需要有一个包含自定义服务的应用和一个普通应用。这里以app1和app2为例。其中内部构造如下:
app1:MainActivity、MyService、
- MyService.java
public class MyService extends android.app.Service{
public IBinder onBind(Intent intent){
return new Bind();
}
public void onCreate(){
System.out.println("MyService is Start");
}
}
这个例子主要是实现通过app2调用app1的MyService
而关键的方法主要是,调用Intent的setComponent(ComponentName name)
方法。从而实现调用其他应用服务的功能。
app2:MainActivity.java
public class MainActivity extends Activity{
private Intent serviceIntent;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serviceIntent = new Intent();
/**
*这里的ComponentName(String packageName,String className);
* 参数的含义依次为:服务的包名,服务的类名。
*/
serviceIntent.setComponent(new ComponentName("com.snowlive.service14","com.snowlive.service14.SendInfoService"));
//启动服务
startService(serviceIntent);
}
protected void onDestroy() {
super.onDestroy();
//停止服务
stopService(serviceIntent);
}
}
通过在Activity的onCreate方法设置serviceIntent,并调用startService(serviceIntent)
方法启动服务
在Activity的onDestroy方法调用stopService(serviceIntent)
方法停止服务。
三、总结:
再次回顾,启动其他应用的服务的方法,关键步骤就是两步:
- 为Intent设置Component
- 调用startService方法启动服务。