I need to turn on Bluetooth in an android device programmatically and wait till it on to proceed to next line of code.
My code is as below
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
ctx.startActivity(enableBtIntent);
}
When doing like this, the code continue to execute from next line without waiting for bluetooth completely on. Is there any way to solve this? Can I add a look to check if bluetooth is on?
You can register a BroadcastReceiver to listen for state changes on the BluetoothAdapter.
First create a BroadcastReceiver that will listen for state changes
private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
final String action = intent.getAction();
if (action.equals(BluetoothAdapter.ACTION_STATE_CHANGED)) {
final int bluetoothState = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE,
BluetoothAdapter.ERROR);
switch (bluetoothState) {
case BluetoothAdapter.STATE_ON:
//Bluethooth is on, now you can perform your tasks
break;
}
}
}
};
Then register the BroadcastReceiver with your Activity when it is created so that it can start receiving events.
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Set a filter to only receive bluetooth state changed events.
IntentFilter filter = new IntentFilter(BluetoothAdapter.ACTION_STATE_CHANGED);
registerReceiver(mReceiver, filter);
}
Remember to unregister the listener when the Activity is destroyed.
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
You can use startActivityForResult() and check for whether resultCode is RESULT_OK in onActivityResult() with bluetooth permission in your Manifest file like..
mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (!mBluetoothAdapter.isEnabled()) {
Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableIntent, 0);
}
onActivityResult
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
// bluetooth enabled
}else{
// show error
}
}
ACTION_REQUEST_ENABLE
Use this code
Permissions on your menifest file
<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>
and code
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent , 0);
} else
{
Toast.makeText(getApplicationContext(),"Already on", Toast.LENGTH_LONG).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode == RESULT_OK){
Toast.makeText(getApplicationContext(),"Turned on",Toast.LENGTH_LONG).show();
}
if(resultCode == RESULT_CANCELED){
}
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
//do your things
}
Related
I have an activity where I ask to enable Bluetooth and discovery mode.
Requests are executed correctly and are taken by onactivityresult().
The problem is in the discovery request.
If I click on reject then RESULT_CANCELED is taken correctly, while if I click on allow, the result code is 120 and therefore it is not RESULT_OK and I cannot start the activity, it is normal that it is 120 and not RESULT_OK?
MyActivity
public class TransitionActivity extends AppCompatActivity {
private static final int ENABLE_REQUEST = 0;
private static final int DISCOVER_REQUEST = 1;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_transition);
BluetoothAdapter bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if(bluetoothAdapter == null){ //bluetooth not supported
Toast.makeText(this, "Bluetooth not supported.", Toast.LENGTH_SHORT).show();
finish();
}
if(!bluetoothAdapter.isEnabled()){
Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(i,ENABLE_REQUEST);
}
if(!bluetoothAdapter.isDiscovering()){
Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
startActivityForResult(i,DISCOVER_REQUEST);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, #Nullable Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(requestCode == ENABLE_REQUEST){
if(resultCode == RESULT_OK){
}
if(resultCode == RESULT_CANCELED){
Toast.makeText(this, "You need to enable the bluetooth.", Toast.LENGTH_SHORT).show();
finish();
}
}
if(requestCode == DISCOVER_REQUEST){
System.out.println("RESULT CODE" + resultCode); //it is 120
if(resultCode == RESULT_OK){ //skipped
Intent secondActivity = new Intent(this, com.project.secondActivity.class);
this.startActivity(secondActivity);
}
if(resultCode == RESULT_CANCELED){
finish();
}
}
}
}
Value of resultCode is same as discoverable duration EXTRA_DISCOVERABLE_DURATION passed in Intent.
and by default duration is 120. So it is OK.
If you will start activity like this
Intent i = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
i.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 240);
startActivityForResult(i,DISCOVER_REQUEST);
It will return 240 as result code.
I am new in android. I was making a sample. I was going to ask a user to turn on bluetooth. The ask form shows but onActivity result does not work. Why?
Here is my code:
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, RESULT_OK);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Toast.makeText(this, "onActivityResult", Toast.LENGTH_SHORT).show();
}
}
Your request code should be greater than Zero, but RESULT_OK = -1 so try to give Request code more than 0,
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, 101);
Src
RESULT_OK is -1 and startActivityForResult expects requestCode >=0.
RESULT_OK (added in API level 1)
int RESULT_OK
Standard activity result: operation succeeded.
Constant Value: -1 (0xffffffff)
Method startActivityForResult (added in API level 1)
void startActivityForResult (Intent intent, int requestCode)
Parameters
intent Intent: The intent to start.
requestCode int: If >= 0, this code will be returned in onActivityResult() when the activity exits.
Throws
android.content.ActivityNotFoundException
You should handle response as per requestCode.
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// Can use switch case also if more requestCode
if (requestCode == 100) {
// do something
} else if (requestCode == 101) {
// do something
} else {
// do something
}
Toast.makeText(this, "onActivityResult", Toast.LENGTH_SHORT).show();
}
This is my code, for turning on the bluetooth:
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
Also:
public static final int REQUEST_ENABLE_BT = 9;
This is my onActivityResult:
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case REQUEST_ENABLE_BT:
if (resultCode == Activity.RESULT_OK) {
bluetoothSetupDone();
} else {
// User did not enable Bluetooth or an error occurred
}
break;
default:
super.onActivityResult(requestCode, resultCode, data);
break;
}
}
The result code is correct, but the request code is not.
Even if the user presses no, or yes on the popup dialog for turning on bluetooth. The value of the requestCode variable in the onActivityResult is some random number (196617), but it should be 9.
Damn. Should have used:
getSupportActivity().startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
wrong requestCode in onActivityResult
http://blog.tgrigsby.com/2012/04/18/android-fragment-frustration.aspx
I was calling startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); from a fragment, So i added getActivity().startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);and this solved my issue.
I want to Scan QR codes on button Click, problem is when I run code on my device Activity Result Intent variable always returns 0.
How do I know if the barcode reader work? I currently see yellow dots on the device's screen.
Here is my code:
private OnClickListener scanner = new OnClickListener() {
public void onClick(View v) {
IntentIntegrator.initiateScan(BarCodeScannerActivity.this);
}
};
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (scanResult != null) {
// handle scan result
String s = "http://www.google.com/search?q=";
s += scanResult.getContents();
Intent myIntent1 = new Intent(Intent.ACTION_VIEW, Uri.parse(s));
startActivity(myIntent1);
}
Thanks
You have error in code
You should have
#Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) {
IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, intent);
if (result != null) {
String contents = result.getContents();
if (contents != null) {
showDialog(R.string.result_succeeded, result.toString());
} else {
showDialog(R.string.result_failed, getString(R.string.result_failed_why));
}
}
}
You are not overriding the onActivityResult like onCreate or onStart
Rather you are writing onActivityResult like normal method which is most common mistake.
Also if you can mention integrator.initiateScan(IntentIntegrator.QR_CODE_TYPES); or integrator.initiateScan(IntentIntegrator.PRODUCT_CODE_TYPES); it would be great.
I have the next code:
class Printer{
Activity activity;
public Printer (Activity activity) {
this.activity = activity;
initializeBluetooth();
}
public boolean initializeBluetooth() {
BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
if (mBluetoothAdapter == null) {
Context context = activity.getApplicationContext();
Toast toast = Toast.makeText(context, activity.getString(R.string.notSupportedBluetooth), 3000);
toast.show();
return false;
} else {
if (!mBluetoothAdapter.isEnabled()) {
Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
activity.startActivityForResult(enableBtIntent, 0);
return false;
}
}
return true;
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
System.out.println(resultCode);
if (resultCode == 0) {
System.out.println("one");
} else {
System.out.println("two");
}
}}
The problem is the onActivityResult, i know it can not be called because the class is not an Activity, so how can i check if the user clicked yes or no to the bluetooth request with out turning my class to an activity??? activity.startActivityForResult(enableBtIntent, 0);
Thank you
Why are you doing this? Just include all of the bluetooth functionality in the Activity class... there is no need to create a separate class for this.
Anyway, just copy and paste your onActivityResult code into your Activity file:
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
System.out.println(resultCode);
if (resultCode == 0) {
System.out.println("one");
} else {
System.out.println("two");
}
}
It makes no sense to include onActivityResult in your Printer class, as onActivityResult will be called for the calling Activity.