package my.yaner.service;
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.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
/**绑定服务测试*/
public class BindServiceActivity extends Activity {
private MatchService mathService;
private boolean isBound = false;
TextView labelView;
protected void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
LinearLayout linearlayout = new LinearLayout(this);
labelView = new TextView(this);
linearlayout.addView(labelView);
Button btnBind = new Button(this);
btnBind.setText("服务绑定");
linearlayout.addView(btnBind);
Button btnCancelBind = new Button(this);
btnCancelBind.setText("取消绑定");
linearlayout.addView(btnCancelBind);
Button btnPlus = new Button(this);
btnPlus.setText("加法运算");
linearlayout.addView(btnPlus);
setContentView(linearlayout);
//绑定按键监听
btnBind.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(!isBound){
final Intent serviceIntent = new Intent(BindServiceActivity.this, MatchService.class);
bindService(serviceIntent, mConnection, Context.BIND_AUTO_CREATE);
isBound = true;
}
}
});
//取消绑定
btnCancelBind.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(isBound){
isBound = false;
unbindService(mConnection);
mathService = null;
}
}
});
//加法运算
btnPlus.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
if(mathService == null){
labelView.setText("未绑定服务");
return;
}
long a = Math.round(Math.random() * 100);
long b = Math.round(Math.random() * 100);
long result = mathService.add(a, b);
String msg = String.valueOf(a) + "+" + String.valueOf(b)
+ "=" + String.valueOf(result);
labelView.setText(msg);
}
});
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceDisconnected(ComponentName name) {
mathService = null;
}
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
mathService = ((MatchService.LocalBinder)service).getService();
}
};
}
====
package my.yaner.service;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.widget.Toast;
public class MatchService extends Service {
private final IBinder mBinder = new LocalBinder();
public class LocalBinder extends Binder{
MatchService getService(){
return MatchService.this;
}
}
@Override
public IBinder onBind(Intent intent) {
Toast.makeText(this, "本地绑定: MathService", Toast.LENGTH_SHORT).show();
return mBinder;
}
public boolean onUnbind(Intent intent){
Toast.makeText(this, "取消本地绑定:MathService", Toast.LENGTH_SHORT).show();
return false;
}
public long add(long a, long b){
return a + b;
}
}