Android connect to bluetooth device with click button on bluetooth device - android

I have device bluetooth with button, I want connect to this device after click button on this device, it's there any example to do this?

May this help you.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity implements Runnable {
protected static final String TAG = "TAG";
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
Button mScan, mPrint;
static OutputStream outStream;
BluetoothAdapter mBluetoothAdapter;
private UUID applicationUUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private ProgressDialog mBluetoothConnectProgressDialog;
static BluetoothSocket mBluetoothSocket;
BluetoothDevice mBluetoothDevice;
#Override
public void onCreate(Bundle mSavedInstanceState) {
super.onCreate(mSavedInstanceState);
setContentView(R.layout.activity_main);
mScan = (Button) findViewById(R.id.Scan);
mScan.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(MainActivity.this, "Message1", 2000).show();
} else {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent,
REQUEST_ENABLE_BT);
} else {
ListPairedDevices();
Intent connectIntent = new Intent(MainActivity.this,
DeviceListActivity.class);
startActivityForResult(connectIntent,
REQUEST_CONNECT_DEVICE);
}
}
}
});
mPrint = (Button) findViewById(R.id.mPrint);
mPrint.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
Thread t = new Thread() {
public void run() {
try {
if (mBluetoothSocket != null) {
//code for send data on printer to print
sendDataToDevice("Hello");
}
// printer specific code you can comment ==== > End
} catch (Exception e) {
Log.e("Main", "Exe ", e);
}
}
};
t.start();
}
});
/* mDisc = (Button) findViewById(R.id.dis); */
/*
* mDisc.setOnClickListener(new View.OnClickListener() { public void
* onClick(View mView) { if (mBluetoothAdapter != null)
* mBluetoothAdapter.disable(); } });
*/
}// onCreate
public void onActivityResult(int mRequestCode, int mResultCode,
Intent mDataIntent) {
super.onActivityResult(mRequestCode, mResultCode, mDataIntent);
switch (mRequestCode) {
case REQUEST_CONNECT_DEVICE:
if (mResultCode == Activity.RESULT_OK) {
Bundle mExtra = mDataIntent.getExtras();
String mDeviceAddress = mExtra.getString("DeviceAddress");
Log.v(TAG, "Coming incoming address " + mDeviceAddress);
mBluetoothDevice = mBluetoothAdapter
.getRemoteDevice(mDeviceAddress);
mBluetoothConnectProgressDialog = ProgressDialog.show(this,
"Connecting...", mBluetoothDevice.getName() + " : "
+ mBluetoothDevice.getAddress(), true, false);
Thread mBlutoothConnectThread = new Thread(this);
mBlutoothConnectThread.start();
// pairToDevice(mBluetoothDevice); This method is replaced by
// progress dialog with thread
}
break;
case REQUEST_ENABLE_BT:
if (mResultCode == Activity.RESULT_OK) {
ListPairedDevices();
Intent connectIntent = new Intent(MainActivity.this,
DeviceListActivity.class);
startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
} else {
Toast.makeText(MainActivity.this, "Message", 2000).show();
}
break;
}
}
private void ListPairedDevices() {
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter
.getBondedDevices();
if (mPairedDevices.size() > 0) {
for (BluetoothDevice mDevice : mPairedDevices) {
Log.v(TAG, "PairedDevices: " + mDevice.getName() + " "
+ mDevice.getAddress());
}
}
}
public void run() {
try {
mBluetoothSocket = mBluetoothDevice
.createRfcommSocketToServiceRecord(applicationUUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket.connect();
mHandler.sendEmptyMessage(0);
} catch (IOException eConnectException) {
Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
closeSocket(mBluetoothSocket);
return;
}
}
private void sendDataToDevice(String message) {
byte[] msgBuffer = message.getBytes();
Log.d(TAG, "...Send data: " + message + "...");
try {
outStream.write(msgBuffer);
} catch (IOException e) {
String msg = "In onResume() and an exception occurred during write: "
+ e.getMessage();
if (address.equals("00:00:00:00:00:00"))
msg = msg
+ ".\n\nUpdate your server address from 00:00:00:00:00:00 to the correct address on line 35 in the java code";
msg = msg
+ ".\n\nTry Connecting the device one more time from the options menu.\n\n";
errorExit("Fatal Error", msg);
}
}
private void closeSocket(BluetoothSocket nOpenSocket) {
try {
nOpenSocket.close();
Log.d(TAG, "SocketClosed");
} catch (IOException ex) {
Log.d(TAG, "CouldNotCloseSocket");
}
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
mBluetoothConnectProgressDialog.dismiss();
Toast.makeText(MainActivity.this, "DeviceConnected", 5000).show();
}
};
}
and DeviceListActivty.java is like this
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class DeviceListActivity extends Activity {
protected static final String TAG = "TAG";
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
#Override
protected void onCreate(Bundle mSavedInstanceState) {
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.device_list);
setResult(Activity.RESULT_CANCELED);
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this,
R.layout.device_name);
ListView mPairedListView = (ListView) findViewById(R.id.paired_devices);
mPairedListView.setAdapter(mPairedDevicesArrayAdapter);
mPairedListView.setOnItemClickListener(mDeviceClickListener);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter
.getBondedDevices();
if (mPairedDevices.size() > 0) {
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice mDevice : mPairedDevices) {
mPairedDevicesArrayAdapter.add(mDevice.getName() + "\n"
+ mDevice.getAddress());
}
} else {
String mNoDevices = "None Paired";// getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(mNoDevices);
}
}
#Override
protected void onDestroy() {
super.onDestroy();
if (mBluetoothAdapter != null) {
mBluetoothAdapter.cancelDiscovery();
}
}
private OnItemClickListener mDeviceClickListener = new OnItemClickListener() {
public void onItemClick(AdapterView<?> mAdapterView, View mView,
int mPosition, long mLong) {
mBluetoothAdapter.cancelDiscovery();
String mDeviceInfo = ((TextView) mView).getText().toString();
String mDeviceAddress = mDeviceInfo
.substring(mDeviceInfo.length() - 17);
Log.v(TAG, "Device_Address " + mDeviceAddress);
Bundle mBundle = new Bundle();
mBundle.putString("DeviceAddress", mDeviceAddress);
Intent mBackIntent = new Intent();
mBackIntent.putExtras(mBundle);
setResult(Activity.RESULT_OK, mBackIntent);
finish();
}
};
}

