不幸的是,Msger已经停止。致命异常:主要 [英] Unfortunately, Msger has stopped. FATAL Exception: main

查看:128
本文介绍了不幸的是,Msger已经停止。致命异常:主要的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  

可能重复:
  <一href="http://stackoverflow.com/questions/6343166/android-os-networkonmainthreadexception">android.os.NetworkOnMainThreadException

当我尝试从监听1号活动运行我的第二个活动,main.xml中有一个致命的异常。当我拿出runTcpClient();在TcpClient的线程(),它加载了罚款。

我碰到使用AsyncTask的管理UI线程:的Andr​​oid UI的AsyncTask

$ C $下TcpClientJava.java

 包com.mesger;

进口java.io.BufferedReader中;
进口java.io.BufferedWriter中;
进口java.io.IOException异常;
进口java.io.InputStreamReader中;
进口java.io.OutputStreamWriter中;
进口的java.net.Socket;
进口的java.net.UnknownHostException;

进口android.app.Activity;
进口android.content.Intent;
进口android.os.Bundle;
进口android.util.Log;



公共类TcpClient的延伸活动{
/ **第一次创建活动时调用。 * /
@覆盖
公共无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.main);
    runTcpClient();
    完();
}

私有静态最终诠释TCP_SERVER_PORT = 1234;
私人无效runTcpClient(){
    尝试 {
        插座S =新的Socket(10.0.2.2,TCP_SERVER_PORT);
        的BufferedReader在=新的BufferedReader(新的InputStreamReader(s.getInputStream()));
        BufferedWriter将出=新的BufferedWriter(新OutputStreamWriter(s.getOutputStream()));
        //发送输出味精
        字符串outMsg =TCP连接+ TCP_SERVER_PORT + System.getProperty(line.separator);
        out.write(outMsg);
        了out.flush();
        Log.i(TcpClient的,派:+ outMsg);
        //接受服务器响应
        串inMsg = in.readLine()+ System.getProperty(line.separator);
        Log.i(TcpClient的,收到:+ inMsg);
        //关闭连接
        S.CLOSE();
    }赶上(UnknownHostException异常E){
        e.printStackTrace();
    }赶上(IOException异常E){
        e.printStackTrace();
    }
}
//用这种方法代替runTcpClient()在的onCreate,如果你想运行TCP客户端作为服务
私人无效runTcpClientAsService(){
    意图lIntent =新的意图(this.getApplicationContext(),TcpClientService.class);
    this.startService(lIntent);
}
 

}

的logcat

  11-12 13:41:22.725:D / gralloc_goldfish(738):仿真器没有检测GPU的仿真。
