Android bindService()提供NullPointerException,onServiceConnected()从未被调用

Android bindService()提供NullPointerException,onServiceConnected()从未被调用,android,service,android-service-binding,Android,Service,Android Service Binding,首先,我要说,我已经搜索了很长时间,发现了很多类似的问题(等等),但我还没有找到任何解决方法: 我有一个服务(jobcrawler),它是通过调用startservice()启动的。 在这个服务中,我启动了一个长时间运行的线程,该线程在某个时候调用了一个类(webservice),其init如下所示: public webservice(Context context) { this.context = context; this.db = new DatabaseHandler

首先,我要说,我已经搜索了很长时间,发现了很多类似的问题(等等),但我还没有找到任何解决方法:

我有一个
服务
(jobcrawler),它是通过调用startservice()启动的。 在这个服务中,我启动了一个长时间运行的线程,该线程在某个时候调用了一个类(webservice),其init如下所示:

public webservice(Context context) {
    this.context = context;
    this.db = new DatabaseHandler(this.context);
    this.access_token = db.getAuthKey();
}
在一些网络调用之后,类(webservice)通过名为receiveData()的方法接收数据。 在ReceiveData内部,我正试图绑定到服务,如下所示:

        if (!isBound) {
            // not bound yet, then bind to the service.
            Intent intent = new Intent(this, jobcrawler.class);
            bindService(intent, myConnection, Context.BIND_AUTO_CREATE);
        }
现在,我在调用bindservice的线路上得到了nullpointerexemption。请注意,我实际上还没有尝试对该服务做任何事情。我只是想把它绑起来。 任何帮助都将不胜感激。。。如果我有头发,我会把它拔出来!哈哈

下面是一些我认为相关的附加代码。 myConnection:

private ServiceConnection myConnection = new ServiceConnection() {
    public void onServiceConnected(ComponentName className,IBinder service) {
        Log.e("webservice", "service is connected");
        MyLocalBinder binder = (MyLocalBinder) service;
        myService = binder.getService();
        isBound = true;
    }

    public void onServiceDisconnected(ComponentName arg0) {
        Log.e("webservice", "service is disconnected");
        isBound = false;
    }
})

来自名为MyLocalBinder的服务的活页夹:

public class MyLocalBinder extends Binder {
    public jobcrawler getService() {   
            Log.e("Job Crawler", "returning self");
        return jobcrawler.this;
    }
}
服务的onbind方法:

private final IBinder myBinder = new MyLocalBinder();

@Override
public IBinder onBind(Intent arg0) {
  Log.d("JobCrawler Service", "Service is bound");
    return myBinder;
}
哦,这就是我从服务内的线程加载类的地方,以防我应该使用不同的上下文或其他内容:

         private webservice ws= new webservice(getBaseContext());

我知道有点晚了,但我遇到了同样的问题,也许一些谷歌用户会很高兴:)

因此,对我来说,以下措施奏效了: 参照您的上下文调用bindService方法:

context.bindService(intent, serviceConnection, Context.BIND_AUTO_CREATE)

不是100%确定,但我认为您的MyLocalBinder定义不正确。您应该创建一个定义活页夹的AIDL文件。JobCrawler还需要是可打包的,并且最好在AIDL中定义。所以,我不能用这种方式绑定到服务?我不确定艾德尔是什么。当我创建绑定代码时,我遵循了这个教程()。好的,从这里我可以发现AIDL是用于在应用程序上下文之外访问的服务的。但是我的服务只是尝试与同一应用程序中的类通信,所以我不需要AIDL,对吗?如果你是在同一个过程中这样做的,那么为什么要使用绑定服务?有很多更简单、更像java的方法可以做到这一点,因为据我所知,真正将信息发送回服务的唯一方法就是绑定到它。如果还有其他选择,我完全接受。有什么建议吗?