让这个 android 应用程序运行有点麻烦。基本上,在主菜单中,我启动了我创建的服务,这工作正常。我遇到的问题是我有一个可以从主活动调用的选项活动,并且我希望选项活动能够与我在主活动中启动的服务进行交互。
我已经阅读了这个页面http://developer.android.com/guide/components/bound-services.html,我似乎做的一切都是正确的,但是当我尝试访问服务的一些成员函数时,我的程序崩溃了. 当我尝试访问服务内的哈希图时,它会特别发生。
在我的选项菜单活动的 onCreate 类中:
Intent passedintent = getIntent(); // gets the intent sent to the activity
//Intent intentShim = new Intent(this, ShimmerService.class);
// binds the shimmer service to this activity
boolean isconnected = getApplicationContext().bindService(intent, shimmerServiceConnection, Context.BIND_AUTO_CREATE);
// register the shimmer receiver
registerReceiver(shimmerReceiver, new IntentFilter("com.jpl_347E.bio_sigapp.ShimmerService"));
passintent Intent 从开始这个活动的主要活动中获取意图。起初我尝试将其作为第一个参数传入
getApplicationContext().bindService(....)
功能,但它似乎没有工作。所以我创建了一个新的意图,它反映了我在主菜单活动中创建服务的意图。我的选项菜单活动中也有这些功能
private ServiceConnection shimmerServiceConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
LocalShimmerBinder binder = (LocalShimmerBinder)arg1;
serviceshim = binder.getService();
}
@Override
public void onServiceDisconnected(ComponentName arg0) {
// TODO Auto-generated method stub
}
};
private BroadcastReceiver shimmerReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (intent.getIntExtra("ShimmerState", -1) != -1)
;//TODO
}
};
这与我在主菜单活动中的代码几乎相同,并且完全能够在那里找到服务。我想我已经将错误追溯到
binder.getService()
此函数返回 null,然后我尝试访问我的引用变量未指向的类中的 hashmap(它指向 null)。我只是想不通为什么 binder.getService() 会在此处返回 null 而不是在主菜单功能中。我可能需要重新启动服务吗?我认为一旦我在 main 中启动了服务,我就不需要在这个活动中再次启动它。