i got some problem with checkout weather device is connected with PC or not? so i have found that intent action ACTION_UMS_CONNECTED is used to get flag to check weather device is connected with PC or not.
i have tried one example but i cant able to get any flag.... I have past code here
package com.Mediamount;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.telephony.TelephonyManager;
import android.widget.Toast;
public class Mediamount extends Activity {
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentFilter filter = new IntentFilter();
this.registerReceiver(mIntentReceiver, filter);
}
private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
boolean queryRestart = false;
if (action.equals(Intent.ACTION_UMS_CONNECTED)) {
Toast.makeText(getBaseContext(), "asdasd", Toast.LENGTH_LONG).show();
} else if (action.equals(Intent.ACTION_SCREEN_ON)) {
} else if (action.equals(Intent.ACTION_SCREEN_OFF)) {
} else if (action.equals(TelephonyManager.ACTION_PHONE_STATE_CHANGED)) {
}
}
};
}
Is there anything are missing in manifest file so please tell me.
Update:
package com.Mediamount;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.widget.Toast;
public class Mediamount extends Activity {
public static BroadcastReceiver mReceiver1 = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
IntentFilter mIntentFilter = new IntentFilter(Intent.ACTION_UMS_CONNECTED);
// install an intent filter to receive SD card related events.
IntentFilter intentFilter1 = new IntentFilter
(Intent.ACTION_MEDIA_MOUNTED);
intentFilter1.addAction(Intent.ACTION_MEDIA_UNMOUNTED);
intentFilter1.addAction(Intent.ACTION_MEDIA_SCANNER_STARTED);
intentFilter1.addAction(Intent.ACTION_MEDIA_SCANNER_FINISHED);
intentFilter1.addAction(Intent.ACTION_MEDIA_EJECT);
// install an intent filter to receive UMS(USB) related events.
intentFilter1.addAction(Intent.ACTION_UMS_CONNECTED);
intentFilter1.addAction(Intent.ACTION_UMS_DISCONNECTED);
intentFilter1.addAction("USB_INTENT");
intentFilter1.addDataScheme("file");
mReceiver1 = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, context.toString(),Toast.LENGTH_LONG).show();
String action = intent.getAction();
if (action.equals(Intent.ACTION_MEDIA_MOUNTED)) {
//Toast.makeText(context, "SD Card mounted",Toast.LENGTH_LONG).show();
} else if (action.equals
(Intent.ACTION_MEDIA_UNMOUNTED)) {
// Toast.makeText(context, "SD Card unmounted",Toast.LENGTH_LONG).show();
} else if (action.equals
(Intent.ACTION_MEDIA_SCANNER_STARTED)) {
// Toast.makeText(context, "SD Card scanner started",Toast.LENGTH_LONG).show();
//System.out.println("SD Card scanner started");
} else if (action.equals
(Intent.ACTION_MEDIA_SCANNER_FINISHED)) {
// Toast.makeText(context, "SD Card scanner finished",Toast.LENGTH_LONG).show();
} else if (action.equals(Intent.ACTION_MEDIA_EJECT)) {
// Toast.makeText(context, "SD Card eject",Toast.LENGTH_LONG).show();
} else if(action.equals(Intent.ACTION_UMS_CONNECTED))
{
// Toast.makeText(context, "connected",Toast.LENGTH_LONG).show();
} else if(action.equals
(Intent.ACTION_UMS_DISCONNECTED)) {
// Toast.makeText(context, "disconnected",Toast.LENGTH_LONG).show();
}
// BONG_TEST }
}
};
registerReceiver(mReceiver1, intentFilter1);
}}
Related
I was looking for examples.
My class look like:
<pre><code>
package com.example.pjimnez.samsung_auto_reply;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.telephony.PhoneStateListener;
import android.telephony.SmsManager;
import android.telephony.TelephonyManager;
import android.widget.Button;
import android.widget.TextView;
import android.view.View;
import android.widget.Toast;
import android.content.Intent;
import android.content.IntentFilter;
public class MainActivity extends AppCompatActivity {
//IntentFilter screenStateFilter;
Button btnStart;
TextView txtHome;
//PhoneState oPhoneState;
IntentFilter filter1;
private final BroadcastReceiver myPhoneState = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String state = intent.getStringExtra(TelephonyManager.EXTRA_STATE);
if (state == null) {
//Outgoing call
String number = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
Toast.makeText(context, number, Toast.LENGTH_LONG).show();
} else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
//Log.e("tag", "EXTRA_STATE_OFFHOOK");
Toast.makeText(context, "EXTRA_STATE_OFFHOOK", Toast.LENGTH_LONG).show();
} else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
//Log.e("tag", "EXTRA_STATE_IDLE");
Toast.makeText(context, "EXTRA_STATE_IDLE", Toast.LENGTH_LONG).show();
} else if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
//Incoming call
String number = intent.getStringExtra(TelephonyManager.EXTRA_INCOMING_NUMBER);
//Log.e("tag", "Incoming number : " + number);
Toast.makeText(context, number, Toast.LENGTH_LONG).show();
} else
Toast.makeText(context, "none", Toast.LENGTH_LONG).show();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
filter1 = new IntentFilter(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
registerReceiver(this.myPhoneState, filter1);
btnStart = (Button) findViewById(R.id.btnStart);// Instancia del objeto boton intro
//No funciona en modo escucha
btnStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
txtHome = (TextView) findViewById(R.id.txtHome);
txtHome.setText("Dio click en el boton!" );//cambio el contenido del TextView
//Envia el mensahe SMS
/*
SmsManager smsManager = SmsManager.getDefault();
smsManager.sendTextMessage("5524234613", null, "Mensaje de prueba", null, null);
*/
}
});
}
}
enter code here
</code></pre>
My manifest has permissions to:
android.permission.READ_PHONE_STATE
android.permission.RECEIVE_SMS
android.permission.SEND_SMS
The problem is that my app never show the message on phone change state
i do not know whats is wrong with the BroadcastReceiver
Could you helpme
Try this:
1- add a class PhoneStateBroadcastReceiver which extends BroadcastReceiver and overwrite onReceive()
2- at runtime, request PHONE_STATE permission upfront
ActivityCompat.requestPermissions(myMainActivity,
new String[]{Manifest.permission.READ_PHONE_STATE},
READ_PHONE_STATE_CODE);
and give it via the system dialog
3- make a phone call
You'll see the intent caught in onReceive():
intent: Intent { act=android.intent.action.READ_PHONE_STATE flg=0x10 cmp=com.myApp.network.PhoneStateBroadcastReceiver (has extras) }
Action: android.intent.action.PHONE_STATE
Hope it helps
I have built full voice recorder application.
I would like to start recording when a voice call starts on the phone, how can I detect the Calls state? tried some code and it didn't work for me.
I just need to know hot to start recording when a voice call starts (incoming and outgoing).
Here is an example of what you need.
Declare receiver in AndroidManifest
<receiver android:name=".IncomingCall">
<intent-filter>
<action android:name="android.intent.action.PHONE_STATE" />
</intent-filter>
</receiver>
Give read phone state permission in AndroidManifest
<uses-permission android:name="android.permission.READ_PHONE_STATE"/>
Create a class IncomingCall with extends BroadcastReceiver class
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.widget.Toast;
/**
* Created by matheszabi on Aug/20/2017 0020.
*/
public class IncomingCall extends BroadcastReceiver {
private Context context;
public void onReceive(Context context, Intent intent) {
this.context = context;
try {
// TELEPHONY MANAGER class object to register one listner
TelephonyManager tmgr = (TelephonyManager) context
.getSystemService(Context.TELEPHONY_SERVICE);
//Create Listner
MyPhoneStateListener PhoneListener = new MyPhoneStateListener();
// Register listener for LISTEN_CALL_STATE
tmgr.listen(PhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
} catch (Exception e) {
Log.e("Phone Receive Error", " " + e);
}
}
private class MyPhoneStateListener extends PhoneStateListener {
public void onCallStateChanged(int state, String incomingNumber) {
Log.d("MyPhoneListener",state+" incoming no:"+incomingNumber);
if (state == 1) {
String msg = "New Phone Call Event. Incomming Number : "+incomingNumber;
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, msg, duration);
toast.show();
}
}
}
}
Above Android 6.0 you need to handle a bit different the permissions:
import android.Manifest;
import android.content.pm.PackageManager;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private static final int MY_REQUEST_CODE = 1234;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
#Override
protected void onResume() {
super.onResume();
if (checkSelfPermission(Manifest.permission.READ_PHONE_STATE)
!= PackageManager.PERMISSION_GRANTED) {
requestPermissions(new String[]{Manifest.permission.READ_PHONE_STATE},
MY_REQUEST_CODE);
}
}
public void onRequestPermissionResult(int requestCode, String[] permissions, int[] grantResults) {
if (requestCode == MY_REQUEST_CODE) {
if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
// Now user should be able to use camera
Toast.makeText(this, "I have access", Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(this, "I DON'T have access", Toast.LENGTH_SHORT).show();
}
}
}
}
You must allow the permissions at the first time run:
Here is the screenshot of the working code:
I found how to do so:
package com.example.tsuryohananov.mycallrecorder;
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;
/**
* Created by tsuryohananov on 20/08/2017.
*/
public class MyPhoneReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Bundle extras = intent.getExtras();
if (extras != null) {
String state = extras.getString(TelephonyManager.EXTRA_STATE);
Log.d("MY_DEBUG_TAG", state);
if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
String phoneNumber = extras.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
Log.d("MY_DEBUG_TAG", phoneNumber);
// here i need to save the number for the listview.
}
if ((state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK))){
String phoneNumber = extras.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
Toast.makeText(context,"Answered" + phoneNumber, Toast.LENGTH_SHORT).show();
MainActivity.recordStart();
}
if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)){
Toast.makeText(context,"Idle State", Toast.LENGTH_SHORT).show();
MainActivity.stopRecord();
}
}
}
}
Hey I am making an android app based on training samples from developer.android.com Here is my MainActivity Code :
package com.example.hellowifi;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.IntentFilter;
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.WifiP2pInfo;
import android.net.wifi.p2p.WifiP2pManager;
import android.net.wifi.p2p.nsd.WifiP2pDnsSdServiceInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.ListView;
import android.widget.Toast;
public class MainActivity extends Activity {
private final IntentFilter mIntentFilter = new IntentFilter();
private WifiP2pManager mManager = null;
private WifiP2pManager.Channel mChannel = null;
private BroadcastReceiver mReciever;
private ListView mListView;
public static final String TAG = "wifidirectdemo";
// TXT RECORD properties
public static final String TXTRECORD_PROP_AVAILABLE = "available";
public static final String SERVICE_INSTANCE = "_wifidemotest";
public static final String SERVICE_REG_TYPE = "_presence._tcp";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.listView);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_CONNECTION_CHANGED_ACTION);
mIntentFilter.addAction(WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION);
mManager = (WifiP2pManager) getSystemService(Context.WIFI_P2P_SERVICE);
mChannel = mManager.initialize(this, getMainLooper(), null);
mReciever = new WiFiBroadCastReciever(mManager, mChannel, this);
startRegistration();
}
#Override
protected void onResume() {
super.onResume();
mReciever = new WiFiBroadCastReciever(mManager, mChannel, this);
registerReceiver(mReciever, mIntentFilter);
}
#Override
protected void onPause() {
super.onPause();
unregisterReceiver(mReciever);
}
public void OnDiscoverButtonClicked(View view) {
mManager.discoverPeers(mChannel, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Discovery Process Succeded", Toast.LENGTH_SHORT).show();
System.out.println("changed");
}
#Override
public void onFailure(int reason) {
Toast.makeText(MainActivity.this, "Discovery Process Failed", Toast.LENGTH_SHORT).show();
}
});
}
private static List peers = new ArrayList();/*
private ArrayAdapter listAdapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,peers);*/
static WifiP2pManager.PeerListListener peerListListener = new WifiP2pManager.PeerListListener() {
#Override
public void onPeersAvailable(WifiP2pDeviceList peerList) {
peers.clear();
peers.addAll(peerList.getDeviceList());
}
};
private void startRegistration() {
// Create a string map containing information about your service.
Map record = new HashMap();
record.put(TXTRECORD_PROP_AVAILABLE, "visible");
// Service information. Pass it an instance name, service type
// _protocol._transportlayer , and the map containing
// information other devices will want once they connect to this one.
WifiP2pDnsSdServiceInfo serviceInfo =
WifiP2pDnsSdServiceInfo.newInstance("_test", "_presence._tcp", record);
// Add the local service, sending the service info, network channel,
// and listener that will be used to indicate success or failure of
// the request.
mManager.addLocalService(mChannel, serviceInfo, new WifiP2pManager.ActionListener() {
#Override
public void onSuccess() {
Toast.makeText(MainActivity.this, "Added Local Service", Toast.LENGTH_SHORT);
}
#Override
public void onFailure(int arg0) {
Toast.makeText(MainActivity.this,"Failed to add a service",Toast.LENGTH_SHORT);
}
});
}
}
and my Broadcastreciever class is this :
package com.example.hellowifi;
import java.util.HashMap;
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.WifiP2pManager;
import android.net.wifi.p2p.WifiP2pManager.PeerListListener;
import android.util.Log;
import android.widget.Toast;
public class WiFiBroadCastReciever extends BroadcastReceiver {
private MainActivity activity;
private WifiP2pManager mManager=null;
private WifiP2pManager.Channel mChannel=null;
PeerListListener myPeerListListener = null;
public WiFiBroadCastReciever(WifiP2pManager manager, WifiP2pManager.Channel channel,
Activity activity) {
super();
this.mManager = manager;
this.mChannel = channel;
this.activity = (MainActivity) activity;
}
#Override
public void onReceive(Context context, Intent intent) {
String action=intent.getAction();
if (WifiP2pManager.WIFI_P2P_STATE_CHANGED_ACTION.equals(action)){
int state=intent.getIntExtra(WifiP2pManager.EXTRA_WIFI_STATE,-1);
if (WifiP2pManager.WIFI_P2P_STATE_ENABLED==state)
Log.d("WiFiBroadCastReciever", "WiFi enabled");
else
Log.d("WiFiBroadCastReciever", "WiFi disabled");
}
else if (WifiP2pManager.WIFI_P2P_PEERS_CHANGED_ACTION.equals(action)){
Toast.makeText(activity, "in intent", Toast.LENGTH_LONG).show();
if (mManager != null) {
mManager.requestPeers(mChannel, myPeerListListener);
}
}
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, connectionListener);*/
}
}
else if (WifiP2pManager.WIFI_P2P_THIS_DEVICE_CHANGED_ACTION.equals(action)){
}
}
final HashMap<String, String> buddies = new HashMap<String, String>();
}
I am getting successful calls to Broadcasting Intents WIFI_P2P_STATE_CHANGED_ACTION,WIFI_P2P_CONNECTION_CHANGED_ACTION,WIFI_P2P_THIS_DEVICE_CHANGED_ACTION but not to WIFI_P2P_PEERS_CHANGED_ACTION
when I am making tethering and portable hotspot to other device and trying to discovering on my device.
Note that: WiFi is enabled and I am also getting Toast of Discovery successful. After that WIFI_P2P_PEERS_CHANGED_ACTION intent is not calling.
I tried searching on each and every thread.
Please try to help me someone. Thanks in advance.
You need to run discoverPeers() on other devices as well.
Now you will receive the WIFI_P2P_PEERS_CHANGED_ACTION intent
I had the same problem before. Please check below scenario how I have fixed the issue.
First I have implemented the same code in server and client android device with minor changes. I have placed a button in server app to invoke the discoverPeers() method. At the same time my client app is running and connected to the same WI-FI network. Then it triggers the WIFI_P2P_PEERS_CHANGED_ACTION event from broadcast in server app. There I have got the list of nearby peers.
I develop an bluetooth app which will connect to a paired device and send a message, but I have to test connection before. I've tried many options, but nothing works in good way. So could you send me any example of code which can do it? I made an thread, but I can't get an good state of connection to build an "if" function. Here is the code:
package com.example.szukacz;
import java.lang.reflect.Method;
import java.util.Set;
import android.app.Activity;
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.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
LinearLayout sparowaneUrzadzenia;
public void lokalizowanie() {
Intent intencja = new Intent(this, Lokalizator.class);
startActivity(intencja);
}
public void parowanie(View v) {
Intent intencja = new Intent(this, Parowanie.class);
startActivity(intencja);
}
boolean isRunning;
Handler handler = new Handler() {
#Override
public void handleMessage(Message msg) {
String status = (String)msg.obj;
if(status == "polaczony") {
alarm();
showToast("prawda, zwraca" + status);
} else {
showToast("wykonanie x, zwraca: " + status);
};
}
};
public void alarm() {
showToast("Alarm!!!");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sparowaneUrzadzenia = (LinearLayout) findViewById(R.id.listaUrzadzenGlowna);
pokazSparowane();
}
public void onStop() {
super.onStop();
isRunning = false;
}
public void onStart() {
super.onStart();
Thread testPolaczen = new Thread(new Runnable() {
public void run() {
try {
for(int i = 0; i < 1000000; i++) {
Thread.sleep(5000);
testujPolaczenia();
int stan = 0;
String status = Integer.toString(stan);
Message msg = handler.obtainMessage(1, (String)status);
if(isRunning == true) {
handler.sendMessage(msg);
}
}
} catch (Throwable t) {
// watek stop
}
}
});
isRunning = true;
testPolaczen.start();
}
private void testujPolaczenia() {
}
public void pokazSparowane(){
/*
* Wyświetlanie listy sparowanych urządzeń .
* */
Log.d("INFO","Sparowane dla tego urzÄ…dzenia");
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
Set<BluetoothDevice> pairedDevices = mBluetoothAdapter.getBondedDevices();
if (pairedDevices.size() > 0) {
for (BluetoothDevice device : pairedDevices) {
Log.d("INFO",device.getName()+" - "+device.getAddress());
// dodawanie urzadzen do listy
Button urzadzenie = new Button(getApplicationContext());
urzadzenie.setText(device.getName());
// urzadzenie.setTextColor(0xffffff); //jak ustawic na czarny kolor napsisów ?
urzadzenie.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
showToast("klik");
lokalizowanie();
}
});
sparowaneUrzadzenia.addView(urzadzenie);
}
} else {
showToast("brak sparowanych urzadzen");
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
private void showToast(String message) {
Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
thanks!
I faced the same problem as I am working on an app which may use TTS while it is running. I think there is no way to check if there is any bluetooth device connected by the BluetoothAdapter class immediately except creating a broadcast receiver and monitor the changes of status of bluetooth.
After scratching my head for a few hours, I found a quite subtle way to solve this problem. I tried, it works pretty well for me.
AudioManager audioManager = (AudioManager) getApplicationContext.getSystemService(Context.AUDIO_SERVICE);
if (audioManager.isBluetoothA2dpOn()) {
//audio is currently being routed to bluetooth -> bluetooth is connected
}
Source: http://developer.android.com/training/managing-audio/audio-output.html
I think it's to late for answer to your question but I think can helps somebody :
If you use Thread you have to create a BroadcastReceiver in your main activity on create :
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_digital_metrix_connexion);
BroadcastReceiver bState = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if(action.equals(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED))
{
int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
switch (state)
{
case BluetoothAdapter.ACTION_ACL_CONNECTED:
{
//Do something you need here
System.out.println("Connected");
break;
}
default:
System.out.println("Default");
break;
}
}
}
};
}
BluetoothAdapter.STATE_CONNECTED is one state over many, for exemple it's possible to check if device connecting or disconnecting thanks to BluetoothAdapter.ACTION_ACL_DISCONNECTED or BluetoothAdapter.ACTION_ACL_DISCONNECTED_REQUEST .
After, you have to create a filter in your thread class or in you main activity if you don't use thread :
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
This filter check the bluetoothadapter state.
And now you have to register your filter so if you use thread pass context in parameter of your thread like this context.registerReceiver(bState,filter);
or in your main Activity : registerReceiver(bState,filter);
If you have any question don't hesitate to ask me.
Hope I helps you somebody.
I'm new here so I apologize if I wrote something bad
I got some error in my code that should find some but device (in Eclipse it looks ok but it shows some Force Quit while I'm clicking button Find Device :(
Code
package com.moj.test;
import android.app.Activity;
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.view.View;
import android.widget.Button;
import android.widget.EditText;
public class Bluetooth extends Activity{
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
private static final int REQUEST_ENABLE_BT = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.bluetooth);
Button bStart = (Button) findViewById(R.id.btbutton1);
Button bFind = (Button) findViewById(R.id.btbutton2);
bStart.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
BluetoothStart();
}
});
bFind.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Register the BroadcastReceiver
IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
registerReceiver(mReceiver, filter); // Don't forget to unregister during onDestroy
mBluetoothAdapter.startDiscovery();
}
});
}
public void BluetoothStart() {
if (mBluetoothAdapter != null) {
if (!mBluetoothAdapter.isEnabled()) {
//Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE), REQUEST_ENABLE_BT);
}
}
}
// Create a BroadcastReceiver for ACTION_FOUND
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
public void onReceive(Context context, Intent intent) {
EditText te = (EditText) findViewById(R.id.editText1);
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);
// Add the name and address to an array adapter to show in a ListView
te.setText(device.getName() + "\n" + device.getAddress());
}
}
};
}
You cant run this on Emulator because it doesn't have support for Bluetooth. You need to test it on a real device.
And don't forget to include Bluetooth permission in manifest.
<manifest ... >
<uses-permission android:name="android.permission.BLUETOOTH" />
...
</manifest>