缓冲读卡器不工作

时间:2013-04-28 05:40:18

标签: android

我是一名初学者android开发者。我正在尝试这段代码。但它总是异常。但是,如果我删除BufferedReader,那么它可以正常工作。

包com.toha.buffercheck;

import java.io.BufferedReader;

import java.io.InputStreamReader;

import java.net.URL;

import java.net.URLConnection;

import android.os.Bundle;  

import android.app.Activity;

import android.view.Menu;

import android.widget.EditText;

import android.widget.TextView;

public class Main extends Activity {

EditText ets , etc;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ets = (EditText) findViewById(R.id.editText1);
        etc = (EditText) findViewById(R.id.editText2);
        final TextView tv = (TextView) findViewById(R.id.textView1);
        try {
            URL url = null;


            url = new URL("http://www.google.com");
            URLConnection conn = url.openConnection();
            BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            tv.setText("Working Till Now");
        }
        catch(Exception e) {
            tv.setText("Stopped Working");
        }
    }

并且LogCat一直在说“应用程序可能在其主线程上工作太多”

PS:它在仿真器版本2.3.3上运行正常 但不适用于模拟器版本4.2.2

2 个答案:

答案 0 :(得分:2)

错误:“应用程序可能在其主线程上工作太多”

不要阻止UI线程 不要从UI线程外部访问Android UI工具包

工作线程

由于上面描述的单线程模型,对于您不应阻止UI线程的应用程序UI的响应性至关重要。如果您要执行的操作不是即时的,则应确保在单独的线程(“后台”或“工作线程”)中执行它们。

AsyncTask允许您在用户界面上执行异步工作。它在工作线程中执行阻塞操作,然后在UI线程上发布结果,而不需要您自己处理线程和/或处理程序。

不要在主线程中加载数据。使用其他线程进行http请求,例如:

new Thread(new Runnable() {
    public void run() {
       try {
          URL url = null;

          url = new URL("http://www.google.com");
          URLConnection conn = url.openConnection();
          BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
       } catch(Exception e) {
           Log.i("Error on load data:", "" + e.getMessage());
       }
    }
}).start();

或者使用AsyncTask加载数据:AsyncTask

Processes and Threads

答案 1 :(得分:0)

这里发生的事情很常见,您正试图在应用程序的主线程上执行一些长时间运行的操作。

这意味着,主线程负责更新UI,以实现流畅的体验,如果android检测到你正在做一些长时间运行的操作,它会阻塞,它会强制关闭应用程序,让你知道这很糟糕。

有许多替代解决方案,例如AsynTask或IntentService。

IntentService是一种在您向其发送意图时运行的服务:

public class NetworkHandler extends IntentService {
    @Override
    protected void onHandleIntent(Intent intent) {
         //Do your request here
    }
}

要激活IntentService,只需执行以下操作:

Intent intent = new Intent(mContext, NetworkHandler.class);
startService(intent);
相关问题