【发布时间】:2013-09-02 18:47:56
【问题描述】:
我正在尝试启动service,然后打开socket 以与服务器建立连接。
点击按钮我创建新的Thread 然后启动服务。
Thread t = new Thread(){
public void run(){
mIntent= new Intent(MainActivity.this, ConnectonService.class);
mIntent.putExtra("KEY1", "Value used by the service");
context.startService(mIntent);
}
};
t.start();
然后在service,我尝试打开socket并与服务器建立连接
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
//TODO do something useful
try {
InetAddress serverAddr = InetAddress.getByName(SERVER_IP);
socket = new Socket(serverAddr, SERVERPORT);
Scanner scanner = new Scanner(socket.getInputStream());
message = scanner.nextLine();
} catch (IOException e) {
e.printStackTrace();
}
return Service.START_NOT_STICKY;
}
但是当我调用它时,我有错误
08-30 08:56:49.268: E/AndroidRuntime(3751): java.lang.RuntimeException: Unable to start service com.example.testofconnection.ConnectonService@40ef02a8 with Intent { cmp=com.example.testofconnection/.ConnectonService (has extras) }: android.os.NetworkOnMainThreadException*
我认为问题在于service 在main thread 上,但我找不到如何在新(独立)线程上启动服务以保留connection alive?
【问题讨论】:
-
我需要与服务器保持连接。 AsyncTask 只打开连接,发送一些请求,得到一些响应并关闭,所以我发现有了服务我可以实现它
标签: android multithreading sockets android-service