服务,调用方法

import android.app.Activity;import android.content.ComponentName;import android.content.Intent;import android.content.ServiceConnection;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;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}@Overrideprotected 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,自动创建ServicebindService(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;@Overridepublic void onServiceConnected(ComponentName name, IBinder service) {//只有当Service的onBind方法返回值不为null,才会调用此方法Log.e("TAG", "onServiceConnected"); myBinder = (MyBinder) service;}@Overridepublic void onServiceDisconnected(ComponentName name) {//服务正常退出的时候不会调用此方法Log.e("TAG", "onServiceDisconnected");}}}import android.app.Service;import android.content.Intent;import android.os.Binder;importandroid.os.IBinder;import android.util.Log;

import android.widget.Toast;public class BindService extends Service{@Overridepublic IBinder onBind(Intent intent) {Log.e("TAG", "onBind");return new  MyBinder();}@Overridepublic void onCreate() {Log.e("TAG", "onCreate");super.onCreate();}@Overridepublic int onStartCommand(Intent intent, int flags, int startId) {Log.e("TAG", "onStartCommand");return super.onStartCommand(intent, flags, startId);}@Overridepublic void onDestroy() {Log.e("TAG", "onDestroy");super.onDestroy();}public void showToast(String s){Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT);}public class MyBinderextends Binder{public void callShowToast(String s){showToast(s);}public void showToast2(String s){Toast.makeText(getApplicationContext(), s, Toast.LENGTH_SHORT);}}}

你可能感兴趣的:(服务,调用方法)