I am building an application which does some work when a specific wifi network is connected. To check if my wifi network is connected i am running a background service which runs a thread of infinite loop inside it. The thread checks for wifi connection is active or not. If yes, then it displays the notification and keeps the notification until wifi is disconnected. I cannot find the better approach to check for my connection asynchronously. The problems I am facing is as follows:
If service is already running and I connect to network i get a notification. Now I open my application and notification still shows. Then I disconnect from wifi connection and the notification disappears, I connect again and notification appears again as well ,as it should. Now if I remove my app from the overview and then disconnect from the wifi, my notification does not go, it sticks in the notification panel. Although this error is uncertain and occur in some phones and not in some.
I am posting my service code and main activity code.
Please suggest me a better approach to do this task.
MyService.java
package com.sumatone.volsbbonetouch;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.wifi.SupplicantState;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
import java.util.logging.Handler;
import java.util.logging.LogRecord;
/**
* Created by shalini on 31-01-2015.
*/
public class MyService extends Service {
private boolean CHECK=true,tcheck=true;
private Thread t1;
#Override
public void onCreate() {
super.onCreate();
final ShowNotification s=new ShowNotification(this);
//Toast.makeText(this,"Service was created",Toast.LENGTH_SHORT).show();
t1=new Thread(new Runnable() {
#Override
public void run() {
while(true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
CHECK=checkConnection();
if (CHECK==true&&tcheck==true) {
Log.d("status", "connected");
s.notifyInstant();
tcheck=false;
}
else if (CHECK==false&&tcheck==false) {
Log.d("status", "disconnected");
s.remove();
tcheck=true;
}
}
}
});
/*t2=new Thread(new Runnable() {
#Override
public void run() {
while(true) {
checkConnection();
if (!CHECK) {
Log.d("status", "disconnected");
t1.notify();
try {
t2.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
});*/
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
//Toast.makeText(this,"Service was started",Toast.LENGTH_SHORT).show();
t1.start();
return super.onStartCommand(intent,flags,startId);
}
public boolean checkConnection() {
/*final ConnectivityManager connMgr = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(wifi.isConnected())
{
Log.d("wifi",wifi.getExtraInfo());
if(wifi.getExtraInfo().equalsIgnoreCase("\"VOLSBB\"")) {
Log.d("wifistate","connected");
return true;
}
return false;
}
else {
return false;
}*/
final WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
final ConnectivityManager connMgr = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
if(wifiManager.isWifiEnabled())
{
final WifiInfo wifiInfo = wifiManager.getConnectionInfo();
final SupplicantState supp= wifiInfo.getSupplicantState();
Log.d("wifi",wifiInfo.getSSID());
if((wifiInfo.getSSID().equalsIgnoreCase("\"VOLSBB\"")||wifiInfo.getSSID().equalsIgnoreCase("\"VOLS\""))&&wifi.isConnected()) {
Log.d("wifistate","connected");
return true;
}
return false;
}
else {
return false;
}
}
#Override
public void onDestroy() {
//Toast.makeText(this,"Service was destroyed",Toast.LENGTH_SHORT).show();
super.onDestroy();
}
#Override
public boolean onUnbind(Intent intent) {
return super.onUnbind(intent);
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
MainActivity.java
package com.sumatone.volsbbonetouch;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.ConnectivityManager;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.http.NameValuePair;
import org.apache.http.message.BasicNameValuePair;
import java.util.ArrayList;
import java.util.List;
/**
* Created by shalini on 29-01-2015.
*/
public class MainActivity extends Activity implements View.OnClickListener {
private String url="http://phc.prontonetworks.com/cgi-bin/authlogin?URI=http://www.msftncsi.com/redirect";
EditText uname,password;
TextView res;
Button login,logout,slogin;
List<NameValuePair> details;
ProgressDialog pDialog;
SharedPreferences s;
Authentication a;
String u,p,toasttext,session;
ImageView about;
String service="ProntoAuthentication";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if(!isMyServiceRunning(MyService.class))
startService(new Intent(this,MyService.class));
about=(ImageView)findViewById(R.id.about);
uname=(EditText)findViewById(R.id.user);
password=(EditText)findViewById(R.id.pass);
s= PreferenceManager.getDefaultSharedPreferences(this);
uname.setText(s.getString("prontousername",null));
password.setText(s.getString("prontopassword",null));
a= new Authentication(this);
login=(Button)findViewById(R.id.login);
logout=(Button)findViewById(R.id.logout);
slogin=(Button)findViewById(R.id.savelogin);
res=(TextView)findViewById(R.id.res);
login.setOnClickListener(this);
logout.setOnClickListener(this);
slogin.setOnClickListener(this);
about.setOnClickListener(this);
session=s.getString("session","first");
if(session.equals("first")){
about.performClick();
SharedPreferences.Editor editor=s.edit();
editor.putString("session","used");
editor.commit();
}
}
#Override
public void onClick(View v) {
if (v.getId() == R.id.login) {
if(checkConnection()) {
details = new ArrayList<NameValuePair>();
url = "http://phc.prontonetworks.com/cgi-bin/authlogin?URI=http://www.msftncsi.com/redirect";
u = uname.getText().toString();
p = password.getText().toString();
details.add(new BasicNameValuePair("userId", u));
details.add(new BasicNameValuePair("password", p));
details.add(new BasicNameValuePair("serviceName", service));
new GetEvents().execute();
}
else
Toast.makeText(this,"Not connected to Volsbb",Toast.LENGTH_SHORT).show();
}
if (v.getId() == R.id.logout) {
if(checkConnection()) {
details = null;
url = "http://phc.prontonetworks.com/cgi-bin/authlogout";
new GetEvents().execute();
}
else
Toast.makeText(this,"Not connected to Volsbb",Toast.LENGTH_SHORT).show();
}
if (v.getId() == R.id.savelogin) {
if (checkConnection()) {
details = new ArrayList<NameValuePair>();
url = "http://phc.prontonetworks.com/cgi-bin/authlogin?URI=http://www.msftncsi.com/redirect";
u = uname.getText().toString();
p = password.getText().toString();
SharedPreferences.Editor editor = s.edit();
editor.putString("prontousername", u);
editor.putString("prontopassword", p);
editor.commit();
details.add(new BasicNameValuePair("userId", u));
details.add(new BasicNameValuePair("password", p));
details.add(new BasicNameValuePair("serviceName", service));
new GetEvents().execute();
} else
Toast.makeText(this, "Not connected to Volsbb", Toast.LENGTH_SHORT).show();
}
if(v.getId()==R.id.about)
{
Intent i= new Intent(this,AboutDialog.class);
startActivity(i);
}
}
private boolean isMyServiceRunning(Class<?> serviceClass) {
ActivityManager manager = (ActivityManager) getSystemService(Context.ACTIVITY_SERVICE);
for (ActivityManager.RunningServiceInfo service : manager.getRunningServices(Integer.MAX_VALUE)) {
if (serviceClass.getName().equals(service.service.getClassName())) {
return true;
}
}
return false;
}
public boolean checkConnection() {
/*final ConnectivityManager connMgr = (ConnectivityManager) this
.getSystemService(Context.CONNECTIVITY_SERVICE);
final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if(wifi.isConnected())
{
Log.d("wifi",wifi.getExtraInfo());
if(wifi.getExtraInfo().equalsIgnoreCase("\"VOLSBB\"")) {
Log.d("wifistate","connected");
return true;
}
return false;
}
else {
return false;
}*/
final WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
if(wifiManager.isWifiEnabled())
{
final WifiInfo wifiInfo = wifiManager.getConnectionInfo();
Log.d("wifi",wifiInfo.getSSID());
if(wifiInfo.getSSID().equalsIgnoreCase("\"VOLSBB\"")) {
Log.d("wifistate","connected");
return true;
}
return false;
}
else {
return false;
}
}
private class GetEvents extends AsyncTask<Void, Void,String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
// Showing progress dialog
pDialog = new ProgressDialog(MainActivity.this);
pDialog.setMessage("Processing");
pDialog.setCancelable(false);
pDialog.show();
}
#Override
protected String doInBackground(Void... params) {
ServiceHandler sh = new ServiceHandler();
// Making a request to url and getting response
String valresponse = sh.makeServiceCall(url, ServiceHandler.POST,details);
Log.d("Response: ", ">" + valresponse);
return valresponse;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
// Dismiss the progress dialog
if (pDialog.isShowing())
pDialog.dismiss();
if(result.contains("Logout successful"))
toasttext="Logged out";
else if(result.contains("Successful Pronto Authentication"))
toasttext="Logged in";
else if(result.contains("There is no active session to logout"))
toasttext="There is no active session";
else if(result.contains("Sorry, please check your username and password"))
toasttext="Invalid username/password";
else if(result.contains("Sorry, your free access quota is over"))
toasttext="Your free access qouta is over";
else
toasttext="Already Logged in";
Toast.makeText(getApplicationContext(),toasttext,Toast.LENGTH_SHORT).show();
}
}
}
You must return START_STICKY in onStartCommand() to keep the service running. START_STICKY tells the OS to recreate the service if it is killed for some reason (i.e., memory, manually killing the app).
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
//Your service code
return START_STICKY;
}
Related
I am trying to make a link (bluetooth) between my arduino and android. i want to recieve the data from the arduino. The ListenInput thread does get started but nothing more
Here is my code
package com.codeyard.teleprompter;
import android.Manifest;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.SharedPreferences;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.preference.PreferenceManager;
import android.support.v4.app.ActivityCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;
public class bleutoothrevivedeletenow extends AppCompatActivity {
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
String address = null;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
Button StartConnection;
Button Disconnect;
Button Recieve;
TextView incomingData;
InputStream mmInStream = null;
String incomingMessage;
StringBuilder messages;
Thread ListenInput = new Thread() {
#Override
public void run() {
try {
mmInStream = btSocket.getInputStream();
byte[] buffer = new byte[1024];
int bytes;
Toast.makeText(getApplicationContext(), "Thread started///", Toast.LENGTH_LONG).show();
while (true) {
// Read from the InputStream
try {
if (mmInStream == null) {
Log.e("", "InputStream is null");
}
bytes = mmInStream.read(buffer);
incomingMessage = new String(buffer, 0, bytes);
messages.append(incomingMessage);
Toast.makeText(getApplicationContext(), "incoming message", Toast.LENGTH_LONG).show();
Toast.makeText(bleutoothrevivedeletenow.this, incomingMessage, Toast.LENGTH_LONG).show();
//TODO Remove this
} catch (Exception e) {
Toast.makeText(bleutoothrevivedeletenow.this, "128", Toast.LENGTH_SHORT).show();
}
}
} catch (Exception e) {
Toast.makeText(bleutoothrevivedeletenow.this, "133", Toast.LENGTH_SHORT).show();
}
}
};
private boolean isBtConnected = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bleutoothrevivedeletenow);
messages = new StringBuilder();
SharedPreferences sharedPreferences;
sharedPreferences = PreferenceManager.getDefaultSharedPreferences(bleutoothrevivedeletenow.this);
address = sharedPreferences.getString("ADDRESS", "");
StartConnection = findViewById(R.id.button5);
Disconnect = findViewById(R.id.button6);
incomingData = findViewById(R.id.textView);
Recieve = findViewById(R.id.button7);
StartConnection.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
new ConnectBT().execute();
}
});
Disconnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (btSocket != null) //If the btSocket is busy
{
try {
btSocket.close(); //close connection
} catch (IOException e) {
e.printStackTrace();
}
}
finish();
}
});
Recieve.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
ListenInput.start();
final Handler handler = new Handler();
Runnable runnable = new Runnable() {
#Override
public void run() {
incomingData.setText(messages);
handler.postDelayed(this, 2000);
}
};
runnable.run();
}
});
}
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute() {
Toast.makeText(getApplicationContext(), "Connecting....", Toast.LENGTH_LONG).show();
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try {
if (btSocket == null || !isBtConnected) {
ActivityCompat.requestPermissions(bleutoothrevivedeletenow.this, new String[]{Manifest.permission.BLUETOOTH}, 1);
ActivityCompat.requestPermissions(bleutoothrevivedeletenow.this, new String[]{Manifest.permission.BLUETOOTH_ADMIN}, 1);
ActivityCompat.requestPermissions(bleutoothrevivedeletenow.this, new String[]{Manifest.permission.BLUETOOTH_PRIVILEGED}, 1);
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);
//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
} catch (IOException e) {
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess) {
Toast.makeText(getApplicationContext(), "Connection Failed", Toast.LENGTH_SHORT).show();
finish();
} else {
Toast.makeText(getApplicationContext(), "Connection Successful", Toast.LENGTH_SHORT).show();
isBtConnected = true;
}
}
}
}
P.S. i have provided the entire code. this code is actually of this github repo:
https://github.com/IamMayankThakur/android-arduino-using-bluetooth
The code first genereated a IllegalThreadException but after debugging i edited the code and now it doesn't crash but still no incoming data
I'm with some doubt how I can execute one action.
When receive one income call, I want to pass the number for my class it manager the Bluetooth connection with Arduino.
After send the number, I'd like to send it by bluetooth connection
I tried use intent but maybe I am using deprecated version.
Android Api 7.1
Brodcaster Receiver Class
package com.jidea.glass;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
public class TelephonyReceiver extends BroadcastReceiver
{
#Override
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
try {
if (intent != null && intent.getAction().equals("android.intent.action.NEW_OUTGOING_CALL")) {
//Toast.makeText(context, "Outgoign call", 1000).show();
String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
} else {
//get the phone state
String newPhoneState = intent.hasExtra(TelephonyManager.EXTRA_STATE) ? intent.getStringExtra(TelephonyManager.EXTRA_STATE) : null;
Bundle bundle = intent.getExtras();
if (newPhoneState != null && newPhoneState.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
//read the incoming call number
String phoneNumber = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.i("PHONE RECEIVER", "Telephone is now ringing " + phoneNumber);
//Toast.makeText(arg0, "Tele disponivel " + phoneNumber, Toast.LENGTH_LONG).show();
if(phoneNumber!=null | phoneNumber.equals("")){
PASS HERE TO BLUETOOTH
}
}
Bluetooth class
package com.jidea.glass;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
//import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;
import androidx.appcompat.app.AppCompatActivity;
import java.io.IOException;
import java.util.UUID;
public class CustomProcess extends AppCompatActivity
{
String address = null;
private ProgressDialog progress;
BluetoothAdapter myBluetooth = null;
BluetoothSocket btSocket = null;
private boolean isBtConnected = false;
//SPP UUID. Look for it
static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
//observable
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent newint = getIntent();
address = newint.getStringExtra(MainActivity.EXTRA_ADDRESS); //receive the address of the bluetooth device
setContentView(R.layout.activity_custom_process);
//msg(address);
new ConnectBT().execute(); //Call the class to connect
}
public void isConnected() {//View view
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write("Conectado".toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
public void haveCall(String Phone) {//View view
Object aLig="Ligação \n"+Phone;
if (btSocket!=null)
{
try
{
btSocket.getOutputStream().write(aLig.toString().getBytes());
}
catch (IOException e)
{
msg("Error");
}
}
}
private void msg(String s)
{
Toast.makeText(getApplicationContext(),s,Toast.LENGTH_LONG).show();
}
private class ConnectBT extends AsyncTask<Void, Void, Void> // UI thread
{
private boolean ConnectSuccess = true; //if it's here, it's almost connected
#Override
protected void onPreExecute()
{
progress = ProgressDialog.show(CustomProcess.this, "Connecting...", "Please wait!!!"); //show a progress dialog
}
#Override
protected Void doInBackground(Void... devices) //while the progress dialog is shown, the connection is done in background
{
try
{
if (btSocket == null || !isBtConnected)
{
myBluetooth = BluetoothAdapter.getDefaultAdapter();//get the mobile bluetooth device
BluetoothDevice dispositivo = myBluetooth.getRemoteDevice(address);//connects to the device's address and checks if it's available
btSocket = dispositivo.createInsecureRfcommSocketToServiceRecord(myUUID);//create a RFCOMM (SPP) connection
BluetoothAdapter.getDefaultAdapter().cancelDiscovery();
btSocket.connect();//start connection
}
}
catch (IOException e)
{
ConnectSuccess = false;//if the try failed, you can check the exception here
}
return null;
}
#Override
protected void onPostExecute(Void result) //after the doInBackground, it checks if everything went fine
{
super.onPostExecute(result);
if (!ConnectSuccess)
{
msg("Connection Failed. Is it a SPP Bluetooth? Try again.");
finish();
}
else
{
msg("Conectado");
isBtConnected = true;
isConnected();
}
progress.dismiss();
}
}
}
First you should create an intent in your BroadcastReceiver and then use LocalBroadcastManager in order to be able to send that intent wherever you want to listen.
val intent = Intent(ACTION)
intent.putExtra("DATA KEY", DATA)
LocalBroadcastManager.getInstance(context).sendBroadcast(intent)
don't forget to register your broadcast receiver in where you want to listen
LocalBroadcastManager.getInstance(context).registerReceiver(your broadcast receiver instance, IntentFilter(ACTION))
I solved it done a Java Internal Listener with Interface the codes.
package com.jidea.glass;
public interface TelephonyListener
{
/**
* To call this method when new message received and send back
* #param message Message
*/
void callReceived(String message);
}
public class CustomProcess extends AppCompatActivity implements MessageListener, TelephonyListener
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
MessageReceiver.bindListener(this);
TelephonyReceiver.bindListener(this);
Intent newint = getIntent();
address = newint.getStringExtra(MainActivity.EXTRA_ADDRESS); //receive the address of the bluetooth device
setContentView(R.layout.activity_custom_process);
//msg(address);
new ConnectBT().execute(); //Call the class to connect
#Override
public void messageReceived(String message)
{
Toast.makeText(this, "Nova Mensagem: " + message, Toast.LENGTH_SHORT).show();
}
#Override
public void callReceived(String message) {
Toast.makeText(this , "Tele disponivel " + message, Toast.LENGTH_LONG).show();
haveCall(message);
}
Continues in my class Receiver it extends BroadcastReceiver I Donw
public class TelephonyReceiver extends BroadcastReceiver
{
private static TelephonyListener mListener;
#Override
public void onReceive(Context arg0, Intent intent) {
// TODO Auto-generated method stub
}
public static void bindListener(TelephonyListener listener){
mListener = listener;
}
So I have been working with arduino for a while and now I've been trying to connect to the blue-tooth module with android studio. I was able to get the blue-tooth to connect but I'm having issues making the blue-tooth connection a service so that it can run even if the app is closed. Whenever I try to get the service to run on my phone, the app crashes as soon as i try to connect to blue-tooth module where as before when it was an activity, it worked perfectly. I've looked at a lot of links and guides on using services and blue-tooth but none of them do exactly what I want.
Below are some code snippets, but here is a link to the entire GitHub project
Blue-tooth activity that I got to work:
package edu.memphis.teamhack.smart_nightlight;
import android.Manifest;
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.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.support.v4.app.ActivityCompat;
import android.support.v4.content.ContextCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.lang.reflect.Method;
import java.util.Set;
import java.util.UUID;
public class BluetoothActivity extends AppCompatActivity {
// GUI Components
private TextView mBluetoothStatus;
private TextView mReadBuffer;
private Button mScanBtn;
private Button mOffBtn;
private Button mListPairedDevicesBtn;
private Button mDiscoverBtn;
private BluetoothAdapter mBTAdapter;
private Set<BluetoothDevice> mPairedDevices;
private ArrayAdapter<String> mBTArrayAdapter;
private ListView mDevicesListView;
private CheckBox mLED1;
private final String TAG = MainActivity.class.getSimpleName();
private Handler mHandler; // Our main handler that will receive callback notifications
private ConnectedThread mConnectedThread; // bluetooth background worker thread to send and receive data
private BluetoothSocket mBTSocket = null; // bi-directional client-to-client data path
private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // "random" unique identifier
// #defines for identifying shared types between calling functions
private final static int REQUEST_ENABLE_BT = 1; // used to identify adding bluetooth names
private final static int MESSAGE_READ = 2; // used in bluetooth handler to identify message update
private final static int CONNECTING_STATUS = 3; // used in bluetooth handler to identify message status
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_bluetooth);
mBluetoothStatus = (TextView)findViewById(R.id.bluetoothStatus);
mReadBuffer = (TextView) findViewById(R.id.readBuffer);
mScanBtn = (Button)findViewById(R.id.scan);
mOffBtn = (Button)findViewById(R.id.off);
mDiscoverBtn = (Button)findViewById(R.id.discover);
mListPairedDevicesBtn = (Button)findViewById(R.id.PairedBtn);
mLED1 = (CheckBox)findViewById(R.id.checkboxLED1);
mBTArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
mBTAdapter = BluetoothAdapter.getDefaultAdapter(); // get a handle on the bluetooth radio
mDevicesListView = (ListView)findViewById(R.id.devicesListView);
mDevicesListView.setAdapter(mBTArrayAdapter); // assign model to view
mDevicesListView.setOnItemClickListener(mDeviceClickListener);
// Ask for location permission if not already allowed
if(ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED)
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, 1);
mHandler = new Handler(){
public void handleMessage(android.os.Message msg){
if(msg.what == MESSAGE_READ){
String readMessage = null;
try {
readMessage = new String((byte[]) msg.obj, "UTF-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
mReadBuffer.setText(readMessage);
}
if(msg.what == CONNECTING_STATUS){
if(msg.arg1 == 1)
mBluetoothStatus.setText("Connected to Device: " + (String)(msg.obj));
else
mBluetoothStatus.setText("Connection Failed");
}
}
};
if (mBTArrayAdapter == null) {
// Device does not support Bluetooth
mBluetoothStatus.setText("Status: Bluetooth not found");
Toast.makeText(getApplicationContext(),"Bluetooth device not found!",Toast.LENGTH_SHORT).show();
}
else {
mLED1.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
SharedPreferences settings = getSharedPreferences("MyPref",
Context.MODE_PRIVATE);
Integer myInt = settings.getInt("colorHex", 0);
if(mConnectedThread != null){ //First check to make sure thread created
mConnectedThread.write(myInt.toString());}
}
});
mScanBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
bluetoothOn(v);
}
});
mOffBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
bluetoothOff(v);
}
});
mListPairedDevicesBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
listPairedDevices(v);
}
});
mDiscoverBtn.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View v){
discover(v);
}
});
}
}
private void bluetoothOn(View view){
if (!mBTAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
mBluetoothStatus.setText("Bluetooth enabled");
Toast.makeText(getApplicationContext(),"Bluetooth turned on",Toast.LENGTH_SHORT).show();
}
else{
Toast.makeText(getApplicationContext(),"Bluetooth is already on", Toast.LENGTH_SHORT).show();
}
}
// Enter here after user selects "yes" or "no" to enabling radio
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent Data){
// Check which request we're responding to
if (requestCode == REQUEST_ENABLE_BT) {
// Make sure the request was successful
if (resultCode == RESULT_OK) {
// The user picked a contact.
// The Intent's data Uri identifies which contact was selected.
mBluetoothStatus.setText("Enabled");
}
else
mBluetoothStatus.setText("Disabled");
}
}
private void bluetoothOff(View view){
mBTAdapter.disable(); // turn off
mBluetoothStatus.setText("Bluetooth disabled");
Toast.makeText(getApplicationContext(),"Bluetooth turned Off", Toast.LENGTH_SHORT).show();
}
private void discover(View view){
// Check if the device is already discovering
if(mBTAdapter.isDiscovering()){
mBTAdapter.cancelDiscovery();
Toast.makeText(getApplicationContext(),"Discovery stopped",Toast.LENGTH_SHORT).show();
}
else{
if(mBTAdapter.isEnabled()) {
mBTArrayAdapter.clear(); // clear items
mBTAdapter.startDiscovery();
Toast.makeText(getApplicationContext(), "Discovery started", Toast.LENGTH_SHORT).show();
registerReceiver(blReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
else{
Toast.makeText(getApplicationContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show();
}
}
}
final BroadcastReceiver blReceiver = 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);
// add the name to the list
mBTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
mBTArrayAdapter.notifyDataSetChanged();
}
}
};
private void listPairedDevices(View view){
mPairedDevices = mBTAdapter.getBondedDevices();
if(mBTAdapter.isEnabled()) {
// put it's one to the adapter
for (BluetoothDevice device : mPairedDevices)
mBTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
Toast.makeText(getApplicationContext(), "Show Paired Devices", Toast.LENGTH_SHORT).show();
}
else
Toast.makeText(getApplicationContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show();
}
private AdapterView.OnItemClickListener mDeviceClickListener = new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> av, View v, int arg2, long arg3) {
if(!mBTAdapter.isEnabled()) {
Toast.makeText(getBaseContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show();
return;
}
mBluetoothStatus.setText("Connecting...");
// Get the device MAC address, which is the last 17 chars in the View
String info = ((TextView) v).getText().toString();
final String address = info.substring(info.length() - 17);
final String name = info.substring(0,info.length() - 17);
// Spawn a new thread to avoid blocking the GUI one
new Thread()
{
public void run() {
boolean fail = false;
BluetoothDevice device = mBTAdapter.getRemoteDevice(address);
try {
mBTSocket = createBluetoothSocket(device);
} catch (IOException e) {
fail = true;
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
}
// Establish the Bluetooth socket connection.
try {
mBTSocket.connect();
} catch (IOException e) {
try {
fail = true;
mBTSocket.close();
mHandler.obtainMessage(CONNECTING_STATUS, -1, -1)
.sendToTarget();
} catch (IOException e2) {
//insert code to deal with this
Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_SHORT).show();
}
}
if(fail == false) {
mConnectedThread = new ConnectedThread(mBTSocket);
mConnectedThread.start();
mHandler.obtainMessage(CONNECTING_STATUS, 1, -1, name)
.sendToTarget();
}
}
}.start();
}
};
private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
try {
final Method m = device.getClass().getMethod("createInsecureRfcommSocketToServiceRecord", UUID.class);
return (BluetoothSocket) m.invoke(device, BTMODULEUUID);
} catch (Exception e) {
Log.e(TAG, "Could not create Insecure RFComm Connection",e);
}
return device.createRfcommSocketToServiceRecord(BTMODULEUUID);
}
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the input and output streams, using temp objects because
// member streams are final
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) { }
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
byte[] buffer = new byte[1024]; // buffer store for the stream
int bytes; // bytes returned from read()
// Keep listening to the InputStream until an exception occurs
while (true) {
try {
// Read from the InputStream
bytes = mmInStream.available();
if(bytes != 0) {
buffer = new byte[1024];
SystemClock.sleep(100); //pause and wait for rest of data. Adjust this depending on your sending speed.
bytes = mmInStream.available(); // how many bytes are ready to be read?
bytes = mmInStream.read(buffer, 0, bytes); // record how many bytes we actually read
mHandler.obtainMessage(MESSAGE_READ, bytes, -1, buffer)
.sendToTarget(); // Send the obtained bytes to the UI activity
}
} catch (IOException e) {
e.printStackTrace();
break;
}
}
}
/* Call this from the main activity to send data to the remote device */
public void write(String input) {
byte[] bytes = input.getBytes(); //converts entered String into bytes
try {
mmOutStream.write(bytes);
} catch (IOException e) { }
}
/* Call this from the main activity to shutdown the connection */
public void cancel() {
try {
mmSocket.close();
} catch (IOException e) { }
}
}
Here is the Bluetooth Service I'm working on:
package edu.memphis.teamhack.smart_nightlight;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.IBinder;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Toast;
public class BluetoothCommService extends Service {
// #defines for identifying shared types between calling functions
private final static int REQUEST_ENABLE_BT = 1; // used to identify adding bluetooth names
private BluetoothAdapter mBTAdapter;
private ArrayAdapter<String> mBTArrayAdapter;
public BluetoothCommService() {
}
public void onCreate(Bundle savedInstanceState){
//super.onCreate(savedInstanceState);
mBTAdapter = BluetoothAdapter.getDefaultAdapter(); // get a handle on the bluetooth radio
mBTArrayAdapter = new ArrayAdapter<String>(this,android.R.layout.simple_list_item_1);
}
#Override
public IBinder onBind(Intent intent) {
// TODO: Return the communication channel to the service.
throw new UnsupportedOperationException("Not yet implemented");
}
void bluetoothOn(View view){
if (!mBTAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
//startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
//GUI
//mBluetoothStatus.setText("Bluetooth enabled");
// Toast.makeText(getApplicationContext(),"Bluetooth turned on",Toast.LENGTH_SHORT).show();
}
else{
//Toast.makeText(getApplicationContext(),"Bluetooth is already on", Toast.LENGTH_SHORT).show();
}
}
private void bluetoothOff(View view){
mBTAdapter.disable(); // turn off
//GUI
//mBluetoothStatus.setText("Bluetooth disabled");
//Toast.makeText(getApplicationContext(),"Bluetooth turned Off", Toast.LENGTH_SHORT).show();
}
private void discover(View view){
// Check if the device is already discovering
if(mBTAdapter.isDiscovering()){
mBTAdapter.cancelDiscovery();
Toast.makeText(getApplicationContext(),"Discovery stopped",Toast.LENGTH_SHORT).show();
}
else{
if(mBTAdapter.isEnabled()) {
mBTArrayAdapter.clear(); // clear items
mBTAdapter.startDiscovery();
Toast.makeText(getApplicationContext(), "Discovery started", Toast.LENGTH_SHORT).show();
registerReceiver(blReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
}
else{
Toast.makeText(getApplicationContext(), "Bluetooth not on", Toast.LENGTH_SHORT).show();
}
}
}
final BroadcastReceiver blReceiver = 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);
// add the name to the list
mBTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
mBTArrayAdapter.notifyDataSetChanged();
}
}
};
}
Feel free to ask any questions.
Try this instructables, i did it by reffering to this tutorial
http://www.instructables.com/id/Android-Bluetooth-Control-LED-Part-2/
for more idea, also refer to
https://www.intorobotics.com/how-to-develop-simple-bluetooth-android-application-to-control-a-robot-remote/
i got an error when i just open my app.. on the first screen it show splash activity ... and there's an error
W/IInputConnectionWrapper: showStatusIcon on inactive InputConnection
and this one the code on my splash activity, dunno on what section it got warn..
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import com.xxx.xx.helper.SessionManager;
import com.xxx.xx.util.ConnectionDetector;
public class Splash extends AppCompatActivity {
private ConnectionDetector cd;
Boolean isInternetPresent = false;
protected SessionManager session;
AlertDialogManager alert = new AlertDialogManager();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
session = new SessionManager(getApplicationContext());
cd = new ConnectionDetector(getApplicationContext());
Thread timer = new Thread(){
public void run(){
try {
sleep(2000);
} catch (Exception e) {
e.printStackTrace();
} finally {
checking();
}
}
};
timer.start();
}
public void checking() {
isInternetPresent = cd.isConnectingToInternet();
if(isInternetPresent) {
session.checkLogin();
finish();
} else {
alert.showAlertDialog(Splash.this, "No Connection", "Check Your Internet Connection.",false);
finish();
}
}
}
and this one my connection manager code ..
import android.content.Context;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
public class ConnectionDetector {
private Context _context;
public ConnectionDetector(Context context) {
this._context = context;
}
public boolean isConnectingToInternet() {
ConnectivityManager connectivity = (ConnectivityManager) _context.getSystemService(Context.CONNECTIVITY_SERVICE);
if (connectivity != null) {
NetworkInfo info = connectivity.getActiveNetworkInfo();
if (info != null) {
if (info.getState() == NetworkInfo.State.CONNECTED) {
return true;
}
}
}
return false;
}
}
Hello I am new to Android. I want to communicate android with pc to send a text file.
I am trying to communicate using following code.
I am using bluetooth dongle to pc.
When i run application it get crashed without any error. Please help me in communication.
enter code here
package com.exam.bluetooth2;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Set;
import java.util.UUID;
import android.R;
import android.annotation.SuppressLint;
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.EditText;
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;
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.activity_list_item);
mScan = (Button) findViewById(R.id.button1);
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);
}
}
}
});
}
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();
Toast.makeText(getBaseContext(), mBluetoothDevice.getAddress(), 10000).show();
//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());
}
}
// Object device = null;
// String dv = device.toString();
// if(dv.contains("00:1B:EE:82:31:1E"))
// {
// mBluetoothDevice = (BluetoothDevice) device;
// }
}
public void run()
{
try
{
mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(applicationUUID);
mBluetoothAdapter.cancelDiscovery();
mBluetoothSocket.connect();
mHandler.sendEmptyMessage(0);
String messsage = "Welcome to SmarTec";
byte[] tosend=messsage.getBytes();
OutputStream out=mBluetoothSocket.getOutputStream();
out.write(tosend);
}
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, "Device Connected", 5000).show();
// Intent in = new Intent(getBaseContext(), Option.class);
// startActivity(in);
}
};
/* public void sendtext(View v) {//button click
Set<BluetoothDevice> bd = mBluetoothAdapter.getBondedDevices();
sendDataToPairedDevice("message1");
}
private void sendDataToPairedDevice(String message ){
byte[] toSend = message.getBytes();
try {
UUID applicationUUID = UUID.fromString("8ce255c0-200a-11e0-ac64- 0800200c9a66");
BluetoothSocket socket = mBluetoothDevice.createInsecureRfcommSocketToServiceRecord(applicationUUID);
OutputStream mmOutStream = socket.getOutputStream();
mmOutStream.write(toSend);
} catch (IOException e) {
Log.e( "Exception during write", e.toString());
}
}
*/
}
enter code here
package com.exam.bluetooth2;
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.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
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 = 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();
}
};
}
Vijay,
You need to check few thinks below:
Add bluetooth permission in manifest file.
If device is not supporting bluetooth, then you get bluetooth adapter value null. So need to check that also.
Also its better to create broadcast receiver with bluetooth actions.