bluetoothを介してa mobileおよびa printerを接続してAndroidでテキストファイルを印刷する方法を誰かに教えてもらえますか?
つまり、Androidアプリケーションから印刷ボタンをクリックすると、プリンターは対応するファイルを印刷する必要があります。私の知る限りでは、Googleで検索しましたが見つかりませんでした。それを行うのに適したサンプルがあります。誰かが少なくとも1つのサンプルを持っている場合Androidこれを行うためのプログラム、それは私の混乱を取り除く方が良いでしょう。
提案してください。あなたの貴重な時間をありがとう!..
BluetoothプリンターAndroid例エディターで新しいAndroidプロジェクトBlueToothPrinterAppを作成します。
ステップ1:
以下のようなメインアクティビティを作成します
com.example.BlueToothPrinterApp/BlueToothPrinterApp.Java
package com.example.BlueToothPrinterApp;
import Android.app.Activity;
import Android.os.Bundle;
import Java.io.IOException;
import Java.io.OutputStream;
import Android.bluetooth.BluetoothSocket;
import Android.content.ContentValues;
import Android.content.Intent;
import Android.os.Environment;
import Android.view.View;
import Android.view.View.OnClickListener;
import Android.widget.Button;
import Android.widget.EditText;
import Android.widget.Toast;
public class BlueToothPrinterApp extends Activity
{
/** Called when the activity is first created. */
EditText message;
Button printbtn;
byte FONT_TYPE;
private static BluetoothSocket btsocket;
private static OutputStream btoutputstream;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
message = (EditText)findViewById(R.id.message);
printbtn = (Button)findViewById(R.id.printButton);
printbtn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
connect();
}
});
}
protected void connect() {
if(btsocket == null){
Intent BTIntent = new Intent(getApplicationContext(), BTDeviceList.class);
this.startActivityForResult(BTIntent, BTDeviceList.REQUEST_CONNECT_BT);
}
else{
OutputStream opstream = null;
try {
opstream = btsocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
btoutputstream = opstream;
print_bt();
}
}
private void print_bt() {
try {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
btoutputstream = btsocket.getOutputStream();
byte[] printformat = { 0x1B, 0×21, FONT_TYPE };
btoutputstream.write(printformat);
String msg = message.getText().toString();
btoutputstream.write(msg.getBytes());
btoutputstream.write(0x0D);
btoutputstream.write(0x0D);
btoutputstream.write(0x0D);
btoutputstream.flush();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onDestroy() {
super.onDestroy();
try {
if(btsocket!= null){
btoutputstream.close();
btsocket.close();
btsocket = null;
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
btsocket = BTDeviceList.getSocket();
if(btsocket != null){
print_bt();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
ステップ2:
com.example.BlueToothPrinterApp/BTDeviceList.Java
package com.example.BlueToothPrinterApp;
import Java.io.IOException;
import Java.util.Set;
import Java.util.UUID;
import Android.app.ListActivity;
import Android.bluetooth.BluetoothAdapter;
import Android.bluetooth.BluetoothDevice;
import Android.bluetooth.BluetoothSocket;
import Android.content.BroadcastReceiver;
import Android.content.Context;
import Android.content.Intent;
import Android.content.IntentFilter;
import Android.os.Bundle;
import Android.view.Menu;
import Android.view.MenuItem;
import Android.view.View;
import Android.widget.ArrayAdapter;
import Android.widget.ListView;
import Android.widget.Toast;
public class BTDeviceList extends ListActivity {
static public final int REQUEST_CONNECT_BT = 0×2300;
static private final int REQUEST_ENABLE_BT = 0×1000;
static private BluetoothAdapter mBluetoothAdapter = null;
static private ArrayAdapter<String> mArrayAdapter = null;
static private ArrayAdapter<BluetoothDevice> btDevices = null;
private static final UUID SPP_UUID = UUID
.fromString(“8ce255c0-200a-11e0-ac64-0800200c9a66″);
// UUID.fromString(“00001101-0000-1000-8000-00805F9B34FB”);
static private BluetoothSocket mbtSocket = null;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle(“Bluetooth Devices”);
try {
if (initDevicesList() != 0) {
this.finish();
return;
}
} catch (Exception ex) {
this.finish();
return;
}
IntentFilter btIntentFilter = new IntentFilter(
BluetoothDevice.ACTION_FOUND);
registerReceiver(mBTReceiver, btIntentFilter);
}
public static BluetoothSocket getSocket() {
return mbtSocket;
}
private void flushData() {
try {
if (mbtSocket != null) {
mbtSocket.close();
mbtSocket = null;
}
if (mBluetoothAdapter != null) {
mBluetoothAdapter.cancelDiscovery();
}
if (btDevices != null) {
btDevices.clear();
btDevices = null;
}
if (mArrayAdapter != null) {
mArrayAdapter.clear();
mArrayAdapter.notifyDataSetChanged();
mArrayAdapter.notifyDataSetInvalidated();
mArrayAdapter = null;
}
finalize();
} catch (Exception ex) {
} catch (Throwable e) {
}
}
private int initDevicesList() {
flushData();
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(getApplicationContext(),
“Bluetooth not supported!!”, Toast.LENGTH_LONG).show();
return -1;
}
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
mArrayAdapter = new ArrayAdapter<String>(getApplicationContext(),
Android.R.layout.simple_list_item_1);
setListAdapter(mArrayAdapter);
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
try {
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
} catch (Exception ex) {
return -2;
}
Toast.makeText(getApplicationContext(),
“Getting all available Bluetooth Devices”, Toast.LENGTH_SHORT)
.show();
return 0;
}
@Override
protected void onActivityResult(int reqCode, int resultCode, Intent intent) {
super.onActivityResult(reqCode, resultCode, intent);
switch (reqCode) {
case REQUEST_ENABLE_BT:
if (resultCode == RESULT_OK) {
Set<BluetoothDevice> btDeviceList = mBluetoothAdapter
.getBondedDevices();
try {
if (btDeviceList.size() > 0) {
for (BluetoothDevice device : btDeviceList) {
if (btDeviceList.contains(device) == false) {
btDevices.add(device);
mArrayAdapter.add(device.getName() + “\n”
+ device.getAddress());
mArrayAdapter.notifyDataSetInvalidated();
}
}
}
} catch (Exception ex) {
}
}
break;
}
mBluetoothAdapter.startDiscovery();
}
private final BroadcastReceiver mBTReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
try {
if (btDevices == null) {
btDevices = new ArrayAdapter<BluetoothDevice>(
getApplicationContext(), Android.R.id.text1);
}
if (btDevices.getPosition(device) < 0) {
btDevices.add(device);
mArrayAdapter.add(device.getName() + “\n”
+ device.getAddress() + “\n” );
mArrayAdapter.notifyDataSetInvalidated();
}
} catch (Exception ex) {
// ex.fillInStackTrace();
}
}
}
};
@Override
protected void onListItemClick(ListView l, View v, final int position,
long id) {
super.onListItemClick(l, v, position, id);
if (mBluetoothAdapter == null) {
return;
}
if (mBluetoothAdapter.isDiscovering()) {
mBluetoothAdapter.cancelDiscovery();
}
Toast.makeText(
getApplicationContext(),
“Connecting to ” + btDevices.getItem(position).getName() + “,”
+ btDevices.getItem(position).getAddress(),
Toast.LENGTH_SHORT).show();
Thread connectThread = new Thread(new Runnable() {
@Override
public void run() {
try {
boolean gotuuid = btDevices.getItem(position)
.fetchUuidsWithSdp();
UUID uuid = btDevices.getItem(position).getUuids()[0]
.getUuid();
mbtSocket = btDevices.getItem(position)
.createRfcommSocketToServiceRecord(uuid);
mbtSocket.connect();
} catch (IOException ex) {
runOnUiThread(socketErrorRunnable);
try {
mbtSocket.close();
} catch (IOException e) {
// e.printStackTrace();
}
mbtSocket = null;
return;
} finally {
runOnUiThread(new Runnable() {
@Override
public void run() {
finish();
}
});
}
}
});
connectThread.start();
}
private Runnable socketErrorRunnable = new Runnable() {
@Override
public void run() {
Toast.makeText(getApplicationContext(),
“Cannot establish connection”, Toast.LENGTH_SHORT).show();
mBluetoothAdapter.startDiscovery();
}
};
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
menu.add(0, Menu.FIRST, Menu.NONE, “Refresh Scanning”);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
super.onOptionsItemSelected(item);
switch (item.getItemId()) {
case Menu.FIRST:
initDevicesList();
break;
}
return true;
}
}
ステップ3:
Main.xmlファイルを編集して、以下のコードを貼り付けます。
res/layout/main.xml
<?xml version=”1.0″ encoding=”utf-8″?>
<RelativeLayout xmlns:Android=”http://schemas.Android.com/apk/res/Android”
Android:layout_width=”fill_parent”
Android:layout_height=”fill_parent”
Android:paddingLeft=”16dp”
Android:paddingRight=”16dp” >
<TextView
Android:id="@+id/msgtextlbl"
Android:layout_width="match_parent"
Android:layout_height="wrap_content"
Android:text="Enter Your Message : "/>
<EditText
Android:id="@+id/message"
Android:layout_width="fill_parent"
Android:layout_height="100dp"
Android:layout_below="@+id/msgtextlbl"
Android:text=""/>
<Button
Android:id="@+id/printButton"
Android:layout_width="fill_parent"
Android:layout_height="wrap_content"
Android:layout_below="@+id/message"
Android:layout_centerHorizontal="true"
Android:layout_marginTop="5dip"
Android:text="Print"/>
</RelativeLayout>
ステップ4:
次にAndroidManifest.xmlを編集します
Bluetooth権限と管理者権限を追加します。
AndroidManifest.xml
<?xml version=”1.0″ encoding=”utf-8″?>
<manifest xmlns:Android=”http://schemas.Android.com/apk/res/Android”
package=”com.example.BlueToothPrinterApp”
Android:versionCode=”1″
Android:versionName=”1.0″>
<application Android:label=”@string/app_name” Android:icon=”@drawable/ic_launcher”>
<activity Android:name=”BlueToothPrinterApp”
Android:label=”@string/app_name”>
<intent-filter>
<action Android:name=”Android.intent.action.MAIN” />
<category Android:name=”Android.intent.category.LAUNCHER” />
</intent-filter>
</activity>
<activity Android:name=”BTDeviceList”></activity>
</application>
<uses-sdk Android:minSdkVersion=”14″ />
<uses-permission Android:name=”Android.permission.BLUETOOTH”></uses-permission>
<uses-permission Android:name=”Android.permission.BLUETOOTH_ADMIN”></uses-permission>
</manifest>
このアプリケーションをコンパイルして実行します。メッセージを入力し、印刷ボタンを押します。
Bluetoothデバイスのリストが表示されます。 Bluetoothプリンターを選択します。
Bluetoothプリンターで印刷を確認します。
この素晴らしいlibを使用して、任意のプリンターに接続して簡単に印刷できます。
https://github.com/mazenrashed/Printooth
次の方法でダウンロードできます。
implementation 'com.github.mazenrashed:Printooth:${LAST_VERSION}'
そしてそれを次のように使用します:
var printables = ArrayList<Printable>()
var printable = Printable.PrintableBuilder()
.setText("Hello World")
printables.add(printable)
BluetoothPrinter.printer().print(printables)