Related

wifi p2p file transfer android connected device but not transfering

Hello iam stuck in problem since yesterday searched everything anywhere i create application which show device which arre connected to same router wifi , then iam able to connect both device using this exmple
https://developer.android.com/guide/topics/connectivity/wifip2p.html#creating-app
everything is okay both devices are connected but when transfer file serviceintent is not starting so thats why i cant transfer anything , there is not log error but happend nothing when i choose image to send
MainActivity Class
package com.b.wifip2p;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.net.wifi.WpsInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pGroup;
import android.net.wifi.p2p.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.os.AsyncTask;
import android.os.Environment;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.format.Formatter;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.ServerSocket;
import java.net.Socket;
import java.sql.SQLOutput;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
public class MainActivity extends AppCompatActivity implements WifiP2pManager.PeerListListener, WifiP2pManager.ConnectionInfoListener {
Button button;
private boolean isWifiP2pEnabled = false;
private boolean retryChannel = false;
private final IntentFilter intentFilter = new IntentFilter();
private WifiP2pManager.Channel channel;
WifiP2pManager.Channel mChannel = null;
WifiP2pManager mManager;
private WifiP2pInfo info;
BroadCast broadCast;
private BroadcastReceiver receiver = null;
static List peers = new ArrayList();
ListView lv;
static Adapater myadapter;
ArrayList<DeviceInfo_Bean>list=new ArrayList<>();
private WifiP2pDevice device;
String hostaddd;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv=findViewById(R.id.lv);
myadapter=new Adapater(this,list);
button=findViewById(R.id.button);
lv.setAdapter(myadapter);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
intentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
connect();
}
});
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
System.out.println("---sucess discover");
}
#Override
public void onFailure(int reasonCode) {
System.out.println("---fail");
}
});
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("image/*");
startActivityForResult(intent, 007);
WifiManager wifiManager = (WifiManager) getApplicationContext().getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
int ipAddress = wifiInfo.getIpAddress();
System.out.println("---ip"+ipAddress);
}
});
}
#Override
public void onResume() {
super.onResume();
broadCast = new BroadCast(mManager, mChannel, MainActivity.this);
registerReceiver(broadCast, intentFilter);
}
#Override
public void onPause() {
super.onPause();
unregisterReceiver(broadCast);
}
private static WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
#Override
public void
onPeersAvailable(WifiP2pDeviceList peerList) {
List<WifiP2pDevice> refreshedPeers = (List<WifiP2pDevice>) peerList.getDeviceList();
if (!refreshedPeers.equals(peers)) {
peers.clear();
peers.addAll(refreshedPeers);
System.out.println("---ref"+refreshedPeers);
}
if (peers.size() == 0) {
Log.d("-----deviceno", "No devices found");
return;
}
}
};
#Override
public void onPeersAvailable(WifiP2pDeviceList peers) {
for (WifiP2pDevice device : peers.getDeviceList())
{
list.clear();
String address=device.deviceAddress;
String name=device.deviceName;
System.out.println("---name"+name+address);
list.add(new DeviceInfo_Bean(name,address));
}
myadapter.notifyDataSetChanged();
Log.i("----", "Found some peers!!! " + peers.getDeviceList());
}
public void connect() {
DeviceInfo_Bean device = list.get(0);
WifiP2pConfig config = new WifiP2pConfig();
config.deviceAddress = device.address;
config.wps.setup = WpsInfo.PBC;
System.out.println("device in"+device.address);
mManager.connect(mChannel, config, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Connected.",
Toast.LENGTH_SHORT).show();
}
#Override
public void onFailure(int reason) {
Toast.makeText(MainActivity.this, "Connect failed. Retry.",
Toast.LENGTH_SHORT).show();
}
});
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
// User has picked an image. Transfer it to group owner i.e peer using
// FileTransferService.
Uri uri = data.getData();
// TextView statusText = (TextView) mContentView.findViewById(R.id.status_text);
// statusText.setText("Sending: " + uri);
// Log.d(WiFiDirectActivity.TAG, "Intent----------- " + uri);
Intent serviceIntent = new Intent(MainActivity.this, FileTransferService.class);
serviceIntent.setAction(FileTransferService.ACTION_SEND_FILE);
serviceIntent.putExtra(FileTransferService.EXTRAS_FILE_PATH, uri.toString());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_ADDRESS,
info.groupOwnerAddress.getHostAddress());
serviceIntent.putExtra(FileTransferService.EXTRAS_GROUP_OWNER_PORT, 8988);
startService(serviceIntent);
}
#Override
public void onPointerCaptureChanged(boolean hasCapture) {
}
public static class FileServerAsyncTask extends AsyncTask<Void, Void, String> {
private Context context;
//private TextView statusText;
/**
* #param context
*
*/
public FileServerAsyncTask(Context context) {
this.context = context;
//this.statusText = (TextView) statusText;
}
#Override
protected String doInBackground(Void... params) {
try {
ServerSocket serverSocket = new ServerSocket(8988);
System.out.println("---socket");
Socket client = serverSocket.accept();
///Log.d(WiFiDirectActivity.TAG, "Server: connection done");
final File f = new File(Environment.getExternalStorageDirectory() + "/"
+ context.getPackageName() + "/wifip2pshared-" + System.currentTimeMillis()
+ ".jpg");
File dirs = new File(f.getParent());
if (!dirs.exists())
dirs.mkdirs();
f.createNewFile();
//Log.d(WiFiDirectActivity.TAG, "server: copying files " + f.toString());
OutputStream stream = client.getOutputStream();
String s="---mymsg";
stream.write(s.getBytes());
Log.e("hello","context value "+context);
InputStream inputstream = client.getInputStream();
copyFile(inputstream, new FileOutputStream(f));
serverSocket.close();
return f.getAbsolutePath();
} catch (IOException e) {
// Log.e(WiFiDirectActivity.TAG, e.getMessage());
return null;
}
}
/*
* (non-Javadoc)
* #see android.os.AsyncTask#onPostExecute(java.lang.Object)
*/
#Override
protected void onPostExecute(String result) {
if (result != null) {
// statusText.setText("File copied - " + result);
Intent intent = new Intent();
intent.setAction(android.content.Intent.ACTION_VIEW);
intent.setDataAndType(Uri.parse("file://" + result), "image/*");
context.startActivity(intent);
}
}
/*
* (non-Javadoc)
* #see android.os.AsyncTask#onPreExecute()
*/
#Override
protected void onPreExecute() {
// statusText.setText("Opening a server socket");
}
}
public static boolean copyFile(InputStream inputStream, OutputStream out) {
byte buf[] = new byte[1024];
int len;
long startTime=System.currentTimeMillis();
try {
while ((len = inputStream.read(buf)) != -1) {
out.write(buf, 0, len);
}
out.close();
inputStream.close();
long endTime=System.currentTimeMillis()-startTime;
Log.v("","Time taken to transfer all bytes is : "+endTime);
} catch (IOException e) {
// Log.d(WiFiDirectActivity.TAG, e.toString());
return false;
}
return true;
}
public void onConnectionInfoAvailable(final WifiP2pInfo info) {
System.out.println("---info");
this.info=info;
// view.setText("Group Owner IP - " + info.groupOwnerAddress.getHostAddress());
InetAddress groupOwnerAddress = info.groupOwnerAddress;
System.out.println("--g"+groupOwnerAddress);
System.out.println("--info"+info.groupOwnerAddress.getHostAddress());
if (info.groupFormed && info.isGroupOwner) {
new FileServerAsyncTask(getApplication())
.execute();
} else if (info.groupFormed) {
// The other device acts as the client. In this case, we enable the
// get file button.
}
// hide the connect button
// mContentView.findViewById(R.id.btn_connect).setVisibility(View.GONE);
}
public void showDetails(WifiP2pDevice device) {
this.device = device;
// this.getView().setVisibility(View.VISIBLE);
// TextView view = (TextView) mContentView.findViewById(R.id.device_address);
// view.setText(device.deviceAddress);
//view = (TextView) mContentView.findViewById(R.id.device_info);
//view.setText(device.toString());
System.out.println("---device"+device.deviceAddress);
}
}'
Broadcast
package com.b.wifip2p;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.net.NetworkInfo;
import android.net.wifi.p2p.WifiP2pConfig;
import android.net.wifi.p2p.WifiP2pDevice;
import android.net.wifi.p2p.WifiP2pDeviceList;
import android.net.wifi.p2p.WifiP2pManager;
import android.util.Log;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import java.nio.channels.Channel;
/**
* Created by BHM on 3/3/2018.
*/
public class BroadCast extends BroadcastReceiver {
private WifiP2pManager mManager;
private WifiP2pManager.Channel mChannel;
private MainActivity activity;
PeerListListener peerListListener=null;
public BroadCast(WifiP2pManager manager, WifiP2pManager.Channel channel,
MainActivity activity) {
super();
this.mManager = manager;
this.mChannel = channel;
this.activity = (MainActivity) activity;
}
#Override
public void onReceive(Context context, Intent intent) {
System.out.println("-----broadcast");
String action = intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)) {
// UI update to indicate wifi p2p status.
int state = intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE, -1);
if (state == WifiP2pManager.WIFI_P2P_STATE_ENABLED) {
// Wifi Direct mode is enabled
// activity.setIsWifiP2pEnabled(true);
} else {
//activity.setIsWifiP2pEnabled(false);
// activity.resetData();
}
// Log.d(WiFiDirectActivity.TAG, "P2P state changed - " + state);
} else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)) {
// request available peers from the wifi p2p manager. This is an
// asynchronous call and the calling activity is notified with a
// callback on PeerListListener.onPeersAvailable()
if (mManager != null) {
// mManager.requestPeers(mChannel, (PeerListListener) mChannel);
}
// Log.d(WiFiDirectActivity.TAG, "P2P peers changed");
} else if (WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION.equals(action)) {
if (mManager == null) {
return;
}
NetworkInfo networkInfo = (NetworkInfo) intent
.getParcelableExtra(WifiP2pManager.EXTRA_NETWORK_INFO);
if (networkInfo.isConnected()) {
// we are connected with the other device, request connection
// info to find group owner IP
mManager.requestConnectionInfo(mChannel, activity);
} else {
// It's a disconnect
// activity.resetData();
}
} else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)) {
// DeviceListFragment fragment = (DeviceListFragment) activity.getFragmentManager()
// .findFragmentById(R.id.frag_list);
// fragment.updateThisDevice((WifiP2pDevice) intent.getParcelableExtra(
// WifiP2pManager.EXTRA_WIFI_P2P_DEVICE));
intent.getParcelableExtra(
WifiP2pManager.EXTRA_WIFI_P2P_DEVICE);
}
}
}
FileTransferService here intent is not coming
package com.b.wifip2p;
import android.app.IntentService;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.util.Log;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
/**
* Created by BHM on 3/4/2018.
*/
class FileTransferService extends IntentService {
private static final int SOCKET_TIMEOUT = 5000;
public static final String ACTION_SEND_FILE = "com.example.android.wifidirect.SEND_FILE";
public static final String EXTRAS_FILE_PATH = "file_url";
public static final String EXTRAS_GROUP_OWNER_ADDRESS = "go_host";
public static final String EXTRAS_GROUP_OWNER_PORT = "go_port";
public FileTransferService(String name) {
super(name);
}
#Override
protected void onHandleIntent(Intent intent) {
System.out.println("--intent");
Context context = getApplicationContext();
if (intent.getAction().equals(ACTION_SEND_FILE)) {
String fileUri = intent.getExtras().getString(EXTRAS_FILE_PATH);
String host = intent.getExtras().getString(EXTRAS_GROUP_OWNER_ADDRESS);
Socket socket = new Socket();
int port = intent.getExtras().getInt(EXTRAS_GROUP_OWNER_PORT);
try {
// Log.d(WiFiDirectActivity.TAG, "Opening client socket - ");
socket.bind(null);
socket.connect((new InetSocketAddress(host, port)), SOCKET_TIMEOUT);
// Log.d(WiFiDirectActivity.TAG, "Client socket - " + socket.isConnected());
OutputStream stream = socket.getOutputStream();
ContentResolver cr = context.getContentResolver();
InputStream is = null;
try {
is = cr.openInputStream(Uri.parse(fileUri));
} catch (FileNotFoundException e) {
// Log.d(WiFiDirectActivity.TAG, e.toString());
}
MainActivity.copyFile(is, stream);
// Log.d(WiFiDirectActivity.TAG, "Client: Data written");
} catch (IOException e) {
// Log.e(WiFiDirectActivity.TAG, e.getMessage());
} finally {
if (socket != null) {
if (socket.isConnected()) {
try {
socket.close();
} catch (IOException e) {
// Give up
e.printStackTrace();
}
}
}
}
}
}
}
I know this is a slightly old question by now, but for those looking for answers:
I would recommend checking that you have the intent filters properly in your AndroidManifest.xml file.
It should look something like:
<activity android:name="ShareActivity">
<intent-filter>
<action android:name="android.intent.action.ACTION_SEND_FILE"/>
<category android:name="android.intent.category.DEFAULT"/>
<data android:mimeType="text/plain"/>
</intent-filter>
</activity>

