簡單的Bindservice服務獲取隨機數,需要在清單檔案中註冊service
阿新 • • 發佈:2018-12-21
1.MainActivity
//宣告中間人 private BindService.IBind iBind; Intent service=new Intent(MainActivity.this,BindService.class); ServiceConnection conn=new ServiceConnection() { @Override public void onServiceConnected(ComponentName name, IBinder service) { //得到中間人 iBind= (BindService.IBind) service; } @Override public void onServiceDisconnected(ComponentName name) { } }; //繫結服務 bindService(service,conn,BIND_AUTO_CREATE); //通過中間人呼叫服務中獲取隨機數的方法 int num = iBind.getNum()
2.建立service類繼承service
package com.example.renzhili20181205.service; import android.app.Service; import android.content.Intent; import android.os.Binder; import android.os.IBinder; import java.util.Random; public class BindService extends Service { private IBind iBind=new IBind(); @Override public IBinder onBind(Intent intent) { return iBind; } //定義中間人 public class IBind extends Binder{ //獲取隨機數的方法 public int getNum(){ return new Random().nextInt(999999); } } @Override public boolean onUnbind(Intent intent) { return super.onUnbind(intent); } }