Android的服务 - 打开插座抛出空异常 [英] android service - opening socket throws null exception

查看:141
本文介绍了Android的服务 - 打开插座抛出空异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建远程服务,将照顾为几个不同的应用程序的所有客户端 - 服务器通信。
的主要思想是在开始从主活动的服务,并打开一个通信套接字到服务器。
在此之后,套接字将被其他应用程序使用 - 这就是为什么我要使用远程服务吧...

I'm trying to create remote service that will take care for all client-server communication for few different apps. The main idea is starting the service from main activity and open a communication socket to a server. after that, the socket will be used by other apps - that's why i want to use remote service for it...

现在我有与插座连接的问题,它会抛出异常空我的设备上。
它使用旧版本的Andr​​oid正常工作的A​​VD。

now i have an issue with the socket connection, it throws null exception on my device. it works fine on AVD using older android version.

这是我的code的某些部分:

here's some parts of my code:

我的主要活动:

final ServiceConnection conn = new ServiceConnection() {
        public void onServiceConnected(ComponentName name, IBinder service) {
            myRemoteService = ConnectionInterface.Stub.asInterface(service);
        }
        public void onServiceDisconnected(ComponentName name) {
            myRemoteService = null;
        }
    };

    final Thread t = new Thread(){
        public void run(){
            bindService(new Intent(getApplicationContext(), ConnectionRemoteService.class),conn,Context.BIND_AUTO_CREATE);
            while(true){}
        }

   };

后来我启动线程吨,t.start();

later on i start the Thread t with t.start();

我ConnectionRemoteService:

my ConnectionRemoteService:

package com.mainlauncher;

import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.IOException;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ResourceBundle;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.widget.Toast;

public class ConnectionRemoteService extends Service {

private static final int SERVERPORT = 7777;
private static final String SERVERADDRESS = "192.168.1.106";

private String deviceID;
private Socket socket;
private DataInputStream in;
private DataOutputStream out;

@Override
public void onCreate() {
    super.onCreate();
    WifiManager wm = (WifiManager)getSystemService(Context.WIFI_SERVICE);
    deviceID = wm.getConnectionInfo().getMacAddress();
    Toast.makeText(this, "Service On.", Toast.LENGTH_LONG).show();
    open();
}

@Override
public void onDestroy() {
    Toast.makeText(this, "Service Off.", Toast.LENGTH_LONG).show();
    close();
}

@Override
public IBinder onBind(Intent intent) {
    return myRemoteServiceStub;
}   

private ConnectionInterface.Stub myRemoteServiceStub = new ConnectionInterface.Stub() {

};

void open(){
    try{
        socket = new Socket(SERVERADDRESS,SERVERPORT);
        in = new DataInputStream(socket.getInputStream());
        out = new DataOutputStream(socket.getOutputStream());
        out.writeUTF(deviceID);
    }
    catch(Exception  e){
        System.err.println(e.getMessage());
    }
}

void close(){
    try {
        if(in!=null)
            in.close();
        if(out!=null)
            out.close();
        if(socket!=null)
            socket.close();
    } 
    catch(Exception  e){
        System.err.println(e.getMessage());
    }
    socket=null;

}

}

主要清单文件:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mainlauncher"
android:versionCode="1"
android:versionName="1.0" >

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="15" />

<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

<application
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name" >
    <activity android:name=".MainLauncherWindow" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

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

    <service
        android:name=".ConnectionRemoteService"
        android:process=":remote"/>
</application>

这里的DDMS日志上的调试模式的要求:

here's DDMS log on "debug" mode as requested:

