Android开发之AIDL的使用一--跨应用启动Service
2024-08-29 10:17:58
启动其他App的服务,跨进程启动服务。
与启动本应用的Service一样,使用startService(intent)方法
不同的是intent需要携带的内容不同,需要使用intent的setComponent()方法。
setComponent()方法需要传入两个参数,第一个参数是包名,第二个参数是组件名。即,第一个参数传入要启动的其他app的包名,第二个参数传入的时候要启动的其他app的service名。
看下面的例子:(aidlserviceapp应用通过button启动aidlservice应用的MyService)
aidlserviceapp应用:
package com.example.aidlserviceapp; import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button; public class MainActivity extends Activity implements OnClickListener { private Button btn_StartService, btn_StopService;
Intent serviceIntent = null; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
serviceIntent = new Intent();
ComponentName componentName = new ComponentName(
"com.example.aidlservice", "com.example.aidlservice.MyService");
serviceIntent.setComponent(componentName); // 使用intent的setComponent()方法,启动其他应用的组件。 btn_StartService = (Button) findViewById(R.id.btn_StartService);
btn_StopService = (Button) findViewById(R.id.btn_StopService); btn_StartService.setOnClickListener(this);
btn_StopService.setOnClickListener(this); } @Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_StartService:
startService(serviceIntent);
break;
case R.id.btn_StopService:
stopService(serviceIntent);
break;
default:
break;
}
}
}
aidlservice应用
package com.example.aidlservice; import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log; public class MyService extends Service {
public static final String TAG = "aidlservice"; @Override
public IBinder onBind(Intent intent) {
return null;
} @Override
public void onCreate() {
super.onCreate();
Log.e(TAG, "其他应用服务启动");
} @Override
public void onDestroy() {
super.onDestroy();
Log.e(TAG, "其他应用服务停止");
} }
同时添加MyService在该应用的manifest。
1.启动aidlservice应用
2.启动aidlserviceapp应用
3.点击button,查看打印的log,是否启动了aidlservice应用的MyService服务。
结果如下图,启动成功。
最新文章
- 关于datagridview里使用combox的总结
- there are no packages available for installation插件安装问题和如何配置浏览器的快捷键
- 开源免费天气预报接口API以及全国所有地区代码!!(国家气象局提供) 【转】
- Android View坐标Left, Right, Top, Bottom
- (LinkedList)Intersection of Two Linked Lists
- JavaScript学习总结【8】、面向对象编程
- LightOj_1030 Discovering Gold
- Mac下面的SecureCRT以及破解方案详解
- CodeForces 1151E Number of Components
- drf视图组件、认证组件
- Java 多线程之Timer与ScheduledExecutorService
- java字符串根据正则表达式让单词首字母大写
- rm 命令
- Flask中的模板语言jinja2
- Java各种对象(PO,BO,VO,DTO,POJO,DAO,Entity,JavaBean,JavaBeans)的区分
- 使用HTML5的两个api,前端js完成图片压缩
- debian下没有公钥解决办法
- wxpython Menus and toolbars
- javascript中window.location.search方法简介
- Netty组件介绍(转)