1. 布局是几个简单的Button
<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:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context="com.silion.servicesample.MainActivity"
android:orientation="vertical">
<Button
android:id="@+id/startService"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:text="@string/start_service"/>
<Button
android:id="@+id/stopService"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:text="@string/stop_service"/>
<Button
android:id="@+id/bindService"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:text="@string/bind_service"/>
<Button
android:id="@+id/unbindService"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:text="@string/unbind_service"/>
<Button
android:id="@+id/foregroundService"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:text="@string/foreground_service"/>
<Button
android:id="@+id/startRemoteService"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:text="@string/start_remote_service"/>
<Button
android:id="@+id/bindRemoteService"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:text="@string/bind_remote_service"/>
</LinearLayout>
2. Mainactivity.java
package com.silion.servicesample;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.*;
import android.os.Process;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
private Context mApplication;
private IMyAidlInterface mAidlService;
View.OnClickListener mClickListener = new View.OnClickListener() {
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.startService: {
Intent normalServiceIntent = new Intent();
normalServiceIntent.setClass(MainActivity.this, NormalService.class);
startService(normalServiceIntent);
break;
}
case R.id.stopService: {
Intent normalServiceIntent = new Intent();
normalServiceIntent.setClass(MainActivity.this, NormalService.class);
stopService(normalServiceIntent);
break;
}
case R.id.bindService: {
Intent normalServiceIntent = new Intent();
normalServiceIntent.setClass(MainActivity.this, NormalService.class);
mApplication.bindService(normalServiceIntent, mNormalServiceConnection, BIND_AUTO_CREATE);
break;
}
case R.id.unbindService: {
Intent normalServiceIntent = new Intent();
normalServiceIntent.setClass(MainActivity.this, NormalService.class);
try {
mApplication.unbindService(mNormalServiceConnection);
} catch (Exception e) {
Toast.makeText(mApplication, "Service is unBinder", Toast.LENGTH_SHORT).show();
}
break;
}
case R.id.foregroundService: {
Intent normalServiceIntent = new Intent();
normalServiceIntent.setClass(MainActivity.this, ForegroundService.class);
startService(normalServiceIntent);
break;
}
case R.id.startRemoteService: {
Intent remoteServiceIntent = new Intent();
remoteServiceIntent.setClass(MainActivity.this, RemoteService.class);
startService(remoteServiceIntent);
break;
}
case R.id.bindRemoteService: {
Intent remoteServiceIntent = new Intent();
remoteServiceIntent.setClass(MainActivity.this, RemoteService.class);
bindService(remoteServiceIntent, mRemoteServiceConnection, BIND_AUTO_CREATE);
break;
}
default:
break;
}
}
};
ServiceConnection mNormalServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
Binder binder = (Binder) service;
Parcel data = Parcel.obtain();
data.writeString("from activity");
Parcel reply = Parcel.obtain();
try {
binder.transact(0, data, reply, 0);
} catch (RemoteException e) {
e.printStackTrace();
}
android.util.Log.v("slong.liang", "MainActivity onServiceConnected reply = " + reply.readString());
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
ServiceConnection mRemoteServiceConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mAidlService = IMyAidlInterface.Stub.asInterface(service);
try {
int result = mAidlService.plus(3, 5);
String upperString = mAidlService.toUpperCase("hello aidl");
android.util.Log.v("slong.liang", "MainActivity : mRemoteServiceConnection result = " + result);
android.util.Log.v("slong.liang", "MainActivity : mRemoteServiceConnection upperString = " + upperString);
} catch (RemoteException e) {
e.printStackTrace();
}
}
@Override
public void onServiceDisconnected(ComponentName name) {
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mApplication = getApplicationContext();
Button startServiceButton = (Button) findViewById(R.id.startService);
startServiceButton.setOnClickListener(mClickListener);
Button stopServiceButton = (Button) findViewById(R.id.stopService);
stopServiceButton.setOnClickListener(mClickListener);
Button bindServiceButton = (Button) findViewById(R.id.bindService);
bindServiceButton.setOnClickListener(mClickListener);
Button unBinderServiceButton = (Button) findViewById(R.id.unbindService);
unBinderServiceButton.setOnClickListener(mClickListener);
Button foregroundServiceButton = (Button) findViewById(R.id.foregroundService);
foregroundServiceButton.setOnClickListener(mClickListener);
Button startRemoteServiceButton = (Button) findViewById(R.id.startRemoteService);
startRemoteServiceButton.setOnClickListener(mClickListener);
Button bindRemoteServiceButton = (Button) findViewById(R.id.bindRemoteService);
bindRemoteServiceButton.setOnClickListener(mClickListener);
android.util.Log.v("slong.liang", "MainAcitivity : onCreate process id is " + Process.myPid());
}
}
3. NormalService.java 继承于 Service
package com.silion.servicesample;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
public class NormalService extends Service {
MyBinder binder = new MyBinder();
public NormalService() {
}
@Override
public void onCreate() {
android.util.Log.v("slong.liang", "NormalService onCreate");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
android.util.Log.v("slong.liang", "NormalService onStartCommand");
}
}).start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
android.util.Log.v("slong.liang", "NormalService onDestory");
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
android.util.Log.v("slong.liang", "NormalService onBind");
return binder;
}
class MyBinder extends Binder {
@Override
protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
android.util.Log.v("slong.liang", "NormalService MyBinder data = " + data);
reply.writeString("from normalService");
return super.onTransact(code, data, reply, flags);
}
}
}
4. ForegroundService.java 继承于Service
package com.silion.servicesample;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.os.Parcel;
import android.os.RemoteException;
/**
* Created by silion on 2015/9/29.
*/
public class ForegroundService extends Service{
MyBinder binder = new MyBinder();
public ForegroundService() {
}
@Override
public void onCreate() {
android.util.Log.v("slong.liang", "ForegroundService onCreate");
super.onCreate();
Notification notification = new Notification(R.drawable.ic_launcher,
getResources().getString(R.string.notification_ticker_text), System.currentTimeMillis());
Intent notificationIntent = new Intent(this, MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0);
notification.setLatestEventInfo(this, getResources().getString(R.string.notification_content_title),
getResources().getString(R.string.notification_content_text), pendingIntent);
startForeground(1, notification);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
new Thread(new Runnable() {
@Override
public void run() {
android.util.Log.v("slong.liang", "ForegroundService onStartCommand");
}
}).start();
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
android.util.Log.v("slong.liang", "ForegroundService onDestory");
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
android.util.Log.v("slong.liang", "ForegroundService onBind");
return binder;
}
class MyBinder extends Binder {
@Override
protected boolean onTransact(int code, Parcel data, Parcel reply, int flags) throws RemoteException {
android.util.Log.v("slong.liang", "ForegroundService MyBinder data = " + data);
reply.writeString("from ForegroundService");
return super.onTransact(code, data, reply, flags);
}
}
}
5. RemoteService.java继承于Service
package com.silion.servicesample;
import android.app.Service;
import android.content.Intent;
import android.os.*;
import android.os.Process;
import android.support.v4.app.INotificationSideChannel;
public class RemoteService extends Service {
public RemoteService() {
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
@Override
public void onCreate() {
super.onCreate();
android.util.Log.v("slong.liang", "RemoteService : onCreate process id is " + Process.myPid());
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
android.util.Log.v("slong.liang", "RemoteServie : onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
}
IMyAidlInterface.Stub mBinder = new IMyAidlInterface.Stub() {
@Override
public void basicTypes(int anInt, long aLong, boolean aBoolean, float aFloat, double aDouble, String aString) throws RemoteException {
}
@Override
public int plus(int a, int b) throws RemoteException {
return a + b;
}
@Override
public String toUpperCase(String str) throws RemoteException {
if(str != null) {
return str.toUpperCase();
}
return null;
}
};
}
6. IMyAidlInterface.aidl AIDL实现跨进程间通信 -- Android Studio new AIDL 然后rebuild 会自动生成 .java文件
// IMyAidlInterface.aidl
package com.silion.servicesample;
// Declare any non-default types here with import statements
interface IMyAidlInterface {
/**
* 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);
int plus(int a, int b);
String toUpperCase(String str);
}
7. 最后还要注册
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.silion.servicesample" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/title_activity_main" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".NormalService"
android:enabled="true"
android:exported="true" >
</service>
<service
android:name=".ForegroundService"
android:enabled="true"
android:exported="true" >
</service>
<service
android:name=".RemoteService"
android:enabled="true"
android:exported="true"
android:process=":remote" >
<intent-filter>
<action android:name="com.silion.servicesample.RemoteService"/>
</intent-filter>
</service>
</application>
</manifest>