簡單的Bindservice服務獲取隨機數,需要在清單檔案中註冊service

ren18234073466發表於2018-12-06
Activity中繫結服務
//宣告中間人
 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()

BindService

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);
    }
    
}

相關文章