从活动通信到服务
Posted
技术标签:
【中文标题】从活动通信到服务【英文标题】:communicate to service from activity 【发布时间】:2013-05-30 17:35:49 【问题描述】:我正在尝试与服务通信。我找到了这个android Guide。
我确实喜欢第一个示例,但我有一个错误:
"java.lang.RuntimeException: 无法绑定到服务 com.example.internetcall.MyService@41763970 与 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;
这是我的服务:
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】:您的异常发生在Log.i("bnf",arg0.getStringExtra("number"));
arg0.getStringExtra("number")
为空。您没有在绑定服务的意图中传递字符串“number”。
【讨论】:
以上是关于从活动通信到服务的主要内容,如果未能解决你的问题,请参考以下文章
Android 从 Service 到 Client 的通信
活动到片段通信:当我尝试从活动更新片段中的文本视图时,出现空指针异常
与来自服务的活动(LocalService)通信 - Android 最佳实践