一、跨应用启动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. PreferenceFragment 使用 小结

    Perference也就是我们常说的偏好设置,首选项设置,能够自己主动保存一些数据,比如我们在上一次使用的时候的一些内容,则在下一次启动后依旧生效,而不须要再进行配置.当用户改变设置时,系统就会更新S ...

  2. c# 面相对象1-概括

    面向对象和面向过程的区别 面向过程就是分析出解决问题所需要的步骤,然后用函数把这些步骤一步一步实现,使用的时候一个一个依次调用就可以了.  面向对象是把构成问题事务分解成各个对象,建立对象的目的不是为 ...

  3. PHP学习笔记十四【面向对象】

    <?php class Cat{ public $name; public $age; public $color; } //创建一个对象 $cat1=new Cat(); $cat1-> ...

  4. 一.Linq to JSON是用来干什么的?

    Linq to JSON是用来操作JSON对象的.可以用于快速查询,修改和创建JSON对象.当JSON对象内容比较复杂,而我们仅仅需要其中的一小部分数据时,可以考虑使用Linq to JSON来读取和 ...

  5. U - stl 的 优先队列 Ⅰ

    Description Given m sequences, each contains n non-negative integer. Now we may select one number fr ...

  6. shopnc 导出Excel数据问题实例 && ajax 获取当前值并传递

    任务:从商家中心导出数据,各个商品所属情况. 商品导出到Excel文件功能 /导出exel 功能make-in-lemon public function createExcelOp(){ $mode ...

  7. ListView的使用——聊天窗口

    一.步骤 1.在layout创建两个布局,分别是自己的回答条,和对方的回答条. 2.创建ChatMessage这个类,成员变量有头像地址.聊天内容.所属类型(假设1表示对方,2表示自己). 3.创建C ...

  8. hdu 4906 3-idiots fft

    题目链接 n个火柴棍取3个, 问能组成三角形的概率是多少. kuangbin大神的博客写的很详细了..http://www.cnblogs.com/kuangbin/archive/2013/07/2 ...

  9. Leetcode 171 Excel Sheet Column Number python

    题目: Given a column title as appear in an Excel sheet, return its corresponding column number. For ex ...

  10. 高性能WEB开发 为什么要减少请求数,如何减少请求数!

    http请求头的数据量 [声明] 转载  原文出处:http://www.blogjava.net/BearRui/. 谢谢我们先分析下请求头,看看每次请求都带了那些额外的数据.下面是监控的googl ...