12月11日至6日:13:45.130:D / InputDispatcher(392):notifyMotion - EVENTTIME = 4210399491000,DEVICEID = 6,源= 0x1002,policyFlags =为0x0,行动=为0x0,旗帜=为0x0,亚状态=为0x0,buttonState =为0x0,edgeFlags =为0x0,X precision = 1.529167,Y precision = 1.383594,停工= 4210399491000
  12月11日至6日:13:45.130:D / InputDispatcher(392):指针0:ID = 0,Tooltype刀具= 1,X = 66.049042,Y = 492.196503,pressure = 0.233333,大小= 0.250980,touchMajor = 44.054604, touchMinor = 44.054604,toolMajor = 4.818472,toolMinor = 4.818472,方向= 0.000000
  12月11日至6日:13:45.130:D / InputDispatcher(392):调度MotionEvent [行动= 0] ToCurrentInputTarget:40f9a6a8 com.mainlauncher / com.mainlauncher.MainLauncherWindow(服务器)
  12月11日至6日:13:45.150:D / PowerManagerService(392)的setPowerState:mPowerState = 0x3中,newState = 0x3中,noChangeLights =假,原因= 3,力=假,mProximitySensorActive =假,mBootCompleted = TRUE,mUseSoftwareAutoBrightness =真(重复:1)
  12月11日至6日:13:45.160:D / PowerManagerService(392)的setPowerState:mPowerState = 0x3中,newState = 0x3中,noChangeLights =假,原因= 2,力=假,mProximitySensorActive =假,mBootCompleted = TRUE,mUseSoftwareAutoBrightness =真
  12月11日至6日:13:45.160:I / PowerManagerService-JNI(392):[稳定性] PowerManagerService_userActivity JNI通过电源键事件PowerManagerService userActivity()
  12月11日至6日:13:45.160:D / PowerManagerService(392):setTimeoutLocked:现在= 4210399,timeoutOverride = -1,nextState = 0x3中,当= 4216399(mKeylightDelay = 6000,mDimDelay = 2147469000,mScreenOffDelay = 7000)
  12月11日至6日:13:45.190:D / InputDispatcher(392):notifyMotion - EVENTTIME = 4210464940000,DEVICEID = 6,源= 0x1002,policyFlags =为0x0,行动=为0x1,旗帜=为0x0,亚状态=为0x0,buttonState =为0x0, edgeFlags =为0x0,X precision = 1.529167,Y precision = 1.383594,停工= 4210399491000
  12月11日至6日:13:45.190:D / InputDispatcher(392):指针0:ID = 0,Tooltype刀具= 1,X = 65.395096,Y = 492.919250,pressure = 0.233333,大小= 0.219608,touchMajor = 38.547779, touchMinor = 38.547779,toolMajor = 4.818472,toolMinor = 4.818472,方向= 0.000000
  12月11日至6日:13:45.190:D / InputDispatcher(392):调度MotionEvent [动作= 1] ToCurrentInputTarget:40f9a6a8 com.mainlauncher / com.mainlauncher.MainLauncherWindow(服务器)
  12月11日至6日:13:45.220:D / dalvikvm(153):货叉前
  12月11日至6日:13:45.230:D / dalvikvm(20210):叉PID:0
  12月11日至6日:13:45.230:D / dalvikvm(20210):晚启用CheckJNI
  12月11日至6日:13:45.230:D / dalvikvm(153):叉PID:20210
  12月11日至6日:13:45.240:D /性能(392):AutoProf启动过程{工艺= com.mainlauncher:遥控器,ActivityName = com.mainlauncher / .ConnectionRemoteService},PID = 20210
  12月11日至6日:13:45.240:I / ActivityManager(392):启动PROC com.mainlauncher:远程服务com.mainlauncher / .ConnectionRemoteService:PID = 20210 UID = 10080导报= {} 3003
  12月11日至6日:13:45.300:D / ConnSrv_Debug(392):由一万零八十零分之二万零二百十得到mDefaultProxy空
  12月11日至6日:13:45.300:D / WifiStateMachine(392):syncRequestConnectionInfo mWifiInfo = SSID:Linksys的BSSID:00:14:BF:E6:13:8F,MAC:18:87:96:88:CD:68 ,请求者状态:已完成,RSSI:-83,链接速度:36,频率:2462,网络ID:1,显式连接:假的
  12月11日至6日:13:45.320:D / AndroidRuntime(20210):关闭VM
  12月11日至6日:13:45.320:W / dalvikvm(20210):主题ID = 1:螺纹未捕获的异常退出(组= 0x40a6b228)
  12月11日至6日:13:45.320:E / EmbeddedLogger(392):应用程序崩溃!工艺:com.mainlauncher:远程
  12月11日至6日:13:45.320:E / EmbeddedLogger(392):应用程序崩溃!包装:com.mainlauncher V1(1.0)
  12月11日至6日:13:45.320:E / AndroidRuntime(20210):致命异常:主要
  12月11日至6日:13:45.320:E / AndroidRuntime(20210):了java.lang.RuntimeException:无法创建服务com.mainlauncher.ConnectionRemoteService:显示java.lang.NullPointerException
  12月11日至6日:13:45.320:E / AndroidRuntime(20210):在android.app.ActivityThread.handleCreateService(ActivityThread.java:2593)
  12月11日至6日:13:45.320:E / AndroidRuntime(20210):在android.app.ActivityThread.access $ 1600(ActivityThread.java:139)
  12月11日至6日:13:45.320:E / AndroidRuntime(20210):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1326)
  12月11日至6日:13:45.320:E / AndroidRuntime(20210):在android.os.Handler.dispatchMessage(Handler.java:99)
  12月11日至6日:13:45.320:E / AndroidRuntime(20210):在android.os.Looper.loop(Looper.java:156)
  12月11日至6日:13:45.320:E / AndroidRuntime(20210):在android.app.ActivityThread.main(ActivityThread.java:5025)
  12月11日至6日:13:45.320:E / AndroidRuntime(20210):在java.lang.reflect.Method.invokeNative(本机方法)
  12月11日至6日:13:45.320:E / AndroidRuntime(20210):在java.lang.reflect.Method.invoke(Method.java:511)
  12月11日至6日:13:45.320:E / AndroidRuntime(20210):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:784)
  12月11日至6日:13:45.320:E / AndroidRuntime(20210):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551)
  12月11日至6日:13:45.320:E / AndroidRuntime(20210):在dalvik.system.NativeStart.main(本机方法)
  12月11日至6日:13:45.320:E / AndroidRuntime(20210):致:显示java.lang.NullPointerException
  12月11日至6日:13:45.320:E / AndroidRuntime(20210):在com.android.internal.os.LoggingPrintStream.println(LoggingPrintStream.java:298)
  12月11日至6日:13:45.320:E / AndroidRuntime(20210):在com.mainlauncher.ConnectionRemoteService.open(ConnectionRemoteService.java:60)
  12月11日至6日:13:45.320:E / AndroidRuntime(20210):在com.mainlauncher.ConnectionRemoteService.onCreate(ConnectionRemoteService.java:33)
  12月11日至6日:13:45.320:E / AndroidRuntime(20210):在android.app.ActivityThread.handleCreateService(ActivityThread.java:2571)
  12月11日至6日:13:45.320:E / AndroidRuntime(20210):10 ...更多
  12月11日至6日:13:45.330:E / EmbeddedLogger(392):应用标签:启动

