package com.example.test23_bindservice;
import com.example.test23_bindservice.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.Menu; import android.view.MenuItem; import android.view.View;
public class MainActivity extends Activity { private MyConnection conn; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onDestroy() { super.onDestroy(); //把Service关闭,解除跟当前Activity的绑定 unbindService(conn); } public void start(View v){ Intent service = new Intent(this,BindService.class); //通过bind方法实现service方法 conn = new MyConnection(); //使用bindService开启的服务 //参数1:包含要启动个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 callServiceMethod(View v){ BindService service = new BindService(); service.showToast("hello"); } private class MyConnection implements ServiceConnection{ private MyBinder myBinder; @Override 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"); } }
}
BindService类
package com.example.test23_bindservice;
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", "onCreate"); 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); } public class MyBinder extends Binder{ public void callShowToast(String s){ showToast(s); } public void showToast2(String s){ Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT); } } }
|