Send Video file from Android to Arduino

From the below code I can convert a image file to byte array in my mobile app.But I cannot Convert a video file since OutOfMemoryError exception comes. I want to send a video file to a arduino board. Since I can send a string from android app to arduino, I am trying to send a video file like that. But it fails. I there any other solution to solve my problem?please help.
Code for converting image to byte array
package com.example.krishan.detectusbplugin;
import android.app.Activity;
import android.os.Bundle;
import android.os.Environment;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Arrays;
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
File file = new File(Environment.getExternalStorageDirectory() + "/Output/" +"My.mp4");
// convertFileToByteArray(file);
System.out.println(Arrays.toString(convertFileToByteArray(file)));
try {
System.out.write(convertFileToByteArray(file));
} catch (IOException e) {
e.printStackTrace();
}
}
public static byte[] convertFileToByteArray(File f) {
byte[] byteArray = null;
try {
InputStream inputStream = new FileInputStream(f);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
byte[] b = new byte[1024 * 8];
int bytesRead = 0;
while ((bytesRead = inputStream.read(b)) != -1) {
bos.write(b, 0, bytesRead);
}
byteArray = bos.toByteArray();
} catch (IOException e) {
e.printStackTrace();
}
return byteArray;
}
}
Code for sending a string to arduino through usb cable
package com.hariharan.arduinousb;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
import com.felhr.usbserial.UsbSerialDevice;
import com.felhr.usbserial.UsbSerialInterface;
import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;
public class MainActivity extends Activity {
public final String ACTION_USB_PERMISSION = "com.hariharan.arduinousb.USB_PERMISSION";
Button startButton, sendButton, clearButton, stopButton;
TextView textView;
EditText editText;
UsbManager usbManager;
UsbDevice device;
UsbSerialDevice serialPort;
UsbDeviceConnection connection;
UsbSerialInterface.UsbReadCallback mCallback = new UsbSerialInterface.UsbReadCallback() { //Defining a Callback which triggers whenever data is read.
#Override
public void onReceivedData(byte[] arg0) {
String data = null;
try {
data = new String(arg0, "UTF-8");
data.concat("/n");
tvAppend(textView, data);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
};
private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver() { //Broadcast Receiver to automatically start and stop the Serial connection.
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(ACTION_USB_PERMISSION)) {
boolean granted = intent.getExtras().getBoolean(UsbManager.EXTRA_PERMISSION_GRANTED);
if (granted) {
connection = usbManager.openDevice(device);
serialPort = UsbSerialDevice.createUsbSerialDevice(device, connection);
if (serialPort != null) {
if (serialPort.open()) { //Set Serial Connection Parameters.
setUiEnabled(true);
serialPort.setBaudRate(9600);
serialPort.setDataBits(UsbSerialInterface.DATA_BITS_8);
serialPort.setStopBits(UsbSerialInterface.STOP_BITS_1);
serialPort.setParity(UsbSerialInterface.PARITY_NONE);
serialPort.setFlowControl(UsbSerialInterface.FLOW_CONTROL_OFF);
serialPort.read(mCallback);
tvAppend(textView, "Serial Connection Opened!\n");
} else {
Log.d("SERIAL", "PORT NOT OPEN");
Toast.makeText(getApplicationContext(), "SERIAL , PORT NOT OPEN", Toast.LENGTH_LONG).show();
}
} else {
Log.d("SERIAL", "PORT IS NULLPORT IS NULL");
Toast.makeText(getApplicationContext(), "SERIAL , PORT IS NULL", Toast.LENGTH_LONG).show();
}
} else {
Log.d("SERIAL", "PERM NOT GRANTED");
Toast.makeText(getApplicationContext(), "SERIAL , PERM NOT GRANTED", Toast.LENGTH_LONG).show();
}
} else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_ATTACHED)) {
onClickStart(startButton);
} else if (intent.getAction().equals(UsbManager.ACTION_USB_DEVICE_DETACHED)) {
onClickStop(stopButton);
}
}
;
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
usbManager = (UsbManager) getSystemService(this.USB_SERVICE);
startButton = (Button) findViewById(R.id.buttonStart);
sendButton = (Button) findViewById(R.id.buttonSend);
clearButton = (Button) findViewById(R.id.buttonClear);
stopButton = (Button) findViewById(R.id.buttonStop);
editText = (EditText) findViewById(R.id.editText);
textView = (TextView) findViewById(R.id.textView);
setUiEnabled(false);
IntentFilter filter = new IntentFilter();
filter.addAction(ACTION_USB_PERMISSION);
filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
registerReceiver(broadcastReceiver, filter);
}
public void setUiEnabled(boolean bool) {
startButton.setEnabled(!bool);
sendButton.setEnabled(bool);
stopButton.setEnabled(bool);
textView.setEnabled(bool);
}
public void onClickStart(View view) {
HashMap<String, UsbDevice> usbDevices = usbManager.getDeviceList();
if (!usbDevices.isEmpty()) {
boolean keep = true;
for (Map.Entry<String, UsbDevice> entry : usbDevices.entrySet()) {
device = entry.getValue();
int devicePID = device.getProductId();
if (devicePID == 0x0043)//Arduino Product ID in Hexa
{
PendingIntent pi = PendingIntent.getBroadcast(this, 0, new Intent(ACTION_USB_PERMISSION), 0);
usbManager.requestPermission(device, pi);
keep = false;
} else {
Toast.makeText(getApplicationContext(), "PID does not match", Toast.LENGTH_LONG).show();
connection = null;
device = null;
}
if (!keep)
break;
}
}
}
public void onClickSend(View view) {
String string = editText.getText().toString();
serialPort.write(string.getBytes());
tvAppend(textView, "\nData Sent : " + string + "\n");
}
public void onClickStop(View view) {
setUiEnabled(false);
serialPort.close();
tvAppend(textView, "\nSerial Connection Closed! \n");
}
public void onClickClear(View view) {
textView.setText(" ");
}
private void tvAppend(TextView tv, CharSequence text) {
final TextView ftv = tv;
final CharSequence ftext = text;
runOnUiThread(new Runnable() {
#Override
public void run() {
ftv.append(ftext);
}
});
}
}

