안녕하세요 현재 안드로이드 개발중에 계속 막히는게 있어 질문드립니다.
현재 통신을 모든 액티비티에서 유지해야 하기 때문에 통신을 서비스에서 돌리고 있습니다.
LoginActivity(액티비티)
NetworkService(서비스)
SocketNetwork(쓰레드)
클래스 3개를 놓고 액티비티가 onCreate를 하면 아래의 코드를 실행하며,
bindService(new Intent(LoginActivity.this, mService.getClass()), mConnection, Context.BIND_AUTO_CREATE);
서비스는 현재 아래와 같이 이루어져 있습니다.
public class NetworkService extends Service {
private SocketNetwork soc;
//서비스 바인더 내부 클래스 선언
public class MainServiceBinder extends Binder {
public NetworkService getService() {
return NetworkService.this; //현재 서비스를 반환.
}
}
@Override
public void onCreate() {
soc = new SocketNetwork(NetworkUtil.IP, NetworkUtil.PORT, LoginActivity.handler);
soc.start();
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
soc.close();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return START_NOT_STICKY;
}
@Override
public IBinder onBind(Intent intent) {
return null;
}
public void sendData(byte[] data) {
soc.writeData(data);
}
public void setHandler(Handler handler) {
soc.setHandler(handler);
}
}
이제 문제는 액티비티에서 서비스의 sendData()를 호출할 때
java.lang.NullPointerException: Attempt to invoke virtual method 'void neighbor.com.mbis.MapUtil.Thread.SocketNetwork.writeData(byte[])' on a null object reference
at neighbor.com.mbis.Network.NetworkService.sendData(NetworkService.java:56)
at neighbor.com.mbis.Activity.LoginActivity.sendData(LoginActivity.java:371)
at neighbor.com.mbis.Activity.LoginActivity.access$200(LoginActivity.java:47)
at neighbor.com.mbis.Activity.LoginActivity$1.handleMessage(LoginActivity.java:156)
아래와 같이 서비스의 soc 객체가 null이라고 합니다;;
private NetworkService mService;
mService.sendData(Data.writeData);
private ServiceConnection mConnection = new ServiceConnection() {
// Called when the connection with the service is established
public void onServiceConnected(ComponentName className, IBinder service) {
NetworkService.MainServiceBinder binder = (NetworkService.MainServiceBinder) service;
mService = binder.getService(); //서비스 받아옴
mService.sendData(Data.writeData);
}
// Called when the connection with the service disconnects unexpectedly
public void onServiceDisconnected(ComponentName className) {
mService = null;
}
};
바로 위에 있는 코드는 액티비티에서 서비스의 sendData를 호출 할 때 사용하는 방식이구요;;
너무 어렵습니다 제발 가르쳐주세요ㅠㅠ 왜 저 soc 객체는 계속 null인 걸까요??