(七)Android中AIDL的应用与理解
一、跨应用启动Service
Intent serviceIntent=new Intent();
serviceIntent.setComponent(new ComponentName("com.example.shiyanshi.startservicefromanotherapp","com.example.shiyanshi.startservicefromanotherapp.AppService"));
跨应用启动Service时,Android5.0以前可以调用隐式Intent(通过在Service设置过滤器intent-filte),Android5.0之后只允许显示Intent来启动。首先创建Intent,之后调用setComponent函数来设置组件,该函数需要一个ComponentName的对象,ComponentName第一个参数为包名,第二个参数为包中的服务类名。
二、跨应用绑定Service并进行通信
app模块中:
1.MainActivity.java
package com.example.shiyanshi.startservicefromoterapp; import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem; public class MainActivity extends Activity { @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); startService(new Intent(this,MyService.class));
} @Override
protected void onDestroy() {
super.onDestroy(); stopService(new Intent(this,MyService.class));
} @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
} @Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId(); //noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
} return super.onOptionsItemSelected(item);
}
}
2.MyService.java
package com.example.shiyanshi.startservicefromoterapp; import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException; public class MyService extends Service {
public MyService() {
} private String data="default data";
private boolean flag; @Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
// throw new UnsupportedOperationException("Not yet implemented");
//返回的是AIDL中的接口,并且此处实现了接口函数的重定义
return new IAppRemoteServiceBinder.Stub() {
@Override
public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {
}
@Override
public void setData(String data) throws RemoteException {
MyService.this.data=data;
}
};
}
@Override
public void onCreate() {
super.onCreate();
System.out.println("**********MyService onCreate************");
//该线程主要用于不断的输出该service种的数据data,data数据的值可以通过在anotherapp中调用setData函数进行设置,这样便实现了双方的通信
new Thread(){
@Override
public void run() {
super.run();
flag=true;
while (flag) {
System.out.println(data);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
@Override
public void onDestroy() {
super.onDestroy();
System.out.println("***************MyService onDestroy********************");
flag=false;
}
}
//
不同的应用进行通信时需要创建aidl文件,并且在其中实现接口函数的定义
3.IAppRemoteServiceBinder.aidl
// IAppRemoteServiceBinder.aidl
package com.example.shiyanshi.startservicefromoterapp; // Declare any non-default types here with import statements interface IAppRemoteServiceBinder {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
double aDouble, String aString);
void setData(String data); //用于两个应用程序之间进行通信的接口函数
}
anotherapp中:
1.布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"
android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:orientation="vertical"
android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"> <TextView android:text="@string/hello_world" android:layout_width="wrap_content"
android:layout_height="wrap_content" /> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="启动外部服务"
android:id="@+id/btnStartService"
android:layout_gravity="bottom" /> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="关闭外部服务"
android:id="@+id/btnStopService"
android:layout_gravity="center_vertical" /> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="绑定外部服务"
android:id="@+id/btnBindService" /> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="解除绑定外部服务"
android:id="@+id/btnUnbindService" /> <Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="同步数据到外部服务"
android:id="@+id/btnSyncDataToAppService" />
<EditText
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="**************"
android:id="@+id/editTextInput"/> </LinearLayout>
2.MainActivity.java
package com.example.shiyanshi.anotherapp; import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.os.RemoteException;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.EditText; import com.example.shiyanshi.startservicefromoterapp.IAppRemoteServiceBinder; public class MainActivity extends Activity implements View.OnClickListener, ServiceConnection { Intent serviceIntent;
private EditText editTextInput;
private IAppRemoteServiceBinder binder; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); editTextInput=(EditText)findViewById(R.id.editTextInput); findViewById(R.id.btnStartService).setOnClickListener(this);
findViewById(R.id.btnStopService).setOnClickListener(this);
findViewById(R.id.btnBindService).setOnClickListener(this);
findViewById(R.id.btnUnbindService).setOnClickListener(this);
findViewById(R.id.btnSyncDataToAppService).setOnClickListener(this);
serviceIntent=new Intent();
serviceIntent.setComponent(new ComponentName("com.example.shiyanshi.startservicefromoterapp","com.example.shiyanshi.startservicefromoterapp.MyService")); } @Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
} @Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId(); //noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
} return super.onOptionsItemSelected(item);
} @Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btnStartService:
startService(serviceIntent);
break;
case R.id.btnStopService:
stopService(serviceIntent);
break;
case R.id.btnBindService:
bindService(serviceIntent,this, Context.BIND_AUTO_CREATE);
break;
case R.id.btnUnbindService:
unbindService(this);
binder=null;
break;
case R.id.btnSyncDataToAppService:
if (binder!=null){
try {
binder.setData(editTextInput.getText().toString());
} catch (RemoteException e) {
e.printStackTrace();
}
}
break;
}
}
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
System.out.println("*******onServiceConnected*************");
//不能直接强制类型转换,因为两个类型处于不同的应用程序中
binder=IAppRemoteServiceBinder.Stub.asInterface(iBinder);
}
@Override
public void onServiceDisconnected(ComponentName componentName) {
}
}
3.文件目录结构,将在App模块中创建的aidl文件复制到了anotherapp中,首先穿件aidl目录,然后在aidl目录中创建app中的程序包(com.example.shiyanshi.startservicefromoterapp),之后将app中的IAppRemoteServiceBinder.aidl文件复制到该程序包
(七)Android中AIDL的应用与理解的更多相关文章
- Android 中AIDL的使用与理解
AIDL的使用: 最常见的aidl的使用就是Service的跨进程通信了,那么我们就写一个Activity和Service的跨进程通信吧. 首先,我们就在AS里面新建一个aidl文件(ps:现在AS建 ...
- Android中AIDL的理解与使用(二)——跨应用绑定Service并通信
跨应用绑定Service并通信: 1.(StartServiceFromAnotherApp)AIDL文件中新增接口: void setData(String data); AppService文件中 ...
- android中对线程池的理解与使用
前段时间有幸接到腾讯上海分公司的 Android开发面试,虽然最后一轮被毙了.但还是得总结一下自己在android开发中的一些盲点,最让我尴尬的是面试官问我几个android中线程池的使用与理解..哎 ...
- 【转】Android中BindService方式使用的理解
原文网址:http://www.cnblogs.com/onlylittlegod/archive/2011/05/15/2046652.html 最近学习了一下Android里面的Service的应 ...
- Android中对Handle机制的理解
一.重要參考资料 [參考资料] 眼下来看,以下的几个网址中的内容质量比較不错.基本不须要再读别的网址了. 1.android消息机制一 http://xtfncel.javaeye. ...
- Android中Adapter和Bridge模式理解和应用
一 Adapter模式 意图: 将一个类的接口转换成客户希望的另外一个接口. Adapter模式使得原本由于接口不兼容而不能在一起工作的那些类可以在一起工作. 适用性: 使用一个已存在的类,而它的接口 ...
- 谈谈对Android中的消息机制的理解
Android中的消息机制主要由Handler.MessageQueue.Looper三个类组成,他们的主要作用是 Handler负责发送.处理Message MessageQueue负责维护Mess ...
- Android中AIDL的理解与使用(一)——跨应用启动/绑定Service
AIDL(Android Interface Definition Language)--安卓接口定义语言 一.startService/stopService 1.同一个应用程序启动Service: ...
- Android中AIDL通信机制分析
一.背景 ·1.AIDL出现的原因 在android系统中,每一个程序都是运行在自己的进程中,进程之间无法进行通讯,为了在Android平台,一个进程通常不能访问另一个进程的内存空间,所以要想对话,需 ...
随机推荐
- Unity 3D 调用摄像头捕获照片 录像
1,要想调用摄像头首先要打开摄像头驱动,如果用户允许则可以使用. 2,定义WebCamTexture的变量用于捕获单张照片. 3,连续捕获须启用线程. 实现代码: using UnityEngine; ...
- Ubuntu下嵌入式Qt开发环境配置全攻略
http://qpcwth.blog.163.com/blog/static/20993024620139151424822/ 在安装的过称中,出现一些问题,注意试想: 1.本次开发环境的配置,是基于 ...
- Hacker(三)之黑客定位目标---IP
IP即Internet Protocol的简称,中文简称"网协",是为计算机网络相互连接进行通信而设计的协议.无论何种操作系统,只要遵守IP协议就可以与Internet互联互通. ...
- 解决 jsp:include 引用文件时出现乱码的问题
阐述问题前,先来看一下下面这张图片左侧iframe中的乱码页面: 这个就是让我纠结好一阵子的乱码截图: 这个乱码页面中是使用了<jsp:include>引用标签后出现了这个问题: 源码截图 ...
- 【指数型母函数+非递归快速幂】【HDU2065】"红色病毒"问题
大一上学完数分上后终于可以搞懂指数型母函数了.. 需要一点关于泰勒级数的高数知识 题目在此: "红色病毒"问题 Time Limit: 1000/1000 MS (Java/Oth ...
- DataSet、DataTable、DataRow区别
DataSet 表示数据在内存中的缓存. 属性 Tables 获取包含在 DataSet 中的表的集合. ds.Tables["sjxx"] DataTable 表示内存中数据 ...
- [转]C# 中的.pdb/ .vshost.exe/ .vshost.exe.manifest文件讨论
原文出处:http://blog.163.com/chwei_sunshine/blog/static/19412628320125893656652/ pdb文件: 英文全称:Program Dat ...
- 使用AsyncTask实现图片加载
如上图所示:我们看到的就是使用PrograssDialog进度条和AsyncTask异步任务实现的效果(额,不要看应用名...).下面介绍一下具体的实现流程. 一.首先使用XML布局,布局很简单直接上 ...
- MVC 过滤器 ActionFilterAttribute
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.We ...
- PHP基础之 file_get_contents() 函数
定义和用法 file_get_contents() 函数把整个文件读入一个字符串中. 和 file() 一样,不同的是 file_get_contents() 把文件读入一个字符串. file_get ...
