代码很简单,就是一个简单的按钮,但是我非得点2次,myService的值才不为null。
点一次内部那个onServiceConnected中的getService()其实已经返回了,但变量不知道为什么就是传不到Activity1里的myService里,必须点第二次才传得出去,我实在没辙了!!package com.jzp.sample;import java.security.PublicKey;import com.jzp.sample.R;import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.*;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;public class Activity1 extends Activity {
@Override
protected void onStart() {
// TODO Auto-generated method stub
super.onStart();
} MyService myService = null; /** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity1);
Button button = (Button) this.findViewById(R.id.button1);
button.setOnClickListener(new OnClickListener() { @Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent intent = new Intent(Activity1.this, MyService.class);
bindService(intent, new ServiceConnection() { @Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
myService = null;
} @Override
public void onServiceConnected(ComponentName arg0,
IBinder arg1) {
// TODO Auto-generated method stub
myService = ((MyService.MyBinder) arg1).getService();
Toast.makeText(Activity1.this, "connected",
Toast.LENGTH_LONG).show();
}
}, BIND_AUTO_CREATE); if (myService != null)
Toast.makeText(Activity1.this, "123", Toast.LENGTH_LONG)
.show();
}
}); }
}