android - 绑定(bind)服务调用给出 NullPointerException

标签 android service

您好,感谢您的帮助。

我有以下 Activity (请参阅下面的代码)。 Activity 绑定(bind)(或尝试绑定(bind))到服务。

该服务公开(或者应该公开)公共(public)方法 getNumber() 来检索号码。

当执行到

 mService.getNumber()

应用程序停止返回 NullPointerException。

我进行了调试,我所能理解的是,由于某种原因,mService.getNumber() 导致了问题。

编辑:显然服务没有绑定(bind),我在

之后测试了 mBound bool 值
Intent intent = new Intent(this, LocalService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);

它返回 false,因此服务没有绑定(bind)...问题就在那里!

感谢您的建议

 public class Quotes extends Activity {
    public LocalService mService;
    boolean mBound = false;
    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
             // Bind to LocalService
        Intent intent = new Intent(this, LocalService.class);
        bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
        Log.e("", "arrivo a prima di loop");
        for(int a=0;;a++){
            SystemClock.sleep(500); 
            Log.e("", "sono nel loop");
            int num =mService.getNumber();
            Toast.makeText(this,Integer.toString(num),     Toast.LENGTH_SHORT).show();
                }
    }
       private ServiceConnection mConnection = new ServiceConnection() {
            //@Override
            public void onServiceConnected(ComponentName className,
                    IBinder service) {
                Log.e("", "sono in ServiceConnection");
    // We've bound to LocalService, cast the IBinder and get    LocalService instance
                LocalBinder binder = (LocalBinder) service;
                mService = binder.getService();
                mBound = true;
            }
            //@Override
            public void onServiceDisconnected(ComponentName arg0) {
                mBound = false;
            }
        };

这是服务的代码:

package com.example.quotes;

@TargetApi(3)
public class LocalService extends Service {
    public int i;
    // Binder given to clients
    private final IBinder mBinder = new LocalBinder();
              * Class used for the client Binder.  Because we know this service always
      * runs in the same process as its clients, we don't need to deal with IPC.
      */
    public class LocalBinder extends Binder {
        LocalService getService() {
            // Return this instance of LocalService so clients can call public methods
            return LocalService.this;
        }
    }
    @Override
    public IBinder onBind(Intent intent) {
        Log.e("", "sono nel service");
         new Task().execute();
        return mBinder;
    } 
         class Task extends AsyncTask<Void, String, Void> {
         @Override
        protected Void doInBackground(Void... unused) {
        for (i=0;;i++) {
        Log.e("Sono nel AsyncTask del Service", Integer.toBinaryString(i));
        SystemClock.sleep(500);
        }
        //return(null);
        }
     }

    public int getNumber() {
        return i;
    }       
 }

日志猫:

12-21 12:05:18.837: D/AndroidRuntime(889): Shutting down VM
12-21 12:05:18.837: W/dalvikvm(889): threadid=1: thread exiting with uncaught exception     (group=0x40a13300)
12-21 12:05:18.887: E/AndroidRuntime(889): FATAL EXCEPTION: main
12-21 12:05:18.887: E/AndroidRuntime(889): java.lang.RuntimeException: Unable to start     activity ComponentInfo{com.example.quotes/com.example.quotes.Quotes}:     java.lang.NullPointerException
12-21 12:05:18.887: E/AndroidRuntime(889):  at     android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
12-21 12:05:18.887: E/AndroidRuntime(889):  at     android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
12-21 12:05:18.887: E/AndroidRuntime(889):  at     android.app.ActivityThread.access$600(ActivityThread.java:130)
12-21 12:05:18.887: E/AndroidRuntime(889):  at     android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
12-21 12:05:18.887: E/AndroidRuntime(889):  at     android.os.Handler.dispatchMessage(Handler.java:99)
12-21 12:05:18.887: E/AndroidRuntime(889):  at android.os.Looper.loop(Looper.java:137)
12-21 12:05:18.887: E/AndroidRuntime(889):  at    android.app.ActivityThread.main(ActivityThread.java:4745)
12-21 12:05:18.887: E/AndroidRuntime(889):  at     java.lang.reflect.Method.invokeNative(Native Method)
12-21 12:05:18.887: E/AndroidRuntime(889):  at java.lang.reflect.Method.invoke(Method.java:511)
12-21 12:05:18.887: E/AndroidRuntime(889):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
12-21 12:05:18.887: E/AndroidRuntime(889):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-21 12:05:18.887: E/AndroidRuntime(889):  at dalvik.system.NativeStart.main(Native Method)
12-21 12:05:18.887: E/AndroidRuntime(889): Caused by: java.lang.NullPointerException
12-21 12:05:18.887: E/AndroidRuntime(889):  at com.example.quotes.Quotes.onCreate(Quotes.java:91)
12-21 12:05:18.887: E/AndroidRuntime(889):  at android.app.Activity.performCreate(Activity.java:5008)
12-21 12:05:18.887: E/AndroidRuntime(889):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
12-21 12:05:18.887: E/AndroidRuntime(889):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
12-21 12:05:18.887: E/AndroidRuntime(889):  ... 11 more

最佳答案

好的,找到了谜语的答案。

与服务的绑定(bind)是异步的。

只有调用onServiceConnected时,服务才被确定绑定(bind);因此,在 onServiceConnected 中,我添加调用一个方法来启动需要在服务上执行的 Activity 。

再见

关于android - 绑定(bind)服务调用给出 NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13990179/

相关文章:

java - 无法按预期将我的 arrayList 写入文件

android - RxJava 运算符结合两个可观察对象并在第一个可观察对象发出时立即发出

android - 为什么我的 Android 应用程序中有一个 "libs"文件夹?

service - "Service failed to start - Verify that you have sufficient privileges to start system services"

Angular 2 Primeng 消息服务未显示消息

javascript - 从 AngularJS API 服务返回一个值给 Controller

android - 前台应用程序上的 startActivity 导致 onPause/onResume

android - 使用事件总线解耦 Android 应用程序

安卓 : Make 2 services communicate

Android绑定(bind)服务和AIDL服务