通过活动与服务沟通

时间:2013-05-30 17:35:49

标签: java android android-service android-binder

我正在尝试与服务进行通信。我找到了Android Guide

我在第一个例子中确实喜欢但是我有一个错误:

  

“java.lang.RuntimeException:无法绑定到服务   com.example.internetcall.MyService@41763970 with Intent {   cmp = com.example.internetcall / .MyService}:   java.lang.NullPointerException:println需要一条消息“。

这是活动:

public class StartService extends Activity{

String telephoneNumber;
TextView statusTextView, numberTextView;
MyService myService;
Boolean myBound;

ServiceConnection mConnection = new ServiceConnection() {

    @Override
    public void onServiceConnected(ComponentName arg0, IBinder arg1) {
        Log.i("bnf","qui");
        LocalBinder binder = (LocalBinder) arg1;
        myService = binder.getService();
        myBound = true;
    }

    @Override
    public void onServiceDisconnected(ComponentName arg0) {
        myBound = false;
    }
};

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.start_service_layout);

    statusTextView = (TextView) this.findViewById(R.id.statusTextView);
    numberTextView = (TextView) this.findViewById(R.id.numberTextView);

    Intent i = this.getIntent();
    telephoneNumber = i.getStringExtra("number");

    numberTextView.setText(telephoneNumber);

    if(isMyServiceRunning()){
        statusTextView.setText("Online");
        statusTextView.setTextColor(Color.GREEN);
    }else{
        statusTextView.setText("Offline");
        statusTextView.setTextColor(Color.RED);
    }

    Intent intent = new Intent(this, MyService.class);
    bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

    //SupportClass.myService.setNumber(telephoneNumber);

}

private boolean isMyServiceRunning() {
    ActivityManager manager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
    for (RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
        if ("com.example.internetcall.MyService".equals(service.service.getClassName().toString())) {
             return true;
        }
    }
    return false;
}



}

这是MyService:

public class MyService extends Service{

MyWebSocket mws;
private final IBinder mBinder = new LocalBinder();
Boolean onCall;
String telephoneNumber;
String myTelephoneNumber = null;

@Override
public IBinder onBind(Intent arg0) {
    Log.i("bnf",arg0.getStringExtra("number"));
    return mBinder;
}

public class LocalBinder extends Binder {
    MyService getService() {
        Log.i("bnf","localbinder");
        // Return this instance of LocalService so clients can call public methods
        return MyService.this;
    }
}

有人知道这个问题的解决方案吗?

如果我做了一些语法错误,我很抱歉,但我不太懂英语。

1 个答案:

答案 0 :(得分:2)

您在Log.i("bnf",arg0.getStringExtra("number")); arg0.getStringExtra("number")发生的异常为空。您没有在意图中传递字符串“number”来绑定服务。