Android应用组件之Service

Service的生命周期:



AIDL的用法:

1. 服务端:

1.1 MyRemoteService.java

public class MyRemoteService extends Service {

	@Override
	public IBinder onBind(Intent intent) {
		Log.e("TAG", "onBind()");
		return new StudentService();
	}
	
	@Override
	public boolean onUnbind(Intent intent) {
		Log.e("TAG", "onUnbind()");
		return super.onUnbind(intent);
	}
	
	//处理Student相关的业务逻辑类
	class StudentService extends IStudentService.Stub {
		@Override
		public Student getStudentById(int id) throws RemoteException {
			Log.e("TAG", "Service getStudentById() "+id);
			return new Student(id, "Tom", 10000);
		}
	}

}


1.2 MainActivity.java

public class MainActivity extends Activity {

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
	}
	
	//启动服务
	public void startMyService(View v) {
		Intent intent = new Intent(this, MyService.class);
		startService(intent);
		Toast.makeText(this, "start service", 0).show();
	}
	
	public void stopMyService(View v) {
		Intent intent = new Intent(this, MyService.class);
		stopService(intent);
		Toast.makeText(this, "stop service", 0).show();
	}
	
	private ServiceConnection conn;
	//绑定服务
	public void bindMyService(View v) {
		Intent intent = new Intent(this, MyService.class);
		//创建连接对象
		if(conn==null) {
			conn = new ServiceConnection() {
				@Override
				public void onServiceDisconnected(ComponentName name) {
					Log.e("TAG", "onServiceDisconnected()");
				}
				@Override
				public void onServiceConnected(ComponentName name, IBinder service) {
					Log.e("TAG", "onServiceConnected()");
				}
			};
			//绑定Service
			bindService(intent, conn, Context.BIND_AUTO_CREATE);
			
			Toast.makeText(this, "bind service", 0).show();
		} else {
			Toast.makeText(this, "已经bindservice", 0).show();
		}
		
	}
	
	//解绑服务
	public void unbindMyService(View v) {
		if(conn!=null) {
			unbindService(conn);
			conn = null;
			Toast.makeText(this, "unbind service", 0).show();
		} else {
			Toast.makeText(this, "还没有bindservice", 0).show();
		}
		
	}
	
	//在Activity死亡之前调用
	@Override
	protected void onDestroy() {
		super.onDestroy();
		if(conn!=null) {
			unbindService(conn);
			conn = null;
		}
	}
	
	
}


1.3 MyService.java

public class MyService extends Service {

	public MyService() {
		Log.e("TAG", "MyService()");
	}
	
	
	@Override
	public void onCreate() {
		super.onCreate();
		Log.e("TAG", "MyService onCreate()");
	}
	
	@Override
	public int onStartCommand(Intent intent, int flags, int startId) {
		Log.e("TAG", "MyService onStartCommand()");
		return super.onStartCommand(intent, flags, startId);
	}
	
	@Override
	public void onDestroy() {
		super.onDestroy();
		Log.e("TAG", "MyService onDestroy()");
	}
	
	@Override
	public IBinder onBind(Intent intent) {
		Log.e("TAG", "onBind()");
		return new Binder();
	}
	
	@Override
	public boolean onUnbind(Intent intent) {
		Log.e("TAG", "onUnbind()");
		return super.onUnbind(intent);
	}
}


1.4 activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="1. 测试启动本地服务"
        android:textSize="25sp" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:id="@+id/button1"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="startMyService"
            android:text="启动服务" />

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="stopMyService"
            android:text="停止服务" />
    </LinearLayout>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="2.  测试绑定本地服务"
        android:textSize="25sp" 
        android:layout_marginTop="10dp"/>

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content" >

        <Button
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="bindMyService"
            android:text="绑定服务" />

        <Button
            android:id="@+id/button2"
            android:layout_width="0dp"
            android:layout_height="wrap_content"
            android:layout_weight="1"
            android:onClick="unbindMyService"
            android:text="解绑服务" />
    </LinearLayout>
</LinearLayout>


1.5 AndroidManifest.xml

<service android:name="com.atguigu.l07_service.local.MyService"/>

