1. 程式人生 > >在Activity中呼叫Service的非靜態方法

在Activity中呼叫Service的非靜態方法

先上程式碼:

public class MyService extends Service {
    public MyService() {
    }

    private long mServiceCreatTime;


    @Override
    public void onCreate() {
        super.onCreate();
        mServiceCreatTime = System.currentTimeMillis();
    }

    @Override
    public IBinder onBind(Intent intent) {
        return
new MyBinder(); } public class MyBinder extends Binder{ public String getRunningTime(){ return MyService.this.getRunningTime(); } } public String getRunningTime(){ long runningTime = System.currentTimeMillis()-mServiceCreatTime; return String.format("服務已執行: %s"
,dateFormat(runningTime)); } public String dateFormat(long timeMillions){ Date date = new Date(timeMillions); SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss"); return sdf.format(date); } }
public class MainActivity extends AppCompatActivity {

    private
TextView mTvRunningTime; private MyService.MyBinder mMyBinder; private Handler mHandler = new Handler(); @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mTvRunningTime = (TextView) findViewById(R.id.tv_running_time); //繫結服務 Intent intent = new Intent(this,MyService.class); MyServiceConnection myServiceConnection = new MyServiceConnection(); bindService(intent,myServiceConnection, Context.BIND_AUTO_CREATE); refreshRunningTime(); } private void refreshRunningTime(){ Timer timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { mHandler.post(new Runnable() { @Override public void run() { //通過MyBinder呼叫MyService中的getRunningTime()方法 if (mMyBinder!=null) { mTvRunningTime.setText(mMyBinder.getRunningTime()); } } }); } },0,1000); } private class MyServiceConnection implements ServiceConnection{ @Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) { mMyBinder = (MyService.MyBinder) iBinder; } @Override public void onServiceDisconnected(ComponentName componentName) { } } }

實現步驟:
1.在Service中建立一個Binder的子類MyBinder, 在MyBinder中呼叫MyService需要提供給外部呼叫的getRuuningTime()方法;
2.在MyService的onBind()方法中返回MyBinder的例項;
3.在Activity中建立一個ServiceConnection的實現類MyServiceConnection;
4.通過bindService()啟動MyService;
5.在MyServiceConnection的onServiceConnected()方法中將iBinder強轉為MyBinder, 這樣就可以通過MyBinder呼叫MyService中的getRunningTime()方法了。