How to set page attributes for printing a document in android application

I am creating an android application that consists of printing document from android application. Here I connected android device and printer via usb. I want to set the page attributes such as new line after the end of the line and page heading and page borders.Please tell me how to do this.Big thanks in advance
This is what i had done for printing from android to printer via USB :
package com.developer.printer;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.util.HashMap;
import java.util.Iterator;
import android.app.Activity;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbDeviceConnection;
import android.hardware.usb.UsbEndpoint;
import android.hardware.usb.UsbInterface;
import android.hardware.usb.UsbManager;
import android.hardware.usb.UsbRequest;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;
public class Printer extends Activity {
Button create_file;
PendingIntent mPermissionIntent;
UsbManager usbManager;
UsbDevice device;
EditText print_text;
UsbDevice printer = null;
private static final int PRINTER_VENDOR_ID = 1256;
private String filename = "MySampleFile.txt";
private String filepath = "PanelFilesstorage";
File myInternalFile;
String data= "This is a sample text";
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
try
{
setContentView(R.layout.activity_demo_printer);
ContextWrapper contextWrapper = new ContextWrapper(getApplicationContext());
File directory = contextWrapper.getDir(filepath, Context.MODE_PRIVATE);
myInternalFile = new File(directory , filename);
print_text = (EditText)findViewById(R.id.editText_printer);
usbManager = (UsbManager) getSystemService(Context.USB_SERVICE);
HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
if (deviceList.size() <= 0)
{
Toast.makeText(getApplicationContext(), "Info: No device found", Toast.LENGTH_SHORT).show();
}
else
{
Toast.makeText(getApplicationContext(), "No of devices"+deviceList.size(), Toast.LENGTH_SHORT).show();
((TextView) findViewById(R.id.textView_devices))
.setText("No of device : " + deviceList.size());
}
Iterator<UsbDevice> deviceIterator = deviceList.values().iterator();
int count = 0;
mPermissionIntent = PendingIntent.getBroadcast(getBaseContext(), 0,
new Intent(ACTION_USB_PERMISSION), 0);
while (deviceIterator.hasNext()) {
count++;
device = deviceIterator.next();
Log.i("info", "Device No " + count + "........");
Log.i("info", "Vendor id : " + device.getVendorId());
Log.i("info", "Product id : " + device.getProductId());
Log.i("info", "Device name : " + device.getDeviceName());
Log.i("info", "Device class : " + device.getClass().getName());
Log.i("info", "Device protocol: " + device.getDeviceProtocol());
Log.i("info", "Device subclass : " + device.getDeviceSubclass());
if (device.getVendorId() == PRINTER_VENDOR_ID) {
printer = device;
break;
}
}
findViewById(R.id.button_print).setOnClickListener(
new OnClickListener() {
#Override
public void onClick(View v) {
Log.i("Info", "Print command given");
IntentFilter filter = new IntentFilter(
ACTION_USB_PERMISSION);
registerReceiver(mUsbReceiver, filter);
if (printer != null) {
usbManager.requestPermission(printer,
mPermissionIntent);
} else {
Log.e("Exception", "Printer not found");
}
}
});
} catch (Exception e) {
Log.e("Exception", "Exception in onCreate " + e.getMessage());
e.printStackTrace();
}
findViewById(R.id.button_create_file).setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View v)
{
try
{
FileOutputStream fos = new FileOutputStream(myInternalFile+"\n");
fos.write(data.toString().getBytes());
fos.close();
}
catch (IOException e)
{
e.printStackTrace();
}
}
});
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver()
{
#Override
public void onReceive(Context context, Intent intent)
{
try {
String action = intent.getAction();
if (ACTION_USB_PERMISSION.equals(action))
{
synchronized (this)
{
final UsbDevice printerDevice = (UsbDevice) intent
.getParcelableExtra(UsbManager.EXTRA_DEVICE);
if (intent.getBooleanExtra(
UsbManager.EXTRA_PERMISSION_GRANTED, false))
{
if (printerDevice != null) {
Log.i("Info", "Device permission granted");
startPrinting(printerDevice);
}
}
else
{
Log.d("Debug", "permission denied for device "
+ printerDevice);
}
}
}
} catch (Exception e)
{
Log.e("Exception", "Exception in onRecieve " + e.getMessage());
e.printStackTrace();
}
}
};
public void startPrinting(final UsbDevice printerDevice)
{
new Handler().post(new Runnable()
{
UsbDeviceConnection conn;
UsbInterface usbInterface;
#Override
public void run()
{
try
{
Log.i("Info", "Bulk transfer started");
usbInterface = printerDevice.getInterface(0);
UsbEndpoint endPoint = usbInterface.getEndpoint(0);
conn = usbManager.openDevice(printer);
conn.claimInterface(usbInterface, true);
String myStringData = print_text.getText().toString();
byte[] array = myStringData.getBytes();
ByteBuffer output_buffer = ByteBuffer
.allocate(array.length);
UsbRequest request = new UsbRequest();
request.initialize(conn, endPoint);
request.queue(output_buffer, array.length);
if (conn.requestWait() == request)
{
Log.i("Info", output_buffer.getChar(0) + "");
Message m = new Message();
m.obj = output_buffer.array();
// handler.sendMessage(m);
output_buffer.clear();
}
else
{
Log.i("Info", "No request recieved");
}
int transfered = conn.bulkTransfer(endPoint,
myStringData.getBytes(),
myStringData.getBytes().length, 5000);
Log.i("Info", "Amount of data transferred : " +transfered);
} catch (Exception e)
{
Log.e("Exception", "Unable to transfer bulk data");
e.printStackTrace();
} finally
{
try
{
conn.releaseInterface(usbInterface);
Log.i("Info", "Interface released");
conn.close();
Log.i("Info", "Usb connection closed");
unregisterReceiver(mUsbReceiver);
Log.i("Info", "Brodcast reciever unregistered");
}
catch (Exception e)
{
Log.e("Exception",
"Unable to release resources because : "
+ e.getMessage());
e.printStackTrace();
}
}
}
});
}
}

