最近在学习 Android Studio 和eclipse还是有很多不同的地方, 正好用到 AIDL, 发现有些不同的地方,第一次在CSDN写这个,写的不好,希望大家多见谅,有错的地方欢迎大家给我留言,我会虚心的接受,并予以改正,下边进入正题.
转载请注明出处: http://blog.csdn.net/zhaoshiyu1/article/details/50831798
感谢郭老师的文章,帮助我很多http://blog.csdn.net/guolin_blog/article/details/11952435
新建一个module,命名ServiceTest
public class MainActivity extends AppCompatActivity implements View.OnClickListener {
private Button startService;
private Button stopService;
private Button bindService;
private Button unbindService;
private MyService.MyBinder myBinder;
private boolean isBinder = false;
private MyAIDLService myAIDLService;
//ServiceConnection的匿名类
private ServiceConnection connection = new ServiceConnection() {
// 这两个方法分别会在Activity与Service建立关联和解除关联的时候调用
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
// myBinder = (MyService.MyBinder) service;
// myBinder.startDownload();
myAIDLService = MyAIDLService.Stub.asInterface(service);
try {
int result = myAIDLService.plus(3, 5);
String upperStr = myAIDLService.toUpperCase("hello world");
Log.d("TAG", "result is " + result);
Log.d("TAG", "upperStr is " + upperStr);
} catch (RemoteException e) {
e.printStackTrace();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startService = (Button) findViewById(R.id.start_service);
stopService = (Button) findViewById(R.id.stop_service);
bindService = (Button) findViewById(R.id.bind_service);
unbindService = (Button) findViewById(R.id.unbind_service);
startService.setOnClickListener(this);
stopService.setOnClickListener(this);
bindService.setOnClickListener(this);
unbindService.setOnClickListener(this);
Log.d("MyService", "MainActivity thread id is " + Thread.currentThread().getId());
Log.d("TAG", "process id is " + Process.myPid());
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_service:
Intent startIntent = new Intent(this, MyService.class);
startService(startIntent);
break;
case R.id.stop_service:
Log.d("MyService", "click Stop Service button");
Intent stopIntent = new Intent(this, MyService.class);
stopService(stopIntent);
break;
case R.id.bind_service:
if (isBinder == false) {
Intent bindIntent = new Intent(this, MyService.class);
bindService(bindIntent, connection, BIND_AUTO_CREATE);
isBinder = true;
}
break;
case R.id.unbind_service:
if (isBinder == true) {
Log.d("MyService", "click Unbind Service button");
unbindService(connection);
isBinder = false;
}
break;
default:
break;
}
}
}
新建一个 MyService 类
public class MyService extends Service {
public static final String TAG = "MyService";
private MyBinder mBinder = new MyBinder();
// private NotificationManager notificationManager = null;
@Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
//throw new UnsupportedOperationException("Not yet implemented");
// return mBinder;
return mBinder2;
}
MyAIDLService.Stub mBinder2 = new MyAIDLService.Stub() {
@Override
public String toUpperCase(String str) throws RemoteException {
if (str != null) {
return str.toUpperCase();
}
return null;
}
@Override
public int plus(int a, int b) throws RemoteException {
return a + b;
}
};
@Override
public void onCreate() {
super.onCreate();
//service线程休眠会导致ANR,
/*
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
*/
Log.d("MyService", "MyService thread id is " + Thread.currentThread().getId());
Log.d(TAG, "onCreaMyte() executed");
Log.d("TAG", "process id is " + Process.myPid());
Notification.Builder builder = new Notification.Builder(this);
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0,
notificationIntent, PendingIntent.FLAG_ONE_SHOT);
builder.setContentTitle("这是通知的标题")
.setContentIntent(pendingIntent)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentText("这是通知的内容");
//将Notification变为前台service
startForeground(1, builder.build());
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d(TAG, "onStartCommand() executed");
new Thread(new Runnable() {
@Override
public void run() {
// 开始执行后台任务
}
}).start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
Log.d(TAG, "onDestroy() executed");
}
class MyBinder extends Binder {
public void startDownload() {
Log.d("TAG", "startDownload() executed");
new Thread(new Runnable() {
@Override
public void run() {
// 执行具体的下载任务
}
}).start();
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.yu.servicetest">
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/AppTheme">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".MyService"
android:enabled="true"
android:exported="true"
android:process=":remote">
<intent-filter>
<action android:name="com.yu.servicetest.MyAIDLService"/>
</intent-filter>
</service>
</application>
</manifest>
activity_main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/start_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Start Service" />
<Button
android:id="@+id/stop_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Stop Service" />
<Button
android:id="@+id/bind_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Bind Service" />
<Button
android:id="@+id/unbind_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Unbind Service"
/>
</LinearLayout>
下面是重点,就是和eclipse不太一样的地方.....
新建一个AIDL
点击finish完成.
编辑 MyAIDLService.aidl
// MyAIDLService.aidl
package com.yu.servicetest;
// Declare any non-default types here with import statements
interface MyAIDLService {
/**
* Demonstrates some basic types that you can use as parameters
* and return values in AIDL.
*/
int plus(int a,int b);
String toUpperCase(String str);
// void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat,
// double aDouble, String aString);
}
之后make project 一下,
看一下,这个路径下是否 自动生成了接口....
在新建一个Module 用于访问servicetest,命名为ClientTest
MainActivity
public class MainActivity extends AppCompatActivity {
private MyAIDLService myAIDLService;
private ServiceConnection connection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
myAIDLService = MyAIDLService.Stub.asInterface(service);
try {
int result = myAIDLService.plus(50, 50);
String upperStr = myAIDLService.toUpperCase("comes from ClientTest");
Log.d("TAG", "result is " + result);
Log.d("TAG", "upperStr is " + upperStr);
} catch (RemoteException e) {
e.printStackTrace();
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Button bindService = (Button) findViewById(R.id.bind_service);
bindService.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Intent intent = new Intent("com.yu.servicetest.MyAIDLService");
bindService(intent, connection, BIND_AUTO_CREATE);
}
});
}
}
activity_main
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:id="@+id/bind_service"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Bind Service" />
</LinearLayout>
和eclipse不同的地方来了.....
将上个Module写好的aidl文件夹,直接复制到ClientTest Module下的main文件夹下,和java同级
make project 一下
在gen目录下,会生成与serviceTest同样的接口类
最后就是运行下ServiceTest 绑定服务 ,然后运行下 ClientTest.点击按钮
要是有什么写的不对的地方,请给我留言,我会及时改正的,谢谢,
再次感谢郭老师的文章,写的非常好