1

我想通过蓝牙或 WiFi 从我的应用程序在 android 8 中打印文本文件。请建议我解决方案。

4

2 回答 2

1

这是一个样本

package com.example.untitled2;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;

public class MyActivity extends Activity {
    private static final UUID MY_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button btn = (Button) findViewById(R.id.button);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
                if (mBluetoothAdapter == null) {
                    Toast.makeText(MyActivity.this, "no device", Toast.LENGTH_LONG).show();
                }
                if (!mBluetoothAdapter.isEnabled()) {
                    mBluetoothAdapter.enable();
                }
                Set<BluetoothDevice> bluetoothDevices = mBluetoothAdapter.getBondedDevices();
                if (bluetoothDevices.size() == 0)
                    return;
                OutputStream mmOutStream;
                BluetoothDevice device = bluetoothDevices.iterator().next();
                try {
                    BluetoothSocket socket = device.createRfcommSocketToServiceRecord(MY_UUID);
                    socket.connect();
                    mmOutStream = socket.getOutputStream();
                    /*String textPrint = ""+(char) 27 + (char)116 + (char) 27;*/
                    String textPrint = "this is example text"+(char)10;
                    mmOutStream.flush();
                    mmOutStream.write(textPrint.getBytes());
                    mmOutStream.flush();
                    for (int i = 0; i < 10; i++) {
                        mmOutStream.write(textPrint.getBytes());
                    }
                    mmOutStream.flush();
                    //mmOutStream.wait();
                    mmOutStream.close();
                    socket.close();
                } catch (IOException e) {
                    Toast.makeText(MyActivity.this, e.getMessage(), Toast.LENGTH_LONG).show();
                }

            }
        });
    }
}
于 2013-01-14T12:39:54.367 回答
0

这是我的代码 [在网上找到并根据我的要求修改] 以连接到蓝牙打印机,完美运行......尝试了 n 测试。:-)

package com.nvsoft.s2pay.mmsl.bluetoothprinter;

import android.app.Activity;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Set;
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 com.nvsoft.s2pay.sms.DynaCCSmsServiceConstants;
import com.nvsoft.s2pay.util.StringUtil;

import java.util.HashSet;

import org.json.me.JSONObject;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

//This class is meant for wrapping the Bluetooth connecting interface provided by android devices.......
//Basically is a state machine, and the communications will happen in a separate thread so as not to obstruct the main UI
public class BTWrapperActivity extends Activity {
public static final int REQUEST_CONNECT_BT = 0x2300;//8960
public static final int REQUEST_ENABLE_BT = 0x1000;//4096
public static final String DEVICES_DISCOVERED = "DD";
public static final String EXTRA_DEVICE_ADDRESS = DynaCCSmsServiceConstants.PRINTER_MAC_ADDRESS;
private static final String ERROR = "ecode";
private static final String ERROR_MSG = "emsg";
public static int ERROR_CODE = 0;
int request;
static private BluetoothAdapter mBluetoothAdapter = null;
static private Set<BluetoothDevice> btDevices = null;
String deviceNames = null;
JSONObject jobj = new JSONObject();
Intent parentIntent = null;
BluetoothDevice selectedDevice = null;

    static private BluetoothSocket mbtSocket = null;


@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    Bundle bundle = getIntent().getExtras();
    deviceNames = bundle.getString(EXTRA_DEVICE_ADDRESS);


    parentIntent = getIntent();
    request = bundle.getInt(BluetoothFilePrinter.REQUEST_CODE);

