搜索网络打印机NetworkOnMainThreadException

时间:2014-05-20 00:44:45

标签: android networking printing

当我运行此代码时,我得到一个android.os.NetworkOnMainThreadException,jar由打印机制造商提供。 StarIOPort.searchPrinter出现错误。我没有得到运行制造商提供的演示代码的错误。

我正在尝试查看本地网络上是否有可用的网络打印机。

private void PortDiscovery(String interfaceName)
{
final EditText editPortName;
ArrayList<String> arrayPortName;    
List<PortInfo> BTPortList;
List<PortInfo> TCPPortList; 
final ArrayList<PortInfo> arrayDiscovery;

try {
     if (true == interfaceName.equals("BT")) {
         BTPortList  = StarIOPort.searchPrinter("BT:");   

         for (PortInfo portInfo : BTPortList) {
                arrayDiscovery.add(portInfo);
         }
    }
    if (true == interfaceName.equals("LAN")) {
        TCPPortList = StarIOPort.searchPrinter("TCP:");

        for (PortInfo portInfo : TCPPortList) {
            arrayDiscovery.add(portInfo);
        }
   }

   arrayPortName = new ArrayList<String>();

   for(PortInfo discovery : arrayDiscovery) {
       String portName;
       portName = discovery.getPortName();

  if(discovery.getMacAddress().equals("") == false) {
      portName += "\n - " + discovery.getMacAddress();
          if(discovery.getModelName().equals("") == false) {
         portName += "\n - " + discovery.getModelName();
      }
  }
  arrayPortName.add(portName);
 }

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

 editPortName = new EditText(this);

 new AlertDialog.Builder(this).setTitle("Please Input Port Name").setView(editPortName).setPositiveButton("OK", new DialogInterface.OnClickListener(){
     public void onClick(DialogInterface dialog, int button){
     EditText portNameField = (EditText)findViewById(R.id.printerName);
         portNameField.setText(editPortName.getText());
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener(){
    public void onClick(DialogInterface dialog, int button) {
}
})
.setItems(arrayPortName.toArray(new String[0]), new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int select) {
EditText portNameField = (EditText)findViewById(R.id.printerName);portNameField.setText(arrayDiscovery.get(select).getPortName());

    }
    })
.show();


}

1 个答案:

答案 0 :(得分:1)

您正在获取NetworkOnMainThreadException,因为Android操作系统不允许在主线程(有时也称为UI线程)上运行繁重的进程(如网络相关操作),因为这些操作/进程可能会占用很多资源和操作时间,因此,应用程序可能会滞后。

解决方案是将您的流程置于可执行线程中,并在onCreate()或您需要的地方实例化该线程,例如,在onClickListener();上。是这样的:

private class Print extends AsyncTask<String, Void, String> {
    ProgressDialog pDialog;

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        Log.d("Hi", "Print Commencing");

        pDialog = new ProgressDialog(MainActivity.this);
        pDialog.setMessage("Printing...");


        String message= "Printing";

        SpannableString ss2 =  new SpannableString(message);
        ss2.setSpan(new RelativeSizeSpan(2f), 0, ss2.length(), 0);  
        ss2.setSpan(new ForegroundColorSpan(Color.BLACK), 0, ss2.length(), 0); 

        pDialog.setMessage(ss2);

        pDialog.setCancelable(false);
        pDialog.show();
    }

    @Override
    protected String doInBackground(String... params) {
        Log.d("Hi", "Printing");
        //Toast.makeText(getApplicationContext(), "Printing.", Toast.LENGTH_LONG).show();

        //insert your code here 

        return "Executed!";

    }

    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        //Toast.makeText(getApplicationContext(), "Done printing.", Toast.LENGTH_LONG).show();
        Log.d("Hi", "Done Printing.");
        pDialog.dismiss();

    }
}

并从类似的函数中调用它:

new Print().execute("")

onPreExecute()中,我初始化了一个不可取消的progressDialog,以保证您的流程正常结束。您应该在doInBackground();部分插入代码。