<service android:name="com.atguigu.l07_service.remote.MyRemoteService">
    <intent-filter>
          <action android:name="com.atguigu.l07_service.remote.MyRemoteService.Action"/>
    </intent-filter>
</service>



2. 客户端:

2.1  MainActivity.java

public class MainActivity extends Activity {

	private EditText et_aidl_id;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		et_aidl_id = (EditText) findViewById(R.id.et_aidl_id);
	}

	private ServiceConnection conn;
	private IStudentService studentService;

	public void bindRemoteService(View v) {

		Intent intent = new Intent(
				"com.atguigu.l07_service.remote.MyRemoteService.Action");
		if (conn == null) {
			conn = new ServiceConnection() {

				@Override
				public void onServiceDisconnected(ComponentName name) {

				}

				@Override
				public void onServiceConnected(ComponentName name,
						IBinder service) {
					Log.e("TAG", "onServiceConnected()");
					studentService = IStudentService.Stub.asInterface(service);
				}
			};
			bindService(intent, conn, Context.BIND_AUTO_CREATE);
			Toast.makeText(this, "绑定Service", 0).show();
		} else {
			Toast.makeText(this, "已经绑定Service", 0).show();
		}

	}

	public void invokeRemote(View v) throws RemoteException {
		if(studentService!=null) {
			int id = Integer.parseInt(et_aidl_id.getText().toString());
			Student student = studentService.getStudentById(id);
			Toast.makeText(this, student.toString(), 0).show();
		}
	}

	public void unbindRemoteService(View v) {
		if (conn != null) {
			unbindService(conn);
			conn = null;
			studentService = null;
			Toast.makeText(this, "解绑Service", 0).show();
		} else {
			Toast.makeText(this, "还未绑定Service", 0).show();
		}
	}
}


2.2 activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="bindRemoteService"
        android:text="bind remote Service" />

    <EditText
        android:id="@+id/et_aidl_id"
        android:layout_width="fill_parent"
        android:layout_height="50dip"
        android:hint="学员ID"
        android:text="3" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="invokeRemote"
        android:text="调用远程服务端的方法" />

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="unbindRemoteService"
        android:text="unbind remote Service" />

</LinearLayout>


2.3 AndroidManifest.xml


3. 公有代码:

3.1 Student.java

public class Student  implements Parcelable{

	private int id;
	private String name;
	private double price;

	public Student(int id, String name, double price) {
		super();
		this.id = id;
		this.name = name;
		this.price = price;
	}

	public Student() {
		super();
	}

	public int getId() {
		return id;
	}

	public void setId(int id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public double getPrice() {
		return price;
	}

	public void setPrice(double price) {
		this.price = price;
	}

	@Override
	public String toString() {
		return "Student [id=" + id + ", name=" + name + ", price=" + price
				+ "]";
	}

	@Override
	public int describeContents() {
		// TODO Auto-generated method stub
		return 0;
	}

	//将当前对象的属性数据打成包: 写到包对象中
	@Override
	public void writeToParcel(Parcel dest, int flags) {
		Log.e("TAG", "打包 writeToParcel()");
		//id
		dest.writeInt(id);
		//name
		dest.writeString(name);
		//price
		dest.writeDouble(price);
	}
	
	// 添加一个静态成员,名为CREATOR,该对象实现了Parcelable.Creator接口
	public static final Parcelable.Creator<Student> CREATOR = new  Parcelable.Creator<Student>() {

		//解包: 读取包中的数据并封装成对象
		@Override
		public Student createFromParcel(Parcel source) {
			Log.e("TAG", "解包 createFromParcel()");
			//id
			int id = source.readInt();
			//name
			String name = source.readString();
			//price
			double price = source.readDouble();
			
			return new Student(id, name, price);
		}

		//返回一个指定大小的对象容器
		@Override
		public Student[] newArray(int size) {
			return new Student[size];
		}
	};

}


3.2 Student.aidl

package com.atguigu.l07_service.remote;
parcelable Student;


3.3 IStudentService.aidl

package com.atguigu.l07_service.remote;
import com.atguigu.l07_service.remote.Student;
interface IStudentService {

	Student getStudentById(int id);
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值