簡體   English   中英

如何從Android平板電腦通過wifi打印機打印簡單的文本

[英]how to print a simple text via wifi printer from android tablet

正在開發一個需要打印選項的 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();
}

有誰知道如何做到這一點? 我需要一個在 wifi 打印機中打印的示例代碼.....謝謝

我的代碼正在運行:WifiPrint.java

公共類 WifiPrint 擴展 Activity { TextView 打印機名稱、網關、打印機端口; 內部端口 = 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); 打印機名稱 = (TextView) findViewById(R.id.textView1); gate_way = (TextView) findViewById(R.id.textView2); 打印機端口 = (TextView) findViewById(R.id.textView3); /* de.lohndirekt.print.IppPrintService svc = new IppPrintService(printerURI); InputStream stream = new BufferedInputStream(new FileInputStream("image.epl")); DocFlavor 風味 = DocFlavor.INPUT_STREAM.AUTOSENSE; Doc myDoc = new SimpleDoc(stream, flavor, null); DocPrintJob 作業 = svc.createPrintJob(); job.print(myDoc, null);*/

}

@Override public boolean onCreateOptionsMenu(Menu menu) { // 使菜單膨脹; 如果它存在,這會將項目添加到操作欄。 getMenuInflater().inflate(R.menu.wifi_print, menu); 返回真; }

public void wifisettings(View v) { startActivityForResult(new Intent(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 = 新線程(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("打印機IP:" + gateway_ip); printer_port.setText("端口:" + 端口);

 } }

公共文件 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 { 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); File pdfFile = new File("/sdcard/testpdf.pdf"); byte[] mybytearray = new byte[(int) pdfFile.length()]; socket = new Socket(gateway_ip, port); runOnUiThread(new Runnable() {
@Override public void run() { // TODO 自動生成的方法存根 if(socket.isConnected()){ Toast.makeText(WifiPrint.this, "Socket Connected", Toast.LENGTH_LONG).show();
}
} });
fis = new FileInputStream(pdfFile); bis = 新的 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" />

只需將此代碼粘貼到您的主要活動中即可。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM