Thursday, April 14, 2016

Enable Bluetooth

Hi ... Dear All ..Today I am uploading a superb example to ask for Enable Bluetooth on your device.

Please check.
I am using Android Studio 1.5.1
Minimun SDK API 19
Target SDK API 23
Please Like us & put your valuable suggestions in comment box.
***** check on physical device
*****  Default layout file nothing added
**** we have to use BluetoothAdapter class for this and method is getDefaultAdapter()
**** check using isEnabled() method if not send the request.
**** Add permission in manifest file
<uses-permission android:name="android.permission.BLUETOOTH"></uses-permission>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"></uses-permission>

A. Java File MainActivity.java

package com.exam.ravi.bluetoothex1;

import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    BluetoothAdapter bluetoothAdapter;
    static final int REQUEST_FOR_BLUETOOTH= 0;
    @Override    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        Toast.makeText(this,"Bluetooth Available : "+BluetoothAvail(),
                                         Toast.LENGTH_LONG).show();
        if(BluetoothAvail())
            EnbleBlue();
    }
    private boolean BluetoothAvail()
    {
        if(bluetoothAdapter==null)
            return false;
        else            return true;
    }
    private void EnbleBlue()
    {
        if(BluetoothAvail() && !bluetoothAdapter.isEnabled())
        {
            Intent iob= new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(iob,REQUEST_FOR_BLUETOOTH);
        }
    }

    @Override

    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode==REQUEST_FOR_BLUETOOTH)
        {
            if(resultCode==RESULT_OK)
            {
             Toast.makeText(this," Bluetooth Turned ON ",Toast.LENGTH_LONG).show();
            }
        }
    }
}

No comments:

Post a Comment