使用嵌套类绑定服务

时间:2015-09-30 09:48:51

标签: android bindservice

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

服务器

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关键字直接初始化它的对象,我也看到了它其他一些例子。我无法解决,任何专家都可以帮助我吗?

0 个答案:

没有答案