11-06 12:13:45.130: D/InputDispatcher(392): notifyMotion - eventTime=4210399491000, deviceId=6, source=0x1002, policyFlags=0x0, action=0x0, flags=0x0, metaState=0x0, buttonState=0x0, edgeFlags=0x0, xPrecision=1.529167, yPrecision=1.383594, downTime=4210399491000 11-06 12:13:45.130: D/InputDispatcher(392): Pointer 0: id=0, toolType=1, x=66.049042, y=492.196503, pressure=0.233333, size=0.250980, touchMajor=44.054604, touchMinor=44.054604, toolMajor=4.818472, toolMinor=4.818472, orientation=0.000000 11-06 12:13:45.130: D/InputDispatcher(392): Dispatch MotionEvent [action=0] ToCurrentInputTarget: 40f9a6a8 com.mainlauncher/com.mainlauncher.MainLauncherWindow (server) 11-06 12:13:45.150: D/PowerManagerService(392): setPowerState: mPowerState=0x3, newState=0x3, noChangeLights=false, reason=3, force=false, mProximitySensorActive=false, mBootCompleted=true, mUseSoftwareAutoBrightness=true (repeat:1) 11-06 12:13:45.160: D/PowerManagerService(392): setPowerState: mPowerState=0x3, newState=0x3, noChangeLights=false, reason=2, force=false, mProximitySensorActive=false, mBootCompleted=true, mUseSoftwareAutoBrightness=true 11-06 12:13:45.160: I/PowerManagerService-JNI(392): [Stability] PowerManagerService_userActivity JNI pass power key event to PowerManagerService userActivity() 11-06 12:13:45.160: D/PowerManagerService(392): setTimeoutLocked: now=4210399, timeoutOverride=-1, nextState=0x3, when=4216399 (mKeylightDelay=6000, mDimDelay=2147469000, mScreenOffDelay=7000) 11-06 12:13:45.190: D/InputDispatcher(392): notifyMotion - eventTime=4210464940000, deviceId=6, source=0x1002, policyFlags=0x0, action=0x1, flags=0x0, metaState=0x0, buttonState=0x0, edgeFlags=0x0, xPrecision=1.529167, yPrecision=1.383594, downTime=4210399491000 11-06 12:13:45.190: D/InputDispatcher(392): Pointer 0: id=0, toolType=1, x=65.395096, y=492.919250, pressure=0.233333, size=0.219608, touchMajor=38.547779, touchMinor=38.547779, toolMajor=4.818472, toolMinor=4.818472, orientation=0.000000 11-06 12:13:45.190: D/InputDispatcher(392): Dispatch MotionEvent [action=1] ToCurrentInputTarget: 40f9a6a8 com.mainlauncher/com.mainlauncher.MainLauncherWindow (server) 11-06 12:13:45.220: D/dalvikvm(153): Before fork 11-06 12:13:45.230: D/dalvikvm(20210): Fork pid: 0 11-06 12:13:45.230: D/dalvikvm(20210): Late-enabling CheckJNI 11-06 12:13:45.230: D/dalvikvm(153): Fork pid: 20210 11-06 12:13:45.240: D/Performance(392): AutoProf Starting process { Process=com.mainlauncher:remote, ActivityName=com.mainlauncher/.ConnectionRemoteService}, pid=20210 11-06 12:13:45.240: I/ActivityManager(392): Start proc com.mainlauncher:remote for service com.mainlauncher/.ConnectionRemoteService: pid=20210 uid=10080 gids={3003} 11-06 12:13:45.300: D/ConnSrv_Debug(392): get mDefaultProxy null by 20210/10080 11-06 12:13:45.300: D/WifiStateMachine(392): syncRequestConnectionInfo mWifiInfo=SSID: linksys, BSSID: 00:14:bf:e6:13:8f, MAC: 18:87:96:88:cd:68, Supplicant state: COMPLETED, RSSI: -83, Link speed: 36, Frequency: 2462, Net ID: 1, Explicit connect: false 11-06 12:13:45.320: D/AndroidRuntime(20210): Shutting down VM 11-06 12:13:45.320: W/dalvikvm(20210): threadid=1: thread exiting with uncaught exception (group=0x40a6b228) 11-06 12:13:45.320: E/EmbeddedLogger(392): App crashed! Process: com.mainlauncher:remote 11-06 12:13:45.320: E/EmbeddedLogger(392): App crashed! Package: com.mainlauncher v1 (1.0) 11-06 12:13:45.320: E/AndroidRuntime(20210): FATAL EXCEPTION: main 11-06 12:13:45.320: E/AndroidRuntime(20210): java.lang.RuntimeException: Unable to create service com.mainlauncher.ConnectionRemoteService: java.lang.NullPointerException 11-06 12:13:45.320: E/AndroidRuntime(20210): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2593) 11-06 12:13:45.320: E/AndroidRuntime(20210): at android.app.ActivityThread.access$1600(ActivityThread.java:139) 11-06 12:13:45.320: E/AndroidRuntime(20210): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1326) 11-06 12:13:45.320: E/AndroidRuntime(20210): at android.os.Handler.dispatchMessage(Handler.java:99) 11-06 12:13:45.320: E/AndroidRuntime(20210): at android.os.Looper.loop(Looper.java:156) 11-06 12:13:45.320: E/AndroidRuntime(20210): at android.app.ActivityThread.main(ActivityThread.java:5025) 11-06 12:13:45.320: E/AndroidRuntime(20210): at java.lang.reflect.Method.invokeNative(Native Method) 11-06 12:13:45.320: E/AndroidRuntime(20210): at java.lang.reflect.Method.invoke(Method.java:511) 11-06 12:13:45.320: E/AndroidRuntime(20210): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784) 11-06 12:13:45.320: E/AndroidRuntime(20210): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:551) 11-06 12:13:45.320: E/AndroidRuntime(20210): at dalvik.system.NativeStart.main(Native Method) 11-06 12:13:45.320: E/AndroidRuntime(20210): Caused by: java.lang.NullPointerException 11-06 12:13:45.320: E/AndroidRuntime(20210): at com.android.internal.os.LoggingPrintStream.println(LoggingPrintStream.java:298) 11-06 12:13:45.320: E/AndroidRuntime(20210): at com.mainlauncher.ConnectionRemoteService.open(ConnectionRemoteService.java:60) 11-06 12:13:45.320: E/AndroidRuntime(20210): at com.mainlauncher.ConnectionRemoteService.onCreate(ConnectionRemoteService.java:33) 11-06 12:13:45.320: E/AndroidRuntime(20210): at android.app.ActivityThread.handleCreateService(ActivityThread.java:2571) 11-06 12:13:45.320: E/AndroidRuntime(20210): ... 10 more 11-06 12:13:45.330: E/EmbeddedLogger(392): Application Label: Launcher

