(Android)将服务绑定到启动服务的活动之外的活动

(Android)将服务绑定到启动服务的活动之外的活动,android,service,Android,Service,让这个android应用程序运行起来有点困难。基本上,在主菜单中,我启动了一个我创建的服务,这很好。我遇到的问题是,我有一个可以从主活动调用的options活动,我希望options活动能够与我在主活动中启动的服务交互 我已经阅读了这一页,看起来我做的一切都是对的,但是当我试图访问服务的一些成员函数时,我的程序崩溃了。当我试图访问服务内部的hashmap时,就会发生这种情况 在选项菜单活动的onCreate类中: Intent passedintent = getIntent(); // get

让这个android应用程序运行起来有点困难。基本上,在主菜单中,我启动了一个我创建的服务,这很好。我遇到的问题是,我有一个可以从主活动调用的options活动,我希望options活动能够与我在主活动中启动的服务交互

我已经阅读了这一页,看起来我做的一切都是对的,但是当我试图访问服务的一些成员函数时,我的程序崩溃了。当我试图访问服务内部的hashmap时,就会发生这种情况

在选项菜单活动的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"));
PassedEvent意图从开始此活动的主活动获取意图。起初,我尝试将其作为

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,而不是在主菜单函数中。我可能需要重新启动服务吗?
我认为,一旦我开始了主要的服务,我就不需要在这个活动中再次启动它

哎呀!这是因为我试图在调用ServiceConnection函数之前在onCreate()中使用该服务。

我意识到您已经找到了一种方法让它工作,但有几点快速建议:

1) 您不需要显式调用
startService
。该方法适用于不同的用例。绑定到它将根据需要创建
服务


2) 不要从
活动中使用
getApplicationContext
活动
是一个
上下文
,因此请传递

谢谢您的输入,我也应该传递什么?对不起,您没有传递应用程序上下文,您只是在使用它。所以,您应该在调用bindService之前删除“getApplicationContext()”。