我正在尝试与服务进行通信。我找到了这个Android 指南。
我确实喜欢第一个示例,但我有一个错误:
“java.lang.RuntimeException:无法使用 Intent { cmp=com.example.internetcall/.MyService } 绑定到服务 com.example.internetcall.MyService@41763970: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;
}
}
这是我的服务:
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;
}
}
有人知道这个问题的解决方案吗?
如果我犯了一些语法错误,我很抱歉,但我不太懂英语。