Android 通過介面的方式去呼叫服務裡面的方法
阿新 • • 發佈:2019-02-03
public class MainActivity extends AppCompatActivity { private MyConn conn; private Iservice myBinder; // 我定義的中間人物件 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Intent intent = new Intent(this, DemoService.class); //連線服務 conn = new MyConn(); bindService(intent, conn, BIND_AUTO_CREATE); } //點選按鈕呼叫服務裡面banzheng的方法 public void click(View v) { myBinder.callBanZheng(100000); } //監視服務的狀態 private class MyConn implements ServiceConnection{ //當服務連線成功呼叫 @Override public void onServiceConnected(ComponentName name, IBinder service) { //獲取中間人物件 myBinder = (Iservice) service; } //失去連線 @Override public void onServiceDisconnected(ComponentName name) { } } @Override protected void onDestroy() { //當Activity銷燬的時候 解綁服務 unbindService(conn); super.onDestroy(); } }
public class DemoService extends Service { private static final String TAG = "jojp"; public DemoService() { } // 把我定義的中間人物件返回 @Override public IBinder onBind(Intent intent) { // TODO: Return the communication channel to the service. // throw new UnsupportedOperationException("Not yet implemented"); return new MyBinder(); } //banzheng的方法 public void banZheng(int money) { if (money > 1000) { Toast.makeText(getApplicationContext(), "banZheng", Toast.LENGTH_SHORT).show(); } else { Toast.makeText(getApplicationContext(), "banZhengFail", Toast.LENGTH_SHORT).show(); } } //打麻將的方法 public void playMaJiang() { Log.d(TAG, "playMaJiang: "); } //洗桑拿的方法 public void sangNa() { Log.d(TAG, "sangNa: "); } private class MyBinder extends Binder implements Iservice{ @Override public void callBanZheng(int money) { //呼叫banzheng的方法 banZheng(money); } public void callPlayMaJiang() { //呼叫playMaJiang的方法 playMaJiang(); } public void callSangNa() { //呼叫洗桑拿的方法 sangNa(); } } }
public interface Iservice {
//把領導想暴露的方法都定義在接口裡
public void callBanZheng(int money);
}