服务绑定到活动

时间:2010-05-11 20:55:51

标签: android

这是我的代码:

public class MainActivity extends Activity {
    private ComponentName mService;
    private Servicio serviceBinder;

    private ServiceConnection mConnection = new ServiceConnection() {
           public void onServiceConnected(ComponentName className, IBinder service) {
             serviceBinder = ((Servicio.MyBinder)service).getService();
           }

           public void onServiceDisconnected(ComponentName className) {
             serviceBinder = null;
           }
        };

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

        Intent bindIntent = new Intent(this, Servicio.class);
        bindService(bindIntent, mConnection, Context.BIND_AUTO_CREATE);
    }

    @Override
    protected void onStart() {
        serviceBinder.somethingThatTakesTooMuch();
        super.onStart();
    }



public class Servicio extends Service {
    private final IBinder binder = new MyBinder();

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

    public int somethingThatTakesTooMuch() {
        return 1;
    }

    public class MyBinder extends Binder {
          Servicio getService() {
            return Servicio.this;
          }
    }

当我跑的时候, 它在这一行得到一个NullPointerException:

serviceBinder.somethingThatTakesTooMuch();

1 个答案:

答案 0 :(得分:5)

在与服务的连接完成之前,正在调用onStart。这不是即时的。

您只能保证在调用onServiceConnected后连接服务。只有这样才能在serviceBinder上调用方法。

尝试在serviceBinder.somethingThatTakesTooMuch()

之后的行上致电serviceBinder = ((Servicio.MyBinder)service).getService();