11-12 13:42:32.409:D / AndroidRuntime(738):关闭虚拟机
11-12 13:42:32.409:W / dalvikvm(738):主题ID = 1:螺纹退出与未捕获的异常(组= 0x40a13300)
11-12 13:42:32.465:E / AndroidRuntime(738):致命异常:主要
11-12 13:42:32.465:E / AndroidRuntime(738):java.lang.RuntimeException的:无法启动的活动ComponentInfo {com.i911.emergency.response / com.mesger.TcpClient}:android.os.NetworkOnMainThreadException
11-12 13:42:32.465:E / AndroidRuntime(738):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
11-12 13:42:32.465:E / AndroidRuntime(738):在android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-12 13:42:32.465:E / AndroidRuntime(738):在android.app.ActivityThread.access $ 600(ActivityThread.java:130)
11-12 13:42:32.465:E / AndroidRuntime(738):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1195)
11-12 13:42:32.465:E / AndroidRuntime(738):在android.os.Handler.dispatchMessage(Handler.java:99)
11-12 13:42:32.465:E / AndroidRuntime(738):在android.os.Looper.loop(Looper.java:137)
11-12 13:42:32.465:E / AndroidRuntime(738):在android.app.ActivityThread.main(ActivityThread.java:4745)
11-12 13:42:32.465:E / AndroidRuntime(738):在java.lang.reflect.Method.invokeNative(本机方法)
11-12 13:42:32.465:E / AndroidRuntime(738):在java.lang.reflect.Method.invoke(Method.java:511)
11-12 13:42:32.465:E / AndroidRuntime(738):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:786)
11-12 13:42:32.465:E / AndroidRuntime(738):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-12 13:42:32.465:E / AndroidRuntime(738):在dalvik.system.NativeStart.main(本机方法)
11-12 13:42:32.465:E / AndroidRuntime(738):由:android.os.NetworkOnMainThreadException
11-12 13:42:32.465:E / AndroidRuntime(738):在android.os.StrictMode $ AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
11-12 13:42:32.465:E / AndroidRuntime(738):在libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
11-12 13:42:32.465:E / AndroidRuntime(738):在libcore.io.IoBridge.connectErrno(IoBridge.java:127)
11-12 13:42:32.465:E / AndroidRuntime(738):在libcore.io.IoBridge.connect(IoBridge.java:112)
11-12 13:42:32.465:E / AndroidRuntime(738):在java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
11-12 13:42:32.465:E / AndroidRuntime(738):在java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
11-12 13:42:32.465:E / AndroidRuntime(738):在java.net.Socket.startupSocket(Socket.java:566)
11-12 13:42:32.465:E / AndroidRuntime(738):在java.net.Socket.tryAllAddresses(Socket.java:127)
11-12 13:42:32.465:E / AndroidRuntime(738):在java.net.Socket中的&LT; INIT&GT;(Socket.java:177)
11-12 13:42:32.465:E / AndroidRuntime(738):在java.net.Socket中的&LT; INIT&GT;(Socket.java:149)
11-12 13:42:32.465:E / AndroidRuntime(738):在com.mesger.TcpClient.runTcpClient(TcpClient.java:32)
11-12 13:42:32.465:E / AndroidRuntime(738):在com.mesger.TcpClient.onCreate(TcpClient.java:25)
11-12 13:42:32.465:E / AndroidRuntime(738):在android.app.Activity.performCreate(Activity.java:5008)
11-12 13:42:32.465:E / AndroidRuntime(738):在android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
11-12 13:42:32.465:E / AndroidRuntime(738):在android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
11-12 13:42:32.465:E / AndroidRuntime(738):11 ...更多
 

解决方案

 产生的原因:android.os.NetworkOnMainThreadException
 

您正试图在主线程上执行一个潜在的慢速网络操作,这成为安卓3.0+一个致命的异常。只需将 runTcpClient()来一个新的线程通过使用AsyncTask的或装载机。

下面是一个例子: android.os.NetworkOnMainThreadException


试试这个:

 类TcpClientTask扩展的AsyncTask&LT;虚空,虚空,虚空&GT; {
    私有静态最终诠释TCP_SERVER_PORT = 1234;
    私人布尔错误=虚假的;

    保护无效doInBackground(虚空......为arg0){
        尝试 {
            插座S =新的Socket(10.0.2.2,TCP_SERVER_PORT);
            的BufferedReader在=新的BufferedReader(新的InputStreamReader(s.getInputStream()));
            BufferedWriter将出=新的BufferedWriter(新OutputStreamWriter(s.getOutputStream()));
            //发送输出味精
            字符串outMsg =TCP连接+ TCP_SERVER_PORT + System.getProperty(line.separator);
            out.write(outMsg);
            了out.flush();
            Log.i(TcpClient的,派:+ outMsg);
            //接受服务器响应
            串inMsg = in.readLine()+ System.getProperty(line.separator);
            Log.i(TcpClient的,收到:+ inMsg);
            //关闭连接
            S.CLOSE();
        }赶上(UnknownHostException异常E){
            错误= TRUE;
            e.printStackTrace();
        }赶上(IOException异常E){
            错误= TRUE;
            e.printStackTrace();
        }
        返回null;
    }

    保护无效onPostExecute(){
        如果(错误){
            //坏事发生
        }
        其他 {
            // 成功
        }

    }
}
 

要使用它拨打:新TcpClientTask()执行();


  