How to connect a mobile and a printer via bluetooth in android?

Can anyone tell me how to connect a mobile and a printer via bluetooth to print a text file in android?
That is,if i click the print button from the android application,the printer has to print that corresponding file.As per my knowledge i have searched for it in Google, but i couldn't find any good samples to do it.Has anyone have at-least one sample android program to do this, it will be better to clear my chaos.
Suggestions please.
Thanks for your precious time!..
Bluetooth Printer Android Example
Create a new android project BlueToothPrinterApp in your editor.
Step 1:
Create main activity like below
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();
}
}
}
Step 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(“8 ce255c0 - 200 a - 11e0 - ac64 - 0800200 c9a66″);
// 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;
}
}
Step 3:
Edit your main.xml file and paste below code.
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>
Step 4:
Now edit your AndroidManifest.xml
Add bluetooth permission and admin permission.
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″>
<uses-sdk android:minSdkVersion=”14″ />
<uses-permission android:name=”android.permission.BLUETOOTH”></uses-permission>
<uses-permission android:name=”android.permission.BLUETOOTH_ADMIN”></uses-permission>
<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>
</manifest>
Compile and run this application. Enter message and press print button.
You will see list of bluetooth devices. Select bluettoth printer.
Check print on your bluetooth printer.
here is the CODE Reference...
You can use this awesome lib, you can connect to any printer and print easily,
https://github.com/mazenrashed/Printooth
you can download it by:
implementation 'com.github.mazenrashed:Printooth:${LAST_VERSION}'
and use it like:
var printables = ArrayList<Printable>()
var printable = Printable.PrintableBuilder()
.setText("Hello World")
printables.add(printable)
BluetoothPrinter.printer().print(printables)

