2014-05-13 97 views
0

正在开发一个需要打印选项的Android应用程序。我用下面的代码的WiFi打印机要做到这一点,但它给Networkonmainthread exception如何从Android平板电脑通过WiFi打印机打印简单文本

try { 
    Socket sock = new Socket("192.168.199.245", 9100); // ip and port of printer 
    PrintWriter oStream = new PrintWriter(sock.getOutputStream()); 
    oStream.println("\t\t Text to The Printer"); 
    oStream.println("\n\n\n"); 
    oStream.close(); 
    sock.close(); 
} catch (UnknownHostException e) { 
    e.printStackTrace(); 
} catch (IOException e) { 
    e.printStackTrace(); 
} 

有没有人知道如何做到这一点?我需要在无线网络打印机打印一个示例代码.....感谢

+0

http://stackoverflow.com/questions/9745859/networkonmainthread – ASP

+0

使用 “StrictMode”,但不建议.... – ASP

+0

@ user3632006请问上面的代码工作? – VVB

回答

0

我的代码工作: WifiPrint.java

公共类WifiPrint延伸活动{TextView的打印机名称, gate_way,printer_port; int port = 9100; WifiManager wifi = null; android.net.DhcpInfo d;字符串gateway_ip =“”;

@Override保护无效的onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.activity_wifi_print); wifi =(WifiManager) getSystemService(Context.WIFI_SERVICE); printer_name =(TextView) findViewById(R.id.textView1); gate_way =(TextView) findViewById(R.id.textView2); printer_port =(TextView) findViewById(R.id.textView3); /* de.lohndirekt.print.IppPrintService svc = new IppPrintService(printerURI); InputStream stream = new BufferedInputStream(new FileInputStream(“image.epl”)); DocFlavor flavor = DocFlavor.INPUT_STREAM.AUTOSENSE; Doc myDoc = new SimpleDoc(stream,flavor,null); DocPrintJob job = svc.createPrintJob(); job.print(myDoc,NULL); */

}

@覆盖公共布尔onCreateOptionsMenu(菜单菜单){// 充气菜单;这会将项目添加到操作栏(如果存在)。 getMenuInflater()。inflate(R.menu.wifi_print,menu);返回true; }

公共无效wifisettings(视图v){startActivityForResult(新 意图( android.provider.Settings.ACTION_WIFI_SETTINGS),0); }

公共无效connectSocket(视图v){
/*乌里文件路径= Uri.parse( “android.resource://” + getPackageName()+ “/” + R.raw.pdfsample); Toast.makeText(this,filepath.getPath(),Toast.LENGTH_LONG).show(); */ClientThread clientThread = new ClientThread(“”);线程clientstartThread = new 线程(clientThread); clientstartThread.start(); }

公共字符串intToIp(int i)以{返回(第(i &为0xFF)+ “” +((I >> 8) &为0xFF)+ “” +((I >> 16)& 0xFF的) +“。”+((i >> 24)& 0xFF)); }

@覆盖保护无效onActivityResult(INT requestCode,整数 resultCode为,意图数据){// TODO自动生成方法存根

super.onActivityResult(requestCode, resultCode, data);  if 

(requestCode == 0){WifiInfo wifiinfo = wifi.getConnectionInfo (); d = wifi。getDhcpInfo();

 printer_name.setText("Name:" + wifiinfo.getSSID());    gateway_ip = 

intToIp(d.gateway); gate_way.setText(“Printer Ip:”+ gateway_ip); printer_port.setText(“Port:”+ port);

} } 

公共文件createFileFromInputStream(InputStream的的inputStream){

try{ 
    File f = new File("/sdcard/testpdf.pdf"); 
    OutputStream outputStream = new FileOutputStream(f); 
    byte buffer[] = new byte[1024]; 
    int length = 0; 

    while((length=inputStream.read(buffer)) > 0) { 
     outputStream.write(buffer,0,length); 
    } 

    outputStream.close(); 
    inputStream.close(); 

    return f; 
}catch (IOException e) { 
     //Logging exception 
} 

return null;  } 

类ClientThread实现Runnable {字符串文件路径= “”; BufferedInputStream bis = null; FileInputStream fis;

Socket socket; 

    public ClientThread(String filename) {   filepath = filename;  } 

    @Override  public void run() {    // TODO Auto-generated method 

存根尝试{
的InputStream在= getResources()openRawResource(R.raw.pdfsample)。 createFileFromInputStream(in); File pdfFile = new File(“/ sdcard/testpdf.pdf”); byte [] mybytearray = new byte [(int)pdfFile.length()]; socket = new Socket(gateway_ip,port); runOnUiThread(新的Runnable(){
@Override 公共无效的run(){// TODO自动生成方法存根 如果(socket.isConnected()){ Toast.makeText(WifiPrint.this, “插座连接“, Toast.LENGTH_LONG).show();
}
} });
fis = new FileInputStream(pdfFile); bis = new BufferedInputStream(fis); bis.read(mybytearray,0,mybytearray.length); OutputStream os = socket.getOutputStream(); os.write(mybytearray,0,mybytearray.length); os.flush();

  if (bis != null) { 
       bis.close(); 
       os.close(); 
       socket.close(); 
       fis.close(); 

      } 
       } catch (final UnknownHostException e) { 
      // TODO Auto-generated catch block 
      runOnUiThread(new Runnable() { 

       @Override 
       public void run() { 
        // TODO Auto-generated method stub 
        Toast.makeText(WifiPrint.this, 
          "UnHost Exceptions" + e.getMessage(), 
          Toast.LENGTH_LONG).show(); 

       } 
      });    } catch (final IOException e) { 
      // TODO Auto-generated catch block 
      runOnUiThread(new Runnable() { 

       @Override 
       public void run() { 
        // TODO Auto-generated method stub 
        Toast.makeText(WifiPrint.this, 
          "Io Exceptions" + e.getMessage(), 
          Toast.LENGTH_LONG).show(); 

       } 
      });    } finally { 
      try { 
       if (bis != null) { 
        bis.close(); 
        socket.close(); 
        fis.close(); 
       } 
      } catch (final IOException e) { 
       // TODO Auto-generated catch block 
       runOnUiThread(new Runnable() { 
        @Override 
        public void run() { 
         // TODO Auto-generated method stub 
         Toast.makeText(
           WifiPrint.this, 
           "Io Exeption in Closing Socket" 
             + e.getMessage(), Toast.LENGTH_LONG) 
           .show(); 
        } 
       }); 
      }   }  } 

}

}

而且清单文件添加某些permssions:

<uses-feature android:name="android.hardware.wifi" /> 
相关问题