    try {

            if (request != DynaCCSmsServiceConstants.EXIT_ACTIVITY_REQUEST){
                if (initDevicesList() != 0) {
                this.finish();
                return;
                } 
            }
    } catch (Exception ex) {
        getIntent().putExtra(ERROR, 701);
        getIntent().putExtra(ERROR_MSG, ex.getMessage());

        finish();
        return;
    }
    // Register the Broadcast receiver for handling new BT device discovery
    //IntentFilter btIntentFilter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
    //this.registerReceiver(mBTReceiver, new IntentFilter(DynaCCSmsServiceConstants.ACTION_EXIT_ACTIVITY));
    this.registerReceiver(mBTReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
    this.registerReceiver(mBTReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_CONNECTED));
    this.registerReceiver(mBTReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED));
    this.registerReceiver(mBTReceiver, new IntentFilter(BluetoothDevice.ACTION_ACL_DISCONNECTED));
    this.registerReceiver(mBTReceiver, new IntentFilter(BluetoothAdapter.ACTION_DISCOVERY_FINISHED));
    this.registerReceiver(mBTReceiver, new IntentFilter(Intent.ACTION_SCREEN_ON));
    this.registerReceiver(mBTReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));

    if (request == DynaCCSmsServiceConstants.EXIT_ACTIVITY_REQUEST) {
        unregisterReceiver(mBTReceiver);
        this.finish();
    }
}

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 (deviceNames!=null) {
            deviceNames = null;
        }
        finalize();
       } catch(Exception ex){
            getIntent().putExtra(ERROR, 702);
            getIntent().putExtra(ERROR_MSG, ex.getMessage());
    } catch (Throwable e) {
        getIntent().putExtra(ERROR, 702);
        getIntent().putExtra(ERROR_MSG, e.getMessage());
    }

}

// This method will Connect to our SPP Bluetooth Device after discovering and pairing if required
// Do not forget to add the permission for Bluetooth to use this method
// Also this method is very tightly coupled with the above method, for getting the status of bt connection  
private int initDevicesList() {
    // Flush any Pending Data to rediscover devices
    if (request == DynaCCSmsServiceConstants.DISCOVER_REQUEST) {
        flushData();
    }
    // Get the Bluetooth Adaptor of the device
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null) {
        return -1;
    }
    if (mBluetoothAdapter.isDiscovering()) {
        mBluetoothAdapter.cancelDiscovery();
    }
    // ENABLE BLUETOOTH on DEVICE if not ALREADY TURNED ON
    Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
    try {
        startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
    } catch (Exception ex) {
        return -2;
    }
    return 0;
} // End getDeviceList

@Override
protected void onActivityResult(int reqCode, int resultCode, Intent intent) {
    super.onActivityResult(reqCode, resultCode, intent);
    if (intent == null) {
        intent = getIntent();
    }
    switch (reqCode) {
        case REQUEST_ENABLE_BT:
            if (request == DynaCCSmsServiceConstants.DISCOVER_REQUEST) {
                if (resultCode == RESULT_OK) {
                    // Start getting the paired devices list
                    Set<BluetoothDevice> btDeviceList = mBluetoothAdapter.getBondedDevices();
                    // If there are paired devices
                    try {
                        if (btDeviceList.size() > 0) {
                            // Loop through paired devices
                            for (BluetoothDevice device : btDeviceList) {
                                jobj.put(device.getName(), device.getAddress());
                                if (btDeviceList.contains(device) == false) {
                                    btDevices.add(device); // Add the device to the device list
                                    jobj.put(device.getName(), device.getAddress());
                                }
                            }
                            if (jobj != null) {
                                intent.putExtra(DEVICES_DISCOVERED, jobj.toString());
                            }
                            setResult(Activity.RESULT_OK, intent);
                            finish();

                        } else {
                            mBluetoothAdapter.startDiscovery();
                        }
                    } catch (Exception ex) {
                        getIntent().putExtra(ERROR, 704);
                        getIntent().putExtra(ERROR_MSG, ex.getMessage());
                        setResult(Activity.RESULT_CANCELED, intent);
                    }
                } else {
                    getIntent().putExtra(ERROR, 704);
                    getIntent().putExtra(ERROR_MSG, "Permission to enable Bluetooth on the device was denied. Please enable Bluetooth and retry.");
                    setResult(Activity.RESULT_CANCELED, intent);
                    finish();
                }
            }//end of discovery
            else if (request == DynaCCSmsServiceConstants.CONNECT_REQUEST || request == DynaCCSmsServiceConstants.PRINT_REQUEST) {
                    if (resultCode == RESULT_OK) {
                        if (deviceNames!=null) {
                            connect(deviceNames);
                        }else{
                            getIntent().putExtra(ERROR, 704);
                            getIntent().putExtra(ERROR_MSG, "Could not find any printer.");
                            setResult(Activity.RESULT_CANCELED, intent);
                            finish();
                        }
                    }else{
                        getIntent().putExtra(ERROR, 704);
                        getIntent().putExtra(ERROR_MSG, "Permission to enable Bluetooth on the device was denied. Please enable Bluetooth and retry.");
                        setResult(Activity.RESULT_CANCELED, intent);
                        finish();
                    }
            }
            break;
        case REQUEST_CONNECT_BT:
            if (resultCode == Activity.RESULT_OK) {
                setResult(Activity.RESULT_OK, intent);
            } else {
                setResult(Activity.RESULT_CANCELED, intent);
            }
            finish();
            break;
    }
}