我有1更多的问题。 字符串inMsg = in.readLine()+ System.getProperty(line.separator); 接收的邮件,我将如何设置它得到它每15毫秒或什么稳定保持接收数据。

我不能确定你正在尝试做的。但我注意到,你只能叫的readLine()一次,如果你想读的多条线路,使用一个循环:

  StringBuilder的味精=新的StringBuilder();
串线;
而((行= in.readLine())!= NULL)//继续读,直到文件结束为止
    。msg.append(in.readLine())追加(System.getProperty(line.separator));
 

StringBuilders产生更少的开销加在一起的字符串时,只需使用 msg.toString()当你想获得完整的信息。

Possible Duplicate:
android.os.NetworkOnMainThreadException

When I try to run my 2nd Activity from a Listener on the 1st Activity, main.xml has a fatal exception. When I take out the runTcpClient(); on the TcpClient Thread() it loads up fine.

I came across UI threads managing using aSyncTask: Android UI aSyncTask

CODE FOR TcpClientJava.java

package com.mesger;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;



public class TcpClient extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    runTcpClient();
    finish();
}

private static final int TCP_SERVER_PORT = 1234;
private void runTcpClient() {
    try {
        Socket s = new Socket("10.0.2.2", TCP_SERVER_PORT);
        BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
        BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
        //send output msg
        String outMsg = "TCP connecting to " + TCP_SERVER_PORT + System.getProperty("line.separator"); 
        out.write(outMsg);
        out.flush();
        Log.i("TcpClient", "sent: " + outMsg);
        //accept server response
        String inMsg = in.readLine() + System.getProperty("line.separator");
        Log.i("TcpClient", "received: " + inMsg);
        //close connection
        s.close();
    } catch (UnknownHostException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } 
}
//replace runTcpClient() at onCreate with this method if you want to run tcp client as a service
private void runTcpClientAsService() {
    Intent lIntent = new Intent(this.getApplicationContext(), TcpClientService.class);
    this.startService(lIntent);
}

}

LOGCAT

11-12 13:41:22.725: D/gralloc_goldfish(738): Emulator without GPU emulation detected.
11-12 13:42:32.409: D/AndroidRuntime(738): Shutting down VM
11-12 13:42:32.409: W/dalvikvm(738): threadid=1: thread exiting with uncaught exception (group=0x40a13300)
11-12 13:42:32.465: E/AndroidRuntime(738): FATAL EXCEPTION: main
11-12 13:42:32.465: E/AndroidRuntime(738): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.i911.emergency.response/com.mesger.TcpClient}: android.os.NetworkOnMainThreadException
11-12 13:42:32.465: E/AndroidRuntime(738):  at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
11-12 13:42:32.465: E/AndroidRuntime(738):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
11-12 13:42:32.465: E/AndroidRuntime(738):  at android.app.ActivityThread.access$600(ActivityThread.java:130)
11-12 13:42:32.465: E/AndroidRuntime(738):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
11-12 13:42:32.465: E/AndroidRuntime(738):  at android.os.Handler.dispatchMessage(Handler.java:99)
11-12 13:42:32.465: E/AndroidRuntime(738):  at android.os.Looper.loop(Looper.java:137)
11-12 13:42:32.465: E/AndroidRuntime(738):  at android.app.ActivityThread.main(ActivityThread.java:4745)
11-12 13:42:32.465: E/AndroidRuntime(738):  at java.lang.reflect.Method.invokeNative(Native Method)
11-12 13:42:32.465: E/AndroidRuntime(738):  at java.lang.reflect.Method.invoke(Method.java:511)
11-12 13:42:32.465: E/AndroidRuntime(738):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
11-12 13:42:32.465: E/AndroidRuntime(738):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
11-12 13:42:32.465: E/AndroidRuntime(738):  at dalvik.system.NativeStart.main(Native Method)
11-12 13:42:32.465: E/AndroidRuntime(738): Caused by: android.os.NetworkOnMainThreadException
11-12 13:42:32.465: E/AndroidRuntime(738):  at android.os.StrictMode$AndroidBlockGuardPolicy.onNetwork(StrictMode.java:1117)
11-12 13:42:32.465: E/AndroidRuntime(738):  at libcore.io.BlockGuardOs.connect(BlockGuardOs.java:84)
11-12 13:42:32.465: E/AndroidRuntime(738):  at libcore.io.IoBridge.connectErrno(IoBridge.java:127)
11-12 13:42:32.465: E/AndroidRuntime(738):  at libcore.io.IoBridge.connect(IoBridge.java:112)
11-12 13:42:32.465: E/AndroidRuntime(738):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:192)
11-12 13:42:32.465: E/AndroidRuntime(738):  at java.net.PlainSocketImpl.connect(PlainSocketImpl.java:172)
11-12 13:42:32.465: E/AndroidRuntime(738):  at java.net.Socket.startupSocket(Socket.java:566)
11-12 13:42:32.465: E/AndroidRuntime(738):  at java.net.Socket.tryAllAddresses(Socket.java:127)
11-12 13:42:32.465: E/AndroidRuntime(738):  at java.net.Socket.<init>(Socket.java:177)
11-12 13:42:32.465: E/AndroidRuntime(738):  at java.net.Socket.<init>(Socket.java:149)
11-12 13:42:32.465: E/AndroidRuntime(738):  at com.mesger.TcpClient.runTcpClient(TcpClient.java:32)
11-12 13:42:32.465: E/AndroidRuntime(738):  at com.mesger.TcpClient.onCreate(TcpClient.java:25)
11-12 13:42:32.465: E/AndroidRuntime(738):  at android.app.Activity.performCreate(Activity.java:5008)
11-12 13:42:32.465: E/AndroidRuntime(738):  at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
11-12 13:42:32.465: E/AndroidRuntime(738):  at     android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
11-12 13:42:32.465: E/AndroidRuntime(738):  ... 11 more

