首先写个类继承Service 在清单文件中注册
Activity与服务连接 重写onBinder 方法
···
···
布局文件xml
···
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="{relativePackage}.{activityClass}" >
···
*************MainActivity中*************
···
package com.example.test23_bindsecevice;
import com.example.test23_bindsecevice.BindService.MyBinder;
import android.app.Activity;
import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
public class MainActivity extends Activity {
private MyConnection conn;
MyBinder myBinder;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
@Override
protected void onDestroy() {
super.onDestroy();
//把service关闭 解除跟当前Activiy的绑定
unbindService(conn);
}
public void start(View v){
Intent service = new Intent(this,BindService.class);
//通过绑定的方式开启service
conn = new MyConnection();
//使用bindService 开启反服务
//参数 1. intent 包含要启动的service
//2. ServiceConnection接口 通过它可以接受服务开启或者停止的消息
//3.开启服务时操作的选项 一般传入BIND_AUTO_CREATE自动创建service
bindService(service, conn, BIND_AUTO_CREATE);//绑定存在自动创建
}
public void stop(View v){
//使用bindService开启服务 要是用unbindService停止
unbindService(conn);
}
public void method(View v){
//BindService service = new BindService();
// service.showToast("12112");
myBinder.method("dfdg");
myBinder.showToast2("4512") ;
}
private class MyConnection implements ServiceConnection{
@Override//当服务与Activity 连接时建立
public void onServiceConnected(ComponentName name, IBinder service) {
//只有当service onbind方法返回值不为null 调用
Log.e("TAG", "onServiceConnected");
myBinder=(MyBinder) service;
}
@Override
public void onServiceDisconnected(ComponentName name) {
Log.e("TAG", "onServiceDisconnected");
}
}
}
···
Service中*********************
···
package com.example.test23_bindsecevice;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class BindService extends Service{
@Override
public IBinder onBind(Intent intent) {
Log.e("TAG", "onBind");
return new MyBinder();
}
@Override
public void onCreate() {
Log.e("TAG", "onBind");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.e("TAG", "onStartCommand");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.e("TAG", "onDestroy");
super.onDestroy();
}
public void showToast(String s){
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
public class MyBinder extends Binder{
public void method(String s){
showToast(s);
}
public void showToast2(String s){
Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT).show();
}
}
}
···