生活随笔
收集整理的這篇文章主要介紹了
Android服务二 创建绑定服务
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
若對AIDL感興趣,請參考跨進程通信二 AIDL
綁定服務
Ibinder實現綁定服務
功能:主要為了實現組件與服務的交互,在綁定的組件可以調用服務端的功能函數
package service;import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import HttpURL.HttpUtil;/*** 創建綁定服務:通過繼承Binder類,來為客戶端提供IBinder接口(本地應用且為單進程)*/
public class MyService extends Service {IBinder mIBinder = new MyBinder();public class MyBinder extends Binder {public BinderService getBinderService(){return BinderService.this;}}@Overridepublic void onCreate() {}@Overridepublic IBinder onBind(final Intent intent) {new Thread(new Runnable() {@Overridepublic void run() {HttpUtil.downloadPicture(intent.getStringExtra("address"));}}).start();return mIBinder;}@Overridepublic boolean onUnbind(Intent intent) {return true;}@Overridepublic void onRebind(Intent intent) {}@Overridepublic void onDestroy() {}
}
public ServiceConnection serviceConnection = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {BinderService.MyBinder myBinder = (BinderService.MyBinder) service;bind_service = myBinder.getBinderService();}@Overridepublic void onServiceDisconnected(ComponentName name) {}
};@Override
protected void onStart() {super.onStart();String address = "https://img-blog.csdn.net/20160527205804527";Intent intent = new Intent(this, BinderService.class);intent.putExtra("address", address);bindService(intent, serviceConnection, BIND_AUTO_CREATE);}@Overrideprotected void onStop() {super.onStop();unbindService(serviceConnection);
}
Messenger實現綁定服務
功能:為了實現跨進程通信,讓客戶端與服務端實現雙向通信
效果圖
配置文件
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"package="com.android.client" ><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=".MessengerService"android:process=":remote"></service></application></manifest>
布局
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:paddingBottom="@dimen/activity_vertical_margin"tools:context=".MainActivity"><EditText
android:id="@+id/num1"android:layout_width="100dp"android:layout_height="wrap_content" /><TextView
android:id="@+id/plus"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="+"android:layout_toRightOf="@id/num1"android:textSize="20sp"/><EditText
android:id="@+id/num2"android:layout_width="100dp"android:layout_height="wrap_content"android:layout_toRightOf="@id/plus"/><TextView
android:id="@+id/equal"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="="android:layout_toRightOf="@id/num2"android:textSize="20sp"/><EditText
android:id="@+id/sum"android:layout_width="100dp"android:layout_height="wrap_content"android:layout_toRightOf="@id/equal"android:textSize="20sp"android:editable="false"/><Button
android:id="@+id/calculate"android:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginTop="80dp"android:text="計算" /></RelativeLayout>
服務端
package com.android.client;import android.app.Service;import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;/*** 服務端*/
public class MessengerService extends Service {public static final int MSG_SUM = 1;public static final int MSG_RET = 2;public Messenger clientMessenger;public Messenger serverMessenger = new Messenger(new Handler(){@Overridepublic void handleMessage(Message msg) {switch (msg.what){case MSG_SUM:clientMessenger = msg.replyTo;Message message = Message.obtain(null,MSG_RET);message.arg1 = msg.arg1+msg.arg2;try {clientMessenger.send(message);} catch (RemoteException e) {e.printStackTrace();}break;default:handleMessage(msg);}}});@Overridepublic IBinder onBind(Intent intent) {return serverMessenger.getBinder();}@Overridepublic boolean onUnbind(Intent intent) {return true;}@Overridepublic void onRebind(Intent intent) {}}
客戶端
package com.android.client;import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;public class MainActivity extends Activity implements View.OnClickListener {public static final int MSG_SUM = 1;public static final int MSG_RET = 2;public EditText num1;public EditText num2;public EditText sum;public Button btn;public Messenger clientMessenger = new Messenger(new Handler(){@Overridepublic void handleMessage(Message msg) {switch (msg.what){case MSG_RET:sum.setText(msg.arg1+"");break;default:super.handleMessage(msg);}}});public Messenger serverMessenger;public ServiceConnection serviceConnection = new ServiceConnection() {@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {serverMessenger = new Messenger(service);}@Overridepublic void onServiceDisconnected(ComponentName name) {serverMessenger = null;}};@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);num1 = (EditText) findViewById(R.id.num1);num2 = (EditText) findViewById(R.id.num2);sum = (EditText) findViewById(R.id.sum);btn = (Button) findViewById(R.id.calculate);Intent intent = new Intent(this,MessengerService.class);bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE);btn.setOnClickListener(this);}@Overrideprotected void onDestroy() {super.onDestroy();unbindService(serviceConnection);}@Overridepublic void onClick(View v) {if(num1.getText().toString().equals("") ||num2.getText().toString().equals("") ){Toast.makeText(this,"請輸入數值",Toast.LENGTH_SHORT).show();return;}Message message = Message.obtain(null,MSG_SUM,Integer.parseInt(num1.getText().toString()),Integer.parseInt(num2.getText().toString()));message.replyTo = clientMessenger;try {serverMessenger.send(message);} catch (RemoteException e) {e.printStackTrace();}}
}
參考文章:
[1]https://developer.android.com/guide/components/bound-services.html
[2]https://developer.android.com/reference/android/app/Service.html
[3]http://xwangly.iteye.com/blog/1109424
[4]http://blog.csdn.net/lmj623565791/article/details/47017485
package service;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import HttpURL.HttpUtil;
/*** 創建綁定服務:通過繼承Binder類,來為客戶端提供IBinder接口(本地應用且為單進程)*/
public class MyService extends Service {IBinder mIBinder =
new MyBinder();
public class MyBinder extends Binder {public MyService
getBinderService(){
return MyService.
this;}}
@Overridepublic void onCreate() {}
@Overridepublic IBinder
onBind(
final Intent intent) {
new Thread(
new Runnable() {
@Overridepublic void run() {HttpUtil.downloadPicture(intent.getStringExtra(
"address"));}}).start();
return mIBinder;}
@Overridepublic boolean onUnbind(Intent intent) {
return true;}
@Overridepublic void onRebind(Intent intent) {}
@Overridepublic void onDestroy() {}
}
總結
以上是生活随笔為你收集整理的Android服务二 创建绑定服务的全部內容,希望文章能夠幫你解決所遇到的問題。
如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。