解决方案

Caused by: android.os.NetworkOnMainThreadException

You are trying to perform a potentially slow network operation on the main thread, this became a fatal exception in Android 3.0+. Simply move runTcpClient() to a new Thread by using an AsyncTask or Loader.

Here is an example: android.os.NetworkOnMainThreadException.


Try this:

class TcpClientTask extends AsyncTask<Void, Void, Void> {
    private static final int TCP_SERVER_PORT = 1234;
    private boolean error = false;

    protected Void doInBackground(Void... arg0) {
        try {
            Socket s = new Socket("10.0.2.2", TCP_SERVER_PORT);
            BufferedReader in = new BufferedReader(new InputStreamReader(s.getInputStream()));
            BufferedWriter out = new BufferedWriter(new OutputStreamWriter(s.getOutputStream()));
            //send output msg
            String outMsg = "TCP connecting to " + TCP_SERVER_PORT + System.getProperty("line.separator"); 
            out.write(outMsg);
            out.flush();
            Log.i("TcpClient", "sent: " + outMsg);
            //accept server response
            String inMsg = in.readLine() + System.getProperty("line.separator");
            Log.i("TcpClient", "received: " + inMsg);
            //close connection
            s.close();
        } catch (UnknownHostException e) {
            error = true;
            e.printStackTrace();
        } catch (IOException e) {
            error = true;
            e.printStackTrace();
        }
        return null;
    }

    protected void onPostExecute() {
        if(error) {
            // Something bad happened
        }
        else {
            // Success
        }

    }
}

To use it call: new TcpClientTask().execute();


I have 1 more question. String inMsg = in.readLine() + System.getProperty("line.separator"); which receives messages, how would I set it up to get it every 15ms or whatever is stable to keep receiving data.

I'm not certain what you are trying to do. But I noticed you only call readLine() once, if you want to read more than one line, use a loop:

StringBuilder msg = new StringBuilder();
String line;
while((line = in.readLine()) != null) // Keep reading until the end of the file is reached
    msg.append(in.readLine()).append(System.getProperty("line.separator"));

StringBuilders create less overhead when adding Strings together, simply use msg.toString() when you want get the whole message.

这篇关于不幸的是,Msger已经停止。致命异常:主要的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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