private final BroadcastReceiver mBTReceiver = new BroadcastReceiver() {

    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        // Get the BluetoothDevice object from the Intent
        BluetoothDevice device ;
        // When discovery finds a device
        if (BluetoothDevice.ACTION_FOUND.equals(action)) {
            device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            try {
                // No paired device found
                if (btDevices == null) {
                    btDevices = new HashSet<BluetoothDevice>();
                    btDevices.add(device);
                    jobj.put(device.getName(), device.getAddress());
                } else {
                    if (!btDevices.contains(device)) {
                        btDevices.add(device);
                        jobj.put(device.getName(), device.getAddress());
                    }
                }
                intent.putExtra(DEVICES_DISCOVERED, jobj.toString());
            } catch (Exception ex) {
                  getIntent().putExtra(ERROR, 705);
                  getIntent().putExtra(ERROR_MSG, ex.getMessage());
            }
        } else if (BluetoothDevice.ACTION_ACL_CONNECTED.equals(action)) {
            intent.putExtra("IS_CONNECTED", true);
        } else if (BluetoothDevice.ACTION_ACL_DISCONNECT_REQUESTED.equals(action)) {
//#ifndef REMOVE_DEBUG               
                logger.debug("BTWrapperActivity - ", " Device is about to disconnect");
//#endif                
            } else if (BluetoothDevice.ACTION_ACL_DISCONNECTED.equals(action)) {
//#ifndef REMOVE_DEBUG               
                logger.debug("BTWrapperActivity - ", "Device has disconnected");
//#endif        
                    intent.putExtra("IS_CONNECTED", false);
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
//#ifndef REMOVE_DEBUG               
                logger.debug("BTWrapperActivity - ", "DISCOVERY FINISSHED");
//#endif
                if (request == DynaCCSmsServiceConstants.DISCOVER_REQUEST) {
                    intent.putExtra(DEVICES_DISCOVERED, jobj.toString());
                    sendDiscoveryResult(intent);
                }
            }else if(Intent.ACTION_SCREEN_ON.equals(action)){
//#ifndef REMOVE_DEBUG               
                logger.debug("BTWrapperActivity - ", "SCREEN ON");
//#endif
            }else if(Intent.ACTION_SCREEN_OFF.equals(action)){
//#ifndef REMOVE_DEBUG               
                logger.debug("BTWrapperActivity - ", "SCREEN OFF");
//#endif
        }
        }
    };

