1

我正在关注绑定服务教程,这是我的代码

服务器

public class Server extends Service {

IBinder mBinder = new LocalBinder();

@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

public class LocalBinder extends Binder {
    public Server getServerInstance() {
        return Server.this;
    }
}

public String getTime() {
    SimpleDateFormat mDateFormat = new SimpleDateFormat(
            "yyyy-MM-dd HH:mm:ss");
    return mDateFormat.format(new Date());
 }
}

客户

public class Client extends Activity {

boolean mBounded;
Server mServer;
TextView text;
Button button;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    text = (TextView) findViewById(R.id.text);
    button = (Button) findViewById(R.id.button);
    button.setOnClickListener(new OnClickListener() {

        public void onClick(View v) {
            text.setText(mServer.getTime());
        }
    });
}

@Override
protected void onStart() {
    super.onStart();
    Intent mIntent = new Intent(this, Server.class);
    bindService(mIntent, mConnection, BIND_AUTO_CREATE);
};

ServiceConnection mConnection = new ServiceConnection() {

    public void onServiceDisconnected(ComponentName name) {
        Toast.makeText(Client.this, "Service is disconnected", 1000).show();
        mBounded = false;
        mServer = null;
    }

    public void onServiceConnected(ComponentName name, IBinder service) {
        Toast.makeText(Client.this, "Service is connected", 1000).show();
        mBounded = true;
        LocalBinder mLocalBinder = (LocalBinder) service;
        mServer = mLocalBinder.getServerInstance();
    }
};

@Override
protected void onStop() {
    super.onStop();
    if (mBounded) {
        unbindService(mConnection);
        mBounded = false;
    }
};
}

它工作正常。

如果我改变

LocalBinder mLocalBinder = (LocalBinder) service;
        mServer = mLocalBinder.getServerInstance();

mServer = new Server();

它也可以正常工作。

那么在 Server 类中创建嵌套的 LocalBinder 类并创建 getServerInstance() 方法来获取它的引用的实际需要是什么,如果我们可以使用传统的 java 方法通过 new 关键字直接初始化它的对象,我在其他一些例子中也看到了.我无法弄清楚,任何专家可以帮助我吗?

4

0 回答 0