package com.example.studyReturn; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import android.widget.Toast; public class TestService extends Service { @Override public IBinder onBind(Intent intent) { System.out.print("服務onbind"); //經過綁定服務過來的返回給onServiceConnected方法 return new MyBinder(); } private class MyBinder extends Binder implements IServer { @Override public void callSer(String name) { //這裏調用服務裏面的方法 serMethod(name); } public void otherMehod() { //其餘方法;若是須要暴漏給外面就去接口去加方法 } } @Override public void onCreate() { System.out.println("服務被開啓了"); super.onCreate(); } @Override public void onDestroy() { System.out.println("服務銷燬了"); super.onDestroy(); } public void serMethod(String name) { Toast.makeText(getApplicationContext(), "服務裏面的方法:"+name, Toast.LENGTH_SHORT).show();; } }
##配置清單 <service android:name=".TestService"></service>
##抽取接口android
package com.example.studyReturn; public interface IServer { public void callSer(String name); //服務中須要暴漏的方法放在接口中 }
public void testBindService(View view) { Intent intent = new Intent(this, TestService.class); MyConn myconn = new MyConn(); bindService(intent, myconn, BIND_AUTO_CREATE); //服務若是不存在則建立 } private class MyConn implements ServiceConnection { public void onServiceConnected(ComponentName name, IBinder ibinder) { //服務中onBind方法返回 is = (IServer) ibinder; } @Override public void onServiceDisconnected(ComponentName arg0) { } } public void callSerService(View view) { //這裏就能夠經過is調用服務裏面的方法了 is.callSer("hahahah"); }