private void connect(final String deviceAddress) {
    mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    if (mBluetoothAdapter == null) {
        return;
    } else {
        selectedDevice = mBluetoothAdapter.getRemoteDevice(deviceAddress);
    }
    // Cancel the dicovery if still going on
    if (mBluetoothAdapter.isDiscovering()) {
        mBluetoothAdapter.cancelDiscovery();
    }
    if (mbtSocket != null) {
        try {
            mbtSocket.close();
        } catch (IOException ex) {
            getIntent().putExtra(ERROR, 706);
            getIntent().putExtra(ERROR_MSG, ex.getMessage());
            setResult(Activity.RESULT_CANCELED, getIntent());
            finish();
        }
        mbtSocket = null;
    }

    // Try to connect with the selected device,
    // made the thread different as the connecting proceedure might break down the system
    Thread connectThread = new Thread(new Runnable() {
        @Override
        public void run() {
           Intent intent = getIntent();
           String errMsg = "";
           try {
                try {
                    Method m = selectedDevice.getClass().getMethod("createInsecureRfcommSocket", new Class[]{int.class});
                    try {
                        mbtSocket = (BluetoothSocket) m.invoke(selectedDevice, 1);
                    } catch (IllegalArgumentException e) {
                        errMsg = e.getMessage();
                        getIntent().putExtra(ERROR, 707);
                        getIntent().putExtra(ERROR_MSG, errMsg);
                    } catch (IllegalAccessException e) {
                        errMsg = e.getMessage();
                        getIntent().putExtra(ERROR, 708);
                        getIntent().putExtra(ERROR_MSG, errMsg);
                    } catch (InvocationTargetException e) {
                        errMsg = e.getMessage();
                        getIntent().putExtra(ERROR, 709);
                        getIntent().putExtra(ERROR_MSG, errMsg);
                    }finally{
                        if (!StringUtil.isEmpty(errMsg) && intent.getExtras().getInt(ERROR)>0) {
                            setResult(Activity.RESULT_CANCELED, getIntent());
                            finish();
                        }
                    }
                } catch (SecurityException e) {
                    errMsg = e.getMessage();
                    getIntent().putExtra(ERROR, 710);
                    getIntent().putExtra(ERROR_MSG, errMsg);
                    setResult(Activity.RESULT_CANCELED, getIntent());
                    finish();
                } catch (NoSuchMethodException e) {
                    errMsg = e.getMessage();
                    getIntent().putExtra(ERROR, 711);
                    getIntent().putExtra(ERROR_MSG, errMsg);
                    setResult(Activity.RESULT_CANCELED, getIntent());
                    finish();
                }
                //mbtSocket = 

selectedDevice.createRfcommSocketToServiceRecord(SPP_UUID);
                    ERROR_CODE = intent.getExtras().getInt(ERROR);
//#ifndef REMOVE_DEBUG                    
                    logger.debug("ERROR = ", ERROR_CODE);
//#endif                    
                    if (ERROR_CODE == 0) {
                        mbtSocket.connect();
//#ifndef REMOVE_DEBUG                        
                        logger.debug("@@BTWrapperActivity - ", "Connected to selectedDevice = " + (String) intent.getExtras().get(EXTRA_DEVICE_ADDRESS));
//#endif

                    intent.putExtra("IS_CONNECTED", true);
                    setResult(Activity.RESULT_OK, intent);
                } else {
                    intent.putExtra(ERROR, ERROR_CODE);
                    intent.putExtra(ERROR_MSG,errMsg);
                    setResult(Activity.RESULT_CANCELED, intent);
                    finish();
                }
            } catch (IOException ex) {
                getIntent().putExtra(ERROR, 712);
                getIntent().putExtra(ERROR_MSG, "Unable to Connect to the Printer. Please verify the printer settings and try again.");
                getIntent().putExtra("IS_CONNECTED", false);
                ex.printStackTrace();

                setResult(Activity.RESULT_CANCELED, intent);
                finish();
            }finally{

               finish();
            }
        }
    });
    connectThread.start();

}

private Runnable socketErrorRunnable = new Runnable() {
    @Override
    public void run() {
        getIntent().putExtra(ERROR, 714);
        getIntent().putExtra(ERROR_MSG,"Cannot establish connection");

        mBluetoothAdapter.startDiscovery();
    }
};

protected void onStop() {

    unregisterReceiver(mBTReceiver);
    super.onStop();
}

private void sendDiscoveryResult(Intent mIntent){
    mIntent.putExtra(DEVICES_DISCOVERED, jobj.toString());
    setResult(Activity.RESULT_OK, mIntent);
    finish();
}

private String getDisplayMessage(){
    String message = "Please Wait!!";
    switch(request) {
        case DynaCCSmsServiceConstants.DISCOVER_REQUEST :
            message = "Discovery in progress!!";
            break;
        case DynaCCSmsServiceConstants.CONNECT_REQUEST:
            message = "Connecting...Please Wait!!";
            break;
        case DynaCCSmsServiceConstants.PRINT_REQUEST:
            message = "Printing in progress!!";
            break;
    }
    return message;
}} // End of class definition
于 2014-01-22T05:49:01.173 回答