我正试图从我的活动中调用我的服务中的方法。但是我不断收到错误
java.lang.NullPointerException: Attempt to invoke virtual method 'void co.app.services.LocalService.methodOne()' on a null object reference
我正在尝试拨打methodOne()
这是我的活动
public class MainActivity extends Activity {
LocalService mService;
private boolean mBounded = false;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//startService(intent);
Intent intent = new Intent(this, LocalService.class);
bindService(intent, mConnection, Context.BIND_AUTO_CREATE);
}
private ServiceConnection mConnection = new ServiceConnection() {
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
LocalService.MyBinder binder = (LocalService.MyBinder) service;
mService = binder.getService();
mBounded = true;
}
@Override
public void onServiceDisconnected(ComponentName name) {
mService = null;
mBounded = false;
}
};
public void publishMain(View view){
mService.methodOne();
}
这是我的服务
public class LocalService extends Service {
private String TAG = "TestService";
private IBinder myBinder = new MyBinder();
public LocalService() {
}
@Override
public void onCreate() {
Log.d(TAG, "onCreate called");
}
@Override
public IBinder onBind(Intent intent) {
Log.d(TAG, "onBind done");
return myBinder;
}
@Override
public boolean onUnbind(Intent intent) {
return false;
}
public class MyBinder extends Binder {
public LocalService getService() {
return LocalService.this;
}
}
@Override
public int onStartCommand(Intent intent, int flags, int startId)
{
Log.d(TAG, "onStartCommand done");
return Service.START_STICKY;
}
public void methodOne() {
Log.i("method", "test");
}
}
从activity_main layout
中的按钮调用PublishMain<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Publish"
android:onClick="publishMain"
android:id="@+id/PublishSubmit"
android:layout_marginBottom="20dp"/>
</LinearLayout>