bindService报空指针错误故障排除

来源:互联网 发布:截图软件百度云 编辑:程序博客网 时间:2024/05/29 13:25

说起来不值一提。学过服务但是很久没有去用,没有研究里面的原理,用起来就出错误。以下是刚写的代码:

service:

public class MyService extends Service {    public MyService() {    }    @Override    public IBinder onBind(Intent intent) {        return new MyBinder();    }    public class MyBinder extends Binder {        public MyService getService() {            return MyService.this;        }    }    public void say(TextView textView) {        textView.setText("啊哈,你没有念开门咒!");    }}

Avtivity:
public class MainActivity extends AppCompatActivity {    private TextView mTextView;    private MyService service;    private ServiceConnection serviceConnection = new ServiceConnection() {        @Override        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {            service = ((MyService.MyBinder) iBinder).getService();        }        @Override        public void onServiceDisconnected(ComponentName componentName) {        }    };    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        mTextView = (TextView) findViewById(R.id.txt_1);        Intent intent = new Intent(this, MyService.class);        bindService(intent, serviceConnection, BIND_AUTO_CREATE);        service.say(mTextView);    }}

AndroidMenifest.xml:

<?xml version="1.0" encoding="utf-8"?><manifest xmlns:android="http://schemas.android.com/apk/res/android"    package="com.devin.bindservicedemo">    <uses-permission android:name="android.permission.INTERNET" />    <application        android:allowBackup="true"        android:icon="@mipmap/ic_launcher"        android:label="@string/app_name"        android:supportsRtl="true"        android:theme="@style/AppTheme">        <activity android:name=".MainActivity">            <intent-filter>                <action android:name="android.intent.action.MAIN" />                <category android:name="android.intent.category.LAUNCHER" />            </intent-filter>        </activity>        <service android:name=".MyService"></service>    </application></manifest>

看起来似乎没有什么问题。但是跑起来就出错。Logcat提示空指针异常。打断点,发现是sevice没有拿到。加日志测试,发现是创建ServiceConnection 时onServiceConnected()方法根本就没有调用。why?


后来仔细琢磨,恍然大悟。服务的启动的异步的。也就是说我在用service.say(mTextView);这一句调用service这个对象的时候,在另一个线程里服务的创建和关联还没有完成,所以就是空指针了。以前使用的时候是用按钮去测试的,点击按钮的时候服务创建和绑定都已经完成,所以没有觉得,没有发现问题就不会无思考。这下耗费我不少心思。

把这一句调到onServiceConnected()方法里面,让他在上一部执行完成之后执行。如果是到另外一个activity执行,则需要用到接口回调通知更新。

换回去之后,运行正常。


补充:运用向导创Service的,在AndroidMenifest.xml有下面两句要删掉:

android:enabled="false"android:exported="false"


0 0
原创粉丝点击