我得到这一行的异常:

socket = new Socket(SERVERADDRESS,SERVERPORT);

我知道一些事情,可以使该异常:
1.我用&LT;使用许可权的android:NAME =android.permission.INTERNET对/&GT; 在我的主要体现。
2.离职线下运行,而不是在主要活动线程。
3.有没有防火墙等...
4.我检查与服务器的连接已经(所有工作正常无服务)。
5.我采用了android:工艺=:远程。在我的表现太

I know few things that can make that exception: 1. I use <uses-permission android:name="android.permission.INTERNET" /> in my main manifest. 2. The Service run under separated thread, not on the main activity thread. 3. There's no firewall etc... 4. I checked connection with the server already (all worked fine without the service). 5. I'm using android:process=":remote" in my manifest too.

为什么会发生异常任何想法?
如何调试它来获得更多的细节?

any ideas why that exception occurs? how can i debug it to get more details?

它的工作找到AVD使用OS 2.3,所以我认为这件事情的主要活动线程的例外,但我不能找出原因。

it worked find on AVD using OS 2.3, so i think it's something with the main activity thread exception, but i can't find out why.

谢谢,
Lioz。

thanks, Lioz.

推荐答案

您在呼唤的open()的onCreate()的onCreate()称为主线程。你不应该在主线程上做网络I / O。你得放错了地方的单独的线程的事情。在你的活动你开始一个单独的线程调用 bindService(),然后循环永远(无限循环嚼起来CPU周期,不是一件好事)。你并不需要从一个单独的线程调用里面 bindService(),因为 bindService()是异步的。它只发起的结合,它实际上并没有等待的结合来完成。这可以在主线程上完成。

You are calling open() from onCreate(). onCreate() is called on the main thread. You shouldn't do network I/O on the main thread. You've got the separate thread thing in the wrong place. In your activity you're starting a separate thread that calls bindService() and then loops forever (infinite loop chewing up CPU cycles, not a good thing). You don't need to call bindService() from inside a separate thread because bindService() is asynchronous. It only initiates the binding, it doesn't actually wait for the binding to complete. This can be done on the main thread.

在哪里,你需要启动一个线程是您的服务中。当你的服务被创建,你应该开始在的onCreate一个单独的线程()和单独的线程需要做的网络I / O(即:开放式插座,读,写等)。

Where you need to start a thread is inside your service. When your service gets created, you should start a separate thread in onCreate() and that separate thread needs to do the network I/O (ie: open socket, read, write, etc.).

此外,您还可以通过删除安卓使调试容易。这将允许你在服务方法中设置断点容易。

Also, you can make debugging easier by removing android:process=":remote" from the manifest. This will allow you to set breakpoints easier in the service methods.

这篇关于Android的服务 - 打开插座抛出空异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