Android bindService抛出NullPointerException

时间:2014-08-25 09:10:52

标签: android service nullpointerexception

我通过几个教程在Android中构建我的第一个bindService但是我继续得到相同的NullPointerException,我不明白。我的最后一个例子很简单......

MyActivity.java:

package de.123team.myapplication;

import android.app.Activity; import android.content.ComponentName; import android.content.Intent; import android.content.ServiceConnection; import android.os.Bundle; import android.os.IBinder; import android.view.Menu; import android.view.MenuItem; import android.widget.TextView;

public class MyActivity extends Activity {

    // Connection
    MySumService mService;
    boolean mBound;

    ServiceConnection mConnection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
            mBound = false;
            //mService = null;
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            mBound = true;
            MySumService.LocalBinder binder = (MySumService.LocalBinder)service;
            mService = binder.getService();
        }

    };


    @Override
    protected void onStart() {
        super.onStart();
    }


    @Override
    protected void onStop() {
        super.onStop();

        if (mBound) {
            mService.unbindService(mConnection);
            mBound = false;
        }
    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_my);


        TextView tvResult = (TextView)findViewById(R.id.tvResult);
        //tvResult.setText("Test123");

        Intent i = new Intent(this, MySumService.class);
        bindService(i, mConnection, BIND_AUTO_CREATE); 

        int r = mService.sum(1, 2);
        tvResult.setText(new String().valueOf(r));
    } }

MySumService.java:

package de.123team.myapplication;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class MySumService extends Service {


    private IBinder mBinder = new LocalBinder();


    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        return mBinder;
    }


    public int sum(int a, int b) {
        return 666;
    }


    public class LocalBinder extends Binder {
        public MySumService getService() {
            return MySumService.this;
        }
    }


}

的AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="de.proteam.myapplication" >

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >

        <activity
            android:name=".MyActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".MySumService"
            android:enabled="true"
            android:exported="true" >
        </service>

    </application> </manifest> 

令人沮丧的logCat我正在看几个小时......

08-25 10:19:59.809    5107-5107/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{de.123team.myapplication/de.123team.myapplication.MyActivity}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5041)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at de.123team.myapplication.MyActivity.onCreate(MyActivity.java:86)
            at android.app.Activity.performCreate(Activity.java:5104)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2144)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
            at android.app.ActivityThread.access$600(ActivityThread.java:141)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:137)
            at android.app.ActivityThread.main(ActivityThread.java:5041)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:511)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
            at dalvik.system.NativeStart.main(Native Method)

2 个答案:

答案 0 :(得分:2)

这里你在调用 bindservice()函数后立即调用方法sum。

移到下面的代码行

int r = mService.sum(1, 2);
tvResult.setText(new String().valueOf(r));

到onServiceConnected()函数,如下所示,

@Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        mBound = true;
        MySumService.LocalBinder binder = (MySumService.LocalBinder)service;
        mService = binder.getService();

        int r = mService.sum(1, 2);
        tvResult.setText(new String().valueOf(r));
    }

这将确保您的服务与您的活动绑定。

答案 1 :(得分:1)

请检查活动生命周期。在OnStart方法之前调用onCreate方法。您正在onStart中初始化mService对象并在onCreate中使用它。

参考:http://developer.android.com/reference/android/app/Activity.html

在onCreate中,因为mService没有初始化,并且根据java中对象的默认值为null,它抛出空指针异常。

理想情况下,您应该从onServiceConnected回调调用sum方法。