第一篇、Android学习之AIDL学习:跨应用启动服务Serivce

本文介绍如何在Android应用间通过AIDL进行跨应用服务调用。重点讲解了在Android 5.0及以后版本中使用显式Intent启动服务的方法,包括设置Intent的ComponentName以及启动和停止服务的过程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

第一篇、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方法启动服务。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

尹振坤

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值