Bluetooth Printer issue in android

I am trying to print the bill through bluetooth using the following code,
when I run the app, first time its getting printed, but when I retry its not getting printed.
package com.sel.bluetooth;
import java.io.OutputStream;
import java.lang.reflect.Method;
import android.app.Activity;
import android.app.Dialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class BluetoothPrint extends Activity {
BluetoothAdapter mBTAdapter;
BluetoothSocket mBTSocket = null;
Dialog dialogProgress;
String BILL, TRANS_ID;
String PRINTER_MAC_ID;
final String ERROR_MESSAGE = "There has been an error in printing the bill.";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
// BILL = getIntent().getStringExtra("TO_PRINT");
// TRANS_ID = getIntent().getStringExtra("TRANS_ID");
// PRINTER_MAC_ID = getIntent().getStringExtra("MAC_ID");
PRINTER_MAC_ID = "00:1F:B7:02:8F:44";
//PRINTER_MAC_ID = "00:12:F3:0D:A3:E6";
// TRANS_ID="12345678";
BILL = "\nSale Slip No: 12345678" + " " + "04-08-2011\n";
BILL = BILL + "----------------------------------------";
BILL = BILL + "\n\n";
BILL = BILL + "Total Qty:" + " " + "2.0\n";
BILL = BILL + "Total Value:" + " " + "17625.0\n";
BILL = BILL + "-----------------------------------------";
mBTAdapter = BluetoothAdapter.getDefaultAdapter();
dialogProgress = new Dialog(BluetoothPrint.this);
try {
if (mBTAdapter.isDiscovering())
mBTAdapter.cancelDiscovery();
else
mBTAdapter.startDiscovery();
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
}
System.out.println("BT Searching status :"
+ mBTAdapter.isDiscovering());
if (mBTAdapter == null) {
Toast.makeText(this, "Device has no bluetooth capability",
Toast.LENGTH_LONG).show();
finish();
} else {
if (!mBTAdapter.isEnabled()) {
Intent i = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(i, 0);
}
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(
BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to
// unregister during
// onDestroy
dialogProgress.setTitle("Finding printer...");
dialogProgress
.setOnDismissListener(new DialogInterface.OnDismissListener() {
public void onDismiss(DialogInterface dialog) {
dialog.dismiss();
setResult(RESULT_CANCELED);
finish();
}
});
dialogProgress.show();
}
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
}
}
public void printBillToDevice(final String address) {
new Thread(new Runnable() {
public void run() {
runOnUiThread(new Runnable() {
public void run() {
dialogProgress.setTitle("Connecting...");
dialogProgress.show();
}
});
mBTAdapter.cancelDiscovery();
try {
System.out
.println("**************************#****connecting");
BluetoothDevice mdevice = mBTAdapter
.getRemoteDevice(address);
Method m = mdevice.getClass().getMethod(
"createRfcommSocket", new Class[] { int.class });
mBTSocket = (BluetoothSocket) m.invoke(mdevice, 1);
mBTSocket.connect();
OutputStream os = mBTSocket.getOutputStream();
os.flush();
os.write(BILL.getBytes());
System.out.println(BILL);
//mBTSocket.close();
setResult(RESULT_OK);
finish();
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
//Toast.makeText(BluetoothPrint.this, ERROR_MESSAGE, Toast.LENGTH_SHORT).show();
e.printStackTrace();
setResult(RESULT_CANCELED);
finish();
}
runOnUiThread(new Runnable() {
public void run() {
try {
dialogProgress.dismiss();
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
}
}
});
}
}).start();
}
#Override
protected void onDestroy() {
Log.i("Dest ", "Checking Ddest");
super.onDestroy();
try {
if(dialogProgress != null)
dialogProgress.dismiss();
if (mBTAdapter != null)
mBTAdapter.cancelDiscovery();
this.unregisterReceiver(mReceiver);
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
}
}
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
try {
String action = intent.getAction();
// When discovery finds a device
if (BluetoothDevice.ACTION_FOUND.equals(action)) {
// Get the BluetoothDevice object from the Intent
BluetoothDevice device = intent
.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
System.out.println("***" + device.getName() + " : "
+ device.getAddress());
if (device.getAddress().equalsIgnoreCase(PRINTER_MAC_ID)) {
mBTAdapter.cancelDiscovery();
dialogProgress.dismiss();
Toast.makeText(BluetoothPrint.this,
device.getName() + " Printing data",
Toast.LENGTH_LONG).show();
printBillToDevice(PRINTER_MAC_ID);
Toast.makeText(BluetoothPrint.this,
device.getName() + " found", Toast.LENGTH_LONG)
.show();
}
}
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
//Toast.makeText(BluetoothPrint.this, ERROR_MESSAGE, Toast.LENGTH_SHORT).show();
}
}
};
#Override
public void onBackPressed() {
try {
if (mBTAdapter != null)
mBTAdapter.cancelDiscovery();
this.unregisterReceiver(mReceiver);
} catch (Exception e) {
Log.e("Class ", "My Exe ", e);
}
setResult(RESULT_CANCELED);
finish();
}
}
Here is the perfectely working code for blue-tooth printer in android
device_list.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:id="#+id/title_paired_devices"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:text="My Text" android:visibility="gone"
android:background="#666" android:textColor="#fff"
android:paddingLeft="5dip" />
<ListView android:id="#+id/paired_devices"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:stackFromBottom="true" android:layout_weight="1" />
</LinearLayout>
device_name.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:textSize="18sp" android:padding="5dip" />
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content" android:text="#string/hello" />
<Button android:text="Scan" android:id="#+id/Scan"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="Print" android:id="#+id/mPrint"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
<Button android:text="Dissable" android:id="#+id/dis"
android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
</LinearLayout>
DeviceListActivity.java
package com.sel.code;
import java.util.Set;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class DeviceListActivity extends Activity
{
protected static final String TAG = "TAG";
private BluetoothAdapter mBluetoothAdapter;
private ArrayAdapter<String> mPairedDevicesArrayAdapter;
#Override
protected void onCreate(Bundle mSavedInstanceState)
{
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.device_list);
setResult(Activity.RESULT_CANCELED);
mPairedDevicesArrayAdapter = new ArrayAdapter<String>(this, R.layout.device_name);
ListView mPairedListView = (ListView) findViewById(R.id.paired_devices);
mPairedListView.setAdapter(mPairedDevicesArrayAdapter);
mPairedListView.setOnItemClickListener(mDeviceClickListener);
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices();
if (mPairedDevices.size() > 0)
{
findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);
for (BluetoothDevice mDevice : mPairedDevices)
{
mPairedDevicesArrayAdapter.add(mDevice.getName() + "\n" + mDevice.getAddress());
}
}
else
{
String mNoDevices = "None Paired";//getResources().getText(R.string.none_paired).toString();
mPairedDevicesArrayAdapter.add(mNoDevices);
}
}
#Override
protected void onDestroy()
{
super.onDestroy();
if (mBluetoothAdapter != null)
{
mBluetoothAdapter.cancelDiscovery();
}
}
private OnItemClickListener mDeviceClickListener = new OnItemClickListener()
{
public void onItemClick(AdapterView<?> mAdapterView, View mView, int mPosition, long mLong)
{
mBluetoothAdapter.cancelDiscovery();
String mDeviceInfo = ((TextView) mView).getText().toString();
String mDeviceAddress = mDeviceInfo.substring(mDeviceInfo.length() - 17);
Log.v(TAG, "Device_Address " + mDeviceAddress);
Bundle mBundle = new Bundle();
mBundle.putString("DeviceAddress", mDeviceAddress);
Intent mBackIntent = new Intent();
mBackIntent.putExtras(mBundle);
setResult(Activity.RESULT_OK, mBackIntent);
finish();
}
};
}
Main.java
package com.sel.code;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.ByteBuffer;
import java.util.Set;
import java.util.UUID;
import android.app.Activity;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;
public class Main extends Activity implements Runnable {
protected static final String TAG = "TAG";
private static final int REQUEST_CONNECT_DEVICE = 1;
private static final int REQUEST_ENABLE_BT = 2;
Button mScan, mPrint, mDisc;
BluetoothAdapter mBluetoothAdapter;
private UUID applicationUUID = UUID
.fromString("00001101-0000-1000-8000-00805F9B34FB");
private ProgressDialog mBluetoothConnectProgressDialog;
private BluetoothSocket mBluetoothSocket;
BluetoothDevice mBluetoothDevice;
#Override
public void onCreate(Bundle mSavedInstanceState) {
super.onCreate(mSavedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.main);
mScan = (Button) findViewById(R.id.Scan);
mScan.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Toast.makeText(Main.this, "Message1", 2000).show();
} else {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(
BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent,
REQUEST_ENABLE_BT);
} else {
ListPairedDevices();
Intent connectIntent = new Intent(Main.this,
DeviceListActivity.class);
startActivityForResult(connectIntent,
REQUEST_CONNECT_DEVICE);
}
}
}
});
mPrint = (Button) findViewById(R.id.mPrint);
mPrint.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
Thread t = new Thread() {
public void run() {
try {
OutputStream os = mBluetoothSocket
.getOutputStream();
String BILL = "";
BILL = "\nInvoice No: ABCDEF28060000005" + " "
+ "04-08-2011\n";
BILL = BILL
+ "-----------------------------------------";
BILL = BILL + "\n\n";
BILL = BILL + "Total Qty:" + " " + "2.0\n";
BILL = BILL + "Total Value:" + " "
+ "17625.0\n";
BILL = BILL
+ "-----------------------------------------\n";
os.write(BILL.getBytes());
//This is printer specific code you can comment ==== > Start
// Setting height
int gs = 29;
os.write(intToByteArray(gs));
int h = 104;
os.write(intToByteArray(h));
int n = 162;
os.write(intToByteArray(n));
// Setting Width
int gs_width = 29;
os.write(intToByteArray(gs_width));
int w = 119;
os.write(intToByteArray(w));
int n_width = 2;
os.write(intToByteArray(n_width));
// Print BarCode
int gs1 = 29;
os.write(intToByteArray(gs1));
int k = 107;
os.write(intToByteArray(k));
int m = 73;
os.write(intToByteArray(m));
String barCodeVal = "ASDFC028060000005";// "HELLO12345678912345012";
System.out.println("Barcode Length : "
+ barCodeVal.length());
int n1 = barCodeVal.length();
os.write(intToByteArray(n1));
for (int i = 0; i < barCodeVal.length(); i++) {
os.write((barCodeVal.charAt(i) + "").getBytes());
}
//printer specific code you can comment ==== > End
} catch (Exception e) {
Log.e("Main", "Exe ", e);
}
}
};
t.start();
}
});
mDisc = (Button) findViewById(R.id.dis);
mDisc.setOnClickListener(new View.OnClickListener() {
public void onClick(View mView) {
if (mBluetoothAdapter != null)
mBluetoothAdapter.disable();
}
});
}// onCreate
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
try {
if (mBluetoothSocket != null)
mBluetoothSocket.close();
} catch (Exception e) {
Log.e("Tag", "Exe ", e);
}
}
#Override
public void onBackPressed() {
try {
if (mBluetoothSocket != null)
mBluetoothSocket.close();
} catch (Exception e) {
Log.e("Tag", "Exe ", e);
}
setResult(RESULT_CANCELED);
finish();
}
public void onActivityResult(int mRequestCode, int mResultCode,
Intent mDataIntent) {
super.onActivityResult(mRequestCode, mResultCode, mDataIntent);
switch (mRequestCode) {
case REQUEST_CONNECT_DEVICE:
if (mResultCode == Activity.RESULT_OK) {
Bundle mExtra = mDataIntent.getExtras();
String mDeviceAddress = mExtra.getString("DeviceAddress");
Log.v(TAG, "Coming incoming address " + mDeviceAddress);
mBluetoothDevice = mBluetoothAdapter
.getRemoteDevice(mDeviceAddress);
mBluetoothConnectProgressDialog = ProgressDialog.show(this,
"Connecting...", mBluetoothDevice.getName() + " : "
+ mBluetoothDevice.getAddress(), true, false);
Thread mBlutoothConnectThread = new Thread(this);
mBlutoothConnectThread.start();
// pairToDevice(mBluetoothDevice); This method is replaced by
// progress dialog with thread
}
break;
case REQUEST_ENABLE_BT:
if (mResultCode == Activity.RESULT_OK) {
ListPairedDevices();
Intent connectIntent = new Intent(Main.this,
DeviceListActivity.class);
startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE);
} else {
Toast.makeText(Main.this, "Message", 2000).show();
}
break;
}
}
private void ListPairedDevices() {
Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter
.getBondedDevices();
if (mPairedDevices.size() > 0) {
for (BluetoothDevice mDevice : mPairedDevices) {
Log.v(TAG, "PairedDevices: " + mDevice.getName() + " "
+ mDevice.getAddress());
}
}
}
public void run() {
try {
mBluetoothSocket = mBluetoothDevice
.createRfcommSocketToServiceRecord(applicationUUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket.connect();
mHandler.sendEmptyMessage(0);
} catch (IOException eConnectException) {
Log.d(TAG, "CouldNotConnectToSocket", eConnectException);
closeSocket(mBluetoothSocket);
return;
}
}
private void closeSocket(BluetoothSocket nOpenSocket) {
try {
nOpenSocket.close();
Log.d(TAG, "SocketClosed");
} catch (IOException ex) {
Log.d(TAG, "CouldNotCloseSocket");
}
}
private Handler mHandler = new Handler() {
#Override
public void handleMessage(Message msg) {
mBluetoothConnectProgressDialog.dismiss();
Toast.makeText(Main.this, "DeviceConnected", 5000).show();
}
};
public static byte intToByteArray(int value) {
byte[] b = ByteBuffer.allocate(4).putInt(value).array();
for (int k = 0; k < b.length; k++) {
System.out.println("Selva [" + k + "] = " + "0x"
+ UnicodeFormatter.byteToHex(b[k]));
}
return b[3];
}
public byte[] sel(int val) {
ByteBuffer buffer = ByteBuffer.allocate(2);
buffer.putInt(val);
buffer.flip();
return buffer.array();
}
}
UnicodeFormatter.java
package com.sel.code;
import java.io.*;
public class UnicodeFormatter {
static public String byteToHex(byte b) {
// Returns hex String representation of byte b
char hexDigit[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
'a', 'b', 'c', 'd', 'e', 'f' };
char[] array = { hexDigit[(b >> 4) & 0x0f], hexDigit[b & 0x0f] };
return new String(array);
}
static public String charToHex(char c) {
// Returns hex String representation of char c
byte hi = (byte) (c >>> 8);
byte lo = (byte) (c & 0xff);
return byteToHex(hi) + byteToHex(lo);
}
} // class
I've just uncommented //mBTSocket.close();
Then, just before, add:
if (mBTAdapter != null)
mBTAdapter.cancelDiscovery();
and everything goes well!
Also try closing the OutputStream after writing to it, preferably in the finish block using:
os.close();

Categories

Resources