无法绑定到TCP服务

时间:2013-10-21 10:33:08

标签: android

SocketService.java:

public class SocketService extends Service {
    int mStartMode;
    IBinder mBinder = new LocalBinder();
    boolean mAllowRebind;
    String IPValue;
    String PortValue;
    Socket socket;
    byte data[];


    public class LocalBinder extends Binder {
        public SocketService getServerInstance() {
            return SocketService.this;
        }
    }


    @Override
    public void onCreate() {
        System.out.println("SERVICE CREATED");
        SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
        IPValue = sharedPreferences.getString("IPValue", "NA");
        PortValue = sharedPreferences.getString("PortValue", "NA");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        System.out.println("SERVICE ONSTARTCOMMAND");
        return mStartMode;
    }

    @Override
    public IBinder onBind(Intent intent) {
        System.out.println("SERVICE BOUND");

        try {
            InetAddress serverAddr = null;
            serverAddr = InetAddress.getByName(IPValue);
            int serverPort = Integer.parseInt(PortValue);
            System.out.println(serverAddr.getHostAddress() + serverPort);
            socket = new Socket(serverAddr, serverPort);

        } catch (UnknownHostException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return mBinder;
    }

    public void send_mesage(String msg) {
        PrintWriter out = null;
        try {
            out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(
                    socket.getOutputStream())), true);
            out.println(msg);

        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

我在onCreate中获取了IP和端口,并在onBind中建立了套接字连接。

现在在我的活动中:

public class MainActivity extends Activity {

    public String IPValue;
    public String PortValue;
    public Socket socket;
    boolean mBounded;
    SocketService mServer;

    ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceDisconnected(ComponentName name) {
            Toast.makeText(MainActivity.this, "Service is disconnected", 1000).show();
            mBounded = false;
            mServer = null;
        }

        public void onServiceConnected(ComponentName name, IBinder service) {
            Toast.makeText(MainActivity.this, "Service is connected", 1000).show();
            mBounded = true;
            SocketService.LocalBinder mLocalBinder = (SocketService.LocalBinder)service;
            mServer = mLocalBinder.getServerInstance();
        }
    };

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

        Intent mIntent = new Intent(this, SocketService.class);
        bindService(mIntent, mConnection, BIND_AUTO_CREATE);

    }

这完美无缺,我的TCP服务器将连接显示为已创建

现在我想访问send_message()中的SocketService方法。 所以我只是在我的活动的mServer.send_mesage("HELLO WORLD!");bindService(mIntent, mConnection, BIND_AUTO_CREATE);之后添加了onCreate()

但这导致一切都崩溃了。我的连接未在我的服务器和应用程序FC上建立。这是日志:

10-21 15:37:33.945    9125-9125/com.example.myfirstapp D/dalvikvm﹕ GC_EXTERNAL_ALLOC freed 54K, 50% free 2694K/5379K, external 0K/0K, paused 313ms
10-21 15:37:48.985    9125-9125/com.example.myfirstapp D/AndroidRuntime﹕ Shutting down VM
10-21 15:37:48.985    9125-9125/com.example.myfirstapp W/dalvikvm﹕ threadid=1: thread exiting with uncaught exception (group=0x40018560)
10-21 15:37:49.015    9125-9125/com.example.myfirstapp E/AndroidRuntime﹕ FATAL EXCEPTION: main
    java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.myfirstapp/com.example.myfirstapp.MainActivity}: java.lang.NullPointerException
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1768)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1784)
            at android.app.ActivityThread.access$1500(ActivityThread.java:123)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:939)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:130)
            at android.app.ActivityThread.main(ActivityThread.java:3835)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:507)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
            at dalvik.system.NativeStart.main(Native Method)
     Caused by: java.lang.NullPointerException
            at com.example.myfirstapp.MainActivity.onCreate(MainActivity.java:57)
            at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1047)
            at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1722)
            at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1784)
            at android.app.ActivityThread.access$1500(ActivityThread.java:123)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:939)
            at android.os.Handler.dispatchMessage(Handler.java:99)
            at android.os.Looper.loop(Looper.java:130)
            at android.app.ActivityThread.main(ActivityThread.java:3835)
            at java.lang.reflect.Method.invokeNative(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:507)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:864)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:622)
            at dalvik.system.NativeStart.main(Native Method)

NullPointerException就在我刚添加的新行上!

我不明白可能导致这个问题的原因!奇怪的是,显然这次服务的onCreateonBind方法甚至都没有被调用,因为我没有看到我在每个方法中输出的打印语句的输出。

任何帮助?

1 个答案:

答案 0 :(得分:0)

mServer为null,直到回调onServiceConnected()触发为止。虽然你已经告诉它绑定在前一行,但绑定需要时间。您必须等到回叫之后再参考mServer