一、跨应用启动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的应用与理解的更多相关文章

  1. Android 中AIDL的使用与理解

    AIDL的使用: 最常见的aidl的使用就是Service的跨进程通信了,那么我们就写一个Activity和Service的跨进程通信吧. 首先,我们就在AS里面新建一个aidl文件(ps:现在AS建 ...

  2. Android中AIDL的理解与使用(二)——跨应用绑定Service并通信

    跨应用绑定Service并通信: 1.(StartServiceFromAnotherApp)AIDL文件中新增接口: void setData(String data); AppService文件中 ...

  3. android中对线程池的理解与使用

    前段时间有幸接到腾讯上海分公司的 Android开发面试,虽然最后一轮被毙了.但还是得总结一下自己在android开发中的一些盲点,最让我尴尬的是面试官问我几个android中线程池的使用与理解..哎 ...

  4. 【转】Android中BindService方式使用的理解

    原文网址:http://www.cnblogs.com/onlylittlegod/archive/2011/05/15/2046652.html 最近学习了一下Android里面的Service的应 ...

  5. Android中对Handle机制的理解

    一.重要參考资料  [參考资料]     眼下来看,以下的几个网址中的内容质量比較不错.基本不须要再读别的网址了. 1.android消息机制一     http://xtfncel.javaeye. ...

  6. Android中Adapter和Bridge模式理解和应用

    一 Adapter模式 意图: 将一个类的接口转换成客户希望的另外一个接口. Adapter模式使得原本由于接口不兼容而不能在一起工作的那些类可以在一起工作. 适用性: 使用一个已存在的类,而它的接口 ...

  7. 谈谈对Android中的消息机制的理解

    Android中的消息机制主要由Handler.MessageQueue.Looper三个类组成,他们的主要作用是 Handler负责发送.处理Message MessageQueue负责维护Mess ...

  8. Android中AIDL的理解与使用(一)——跨应用启动/绑定Service

    AIDL(Android Interface Definition Language)--安卓接口定义语言 一.startService/stopService 1.同一个应用程序启动Service: ...

  9. Android中AIDL通信机制分析

    一.背景 ·1.AIDL出现的原因 在android系统中,每一个程序都是运行在自己的进程中,进程之间无法进行通讯,为了在Android平台,一个进程通常不能访问另一个进程的内存空间,所以要想对话,需 ...

随机推荐

  1. mysql sql limit where having order

    SQL语句执行顺序及MySQL中limit的用法 . 分类: MySql2013-09-02 09:1315人阅读评论(0)收藏举报 写的顺序:select ... from... where.... ...

  2. Oracle DBlink的创建-查看与删除

    DBlink常用于在两个Oracle数据库之间相互连接,如手工同步数据时,DBLink是最方便快捷的手段之一. 1.创建DBLink语法:create public database link < ...

  3. Oracle Linux Server 7安装VMwareTools问题

    OracleLinuxServer7安装VMwareTools问题#./vmware-install.pl时报错:#-bash: ./vmware-instal.pl:/usr/bin/perl:ba ...

  4. 【沙茶了+筛选保存最大质因数】【HDU2136】Largest prime factor

    Largest prime factor Time Limit: 5000/1000 MS (Java/Others)    Memory Limit: 32768/32768 K (Java/Oth ...

  5. MySQL安装配置过程

    1.下载压缩包,解压: 2: 修改  my-default.ini 文件 将一下代码前# 去掉修改成自己的地址 # These are commonly set, remove the # and s ...

  6. 深入浅析mysql引擎

    mysql引擎 mysql数据库引擎取决于mysql在安装的时候是如何被编译的.要添加一个新的引擎,就必须重新编译mysql.在缺省情况下,mysql支持三个引擎:ISAM,MYISAM和HEAP.另 ...

  7. eclipse优化配置

    -startup plugins/org.eclipse.equinox.launcher_1..jar --launcher.library plugins/org.eclipse.equinox. ...

  8. python运维开发(十一)----线程、进程、协程

    内容目录: 线程 基本使用 线程锁 自定义线程池 进程 基本使用 进程锁 进程数据共享 进程池 协程 线程 线程使用的两种方式,一种为我们直接调用thread模块上的方法,另一种我们自定义方式 方式一 ...

  9. python运维开发(九)----socket

    内容目录: socket通信过程 单线程socket 多线程socket ThreadingTCPServer socket socket通常也称作"套接字",用于描述IP地址和端 ...

  10. undefined reference to `_sbrk', `_write', `_lseek', `_read'

    现象: 在用GCC编译嵌入式MCU程序时,由于使用了第三方的库,出现了类似undefined reference to `_sbrk', `_write', `_lseek', `_read'的连接错 ...