如何从Android平板电脑通过wifi打印机打印一个简单的文本

时间:2014-05-13 10:43:03

标签: android printing

正在开发一个需要打印选项的Android应用程序。我使用以下代码在wifi打印机中执行此操作,但它提供Networkonmainthread exception

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();
}

有谁知道这是怎么回事?我需要一个用于在打印机打印的示例代码.....谢谢

2 个答案:

答案 0 :(得分:0)

我的代码正在运行: WifiPrint.java

  

公共类WifiPrint扩展了Activity {TextView printer_name,   gate_way,printer_port; int port = 9100; WifiManager wifi = null;     android.net.DhcpInfo d; String gateway_ip =“”;

     

@Override protected void 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); * /

     

}

     

@Override public boolean onCreateOptionsMenu(Menu menu){//   给菜单充气;这会将项目添加到操作栏(如果存在)。         getMenuInflater()。inflate(R.menu.wifi_print,menu);返回true;     }

     

public void wifisettings(View v){startActivityForResult(new   意图(                 android.provider.Settings.ACTION_WIFI_SETTINGS),0); }

     

public void connectSocket(View v){
                / * Uri filepath = 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(); }

     

public String intToIp(int i){return((i& 0xFF)+“。”+((i>> 8)   &安培; 0xFF)+“。” +((i>>> 16)& 0xFF)                 +“。” +((i>>> 24)& 0xFF)); }

     

@Override protected void onActivityResult(int requestCode,int   resultCode,Intent data){// 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);

  }   }
     

public File 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;     }
     

class ClientThread实现Runnable {String filepath =“”;         BufferedInputStream bis = null; FileInputStream fis;

  Socket socket;

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

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

存根尝试{
                InputStream in = getResources()。openRawResource(R.raw.pdfsample);                 createFileFromInputStream(IN);                 文件pdfFile =新文件(“/ sdcard / testpdf.pdf”);                 byte [] mybytearray = new byte [(int)pdfFile.length()];                 socket = new Socket(gateway_ip,port);                 runOnUiThread(new Runnable(){
                    @覆盖                     public void run(){                         // TODO自动生成的方法存根                         如果(socket.isConnected()){                             Toast.makeText(WifiPrint.this,                                     “Socket Connected”,                                     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();
                  }
              });
          }           }       }
     

}

     

}

并在清单文件中添加某些权限:

  

                                                

<uses-feature android:name="android.hardware.wifi" />

答案 1 :(得分:0)

只需将此代码粘贴到您的主要活动中即可。

StrictMode.setThreadPolicy(new Builder().detectDiskReads().detectDiskWrites().detectNetwork().penaltyLog().build());
    StrictMode.setVmPolicy(new VmPolicy.Builder().detectLeakedSqlLiteObjects().detectLeakedClosableObjects().penaltyLog().penaltyDeath().build());