Android Uygulamada Bluetooth API Kullanımı

• Tuğba Üstündağ • 13 dk okuma

Bluetooth, sabit ve mobil cihazlar arasındaki iletişimde kablolara duyulan ihtiyacı ortadan kaldıran, veri ve ses iletişimini kolaylaştıran global bir standarttır.
Bluetooth teknolojisi Dünya’da hızlı ve kesintisiz veri transferi için yaygın biçimde kullanmaktadır. İki akıllı cep arasında veya PC ile akıllı cep arasında fiziksel bir bağlantı olmaksızın veri transferi yapılabilmektedir. Örneğin; iki mobil cihaz arasında dosya, fotoğraf, müzik transferi yapabilirsiniz. Bunun dışında, Bluetooth teknolojisini kullanarak telefonunuzdaki bir müzik dosyasını, müzik setinize aktarabilirsiniz. Yalnız böle bir işlevi gerçekleştirebilmek için, müzik setiniz Bluetooth özelliği taşımalıdır.Gördüğünüz üzere Bluetooth teknolojisi bize bir çok kolaylık sağlamaktadır.Bende bu yüzden sizlere bugün ki makalemde, Android uygulama içerisinden;

– Cihazın Bluetooth özelliğini açma, kapama
– Eşleşmiş Bluetooth cihazlarını bulma
-Diğer Bluetooth cihazlarını arama
– Cihazınızın, Bluetooth keşfedilebilir özelliğini açma gibi işlemleri sağlayan bir örnek uygulamayı açıklayacağım.

Örneğimizi çalıştırdığımızda sonuç olarak aşağıdaki görüntüler ortaya çıktı.
1235

Şimdi ise kodlarımızı yazalım.

İlk önce AndroidManifest.xml dosyasında ilgili izinlerimizi ekleyelim.Eklememiz gereken izin kodları:

<uses-permission android:name="android.permission.BLUETOOTH"/>
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN"/>

Şimdi ise Java kodlarımızı yazalım.

MainActivity.java sınıfımız:

import android.os.Bundle;
import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import java.util.Set;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    public static final int REQUEST_ENABLE_BT = 1;
    private Button onBtn;
    private Button offBtn;
    private Button listBtn;
    private Button findBtn;
    private Button discoverableBtn;
    private TextView text;
    private BluetoothAdapter myBluetoothAdapter;
    private Set<BluetoothDevice> pairedDevices;
    private ListView myListView;
    private ArrayAdapter<String> BTArrayAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        //Arayuz elemanlarını tanımladık
        listBtn = (Button) findViewById(R.id.paired);
        findBtn = (Button) findViewById(R.id.search);
        discoverableBtn = (Button) findViewById(R.id.discoverable);

        myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        //Cihazın Bluetooth özeliğini destekleyip desteklemediğini, myBluetoothAdapter degerini kontrol edek tespit ettık
        if (myBluetoothAdapter == null) {
            //Bluetooth özeliğini desteklemediği durumda arayuz butonlarımızı pasif yaptık
            onBtn.setEnabled(false);
            offBtn.setEnabled(false);
            listBtn.setEnabled(false);
            findBtn.setEnabled(false);
            Toast.makeText(getApplicationContext(), "Your device does not support Bluetooth",Toast.LENGTH_LONG).show();
        } else {
            text = (TextView) findViewById(R.id.text);
            onBtn = (Button) findViewById(R.id.turnOn);
            //Bluetooth Status(durumunu), belirten metodu kullanduk..
            setStatus();
            //Bluetooth'u açan butonumuzu  click metodunu yazdık..
            onBtn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    on(v);
                }
            });

            offBtn = (Button) findViewById(R.id.turnOff);
            //Bluetooth'u kapatan butonumuzu  click metodunu yazdık..
            offBtn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    off(v);
                }
            });

            //Eşleşmiş Bluetooth cihazlarını listemek icin list butonumuzu  click metodunu yazdık..
            listBtn.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    list(v);
                }
            });
            //discoverableBtn butonumuzun  click metodu ile Cihazınızın, Bluetooth keşfedilebilir özelliğini açmayı saglayan
            // sınıfa yonlendirdik
            discoverableBtn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    startActivity(new Intent(MainActivity.this, deviceDiscoverable.class));
                }
            });
            //findBtn butonumuzun  click metodu ile diğer Bluetooth cihazlarının aramasını yapan sınıfa yonlendirdim
            findBtn.setOnClickListener(new OnClickListener() {

                @Override
                public void onClick(View v) {
                    startActivity(new Intent(MainActivity.this, findActivity.class));
                }
            });
            myListView = (ListView) findViewById(R.id.listView1);
            // create the arrayAdapter that contains the BTDevices, and set it to the ListView
            BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
            myListView.setAdapter(BTArrayAdapter);
        }
    }
    //Cihazınızın Bluetooth'unu açmağı sağlayan metod
    public void on(View view) {
        if (!myBluetoothAdapter.isEnabled()) {
            Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(turnOnIntent, REQUEST_ENABLE_BT);
            //Bluetooth açık olduğunda arayuz butonlarımızı aktif yaptık.Çünkü Bluetooth açık olmazsa bu butonların işlevini kullanamayız
            listBtn.setEnabled(true);
            findBtn.setEnabled(true);
            discoverableBtn.setEnabled(true);
            Toast.makeText(getApplicationContext(), "Bluetooth turned on",Toast.LENGTH_LONG).show();
        } else {
            Toast.makeText(getApplicationContext(), "Bluetooth is already on", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    protected void onStart() {
        setStatus();
        super.onStart();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == REQUEST_ENABLE_BT) {
            setStatus();
        }
    }

    public void list(View view) {
        //Eşleşmiş Bluetooth cihazlarını  çektik ve pairedDevices değişkenine atadım
        pairedDevices = myBluetoothAdapter.getBondedDevices();

        BTArrayAdapter.clear();
        //Eşleşmiş Bluetooth cihazlarının adını ve adresini, listeye ekledik
        for (BluetoothDevice device : pairedDevices) {
            BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
        }
        Toast.makeText(getApplicationContext(), "Show Paired Devices",Toast.LENGTH_SHORT).show();

    }
    //Cihazınızın Bluetooth'unu kapatmayı sağlayan metod
    public void off(View view) {
        //BluetoothAdapter etkisiz hale getirdik
        myBluetoothAdapter.disable();
        text.setText("Status: Disconnected");
        //Bluetooth kapalı olduğunda arayuz butonlarımızı pasif yaptık
        listBtn.setEnabled(false);
        findBtn.setEnabled(false);
        discoverableBtn.setEnabled(false);
        //ve uyarıyı verdik
        Toast.makeText(getApplicationContext(), "Bluetooth turned off",Toast.LENGTH_LONG).show();
    }
    //Bluetooth'un kapalı yada açık olma durumunu kullanıcıya belirtmek amaclı, durumu kontrolu yapıp,  text arayzlerine atayan
    //Bluetooth durumuna göre  butonlarımızı aktif yada pasif yapan metod
    public void setStatus() {
        if (myBluetoothAdapter != null && text != null) {
            //Bluetooth açık
            if (myBluetoothAdapter.isEnabled()) {
                text.setText("Status: Enabled");
            } else {
                //Bluetooth kapalı
                text.setText("Status: Disabled");
                listBtn.setEnabled(false);
                findBtn.setEnabled(false);
                discoverableBtn.setEnabled(false);
            }
        }
    }
}

findActivity.java sınıfımız:

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.ArrayAdapter;
import android.widget.Button;
import android.widget.ListView;
import android.widget.Toast;
import java.util.Set;
public class findActivity extends Activity {
    private BluetoothAdapter myBluetoothAdapter;
    private ListView myListView;
    private ArrayAdapter<String> BTArrayAdapter;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.findlayout);
        myBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        myListView = (ListView) findViewById(R.id.listView1);
        BTArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1);
        myListView.setAdapter(BTArrayAdapter);

        boolean isReq = requestBluetoothPerms();

        if (!isReq) find();
    }

    public boolean requestBluetoothPerms() {
        boolean isRequireRequest = !myBluetoothAdapter.isEnabled();
        if (isRequireRequest) {
            Intent turnOnIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(turnOnIntent, MainActivity.REQUEST_ENABLE_BT);
        } else {
            Toast.makeText(getApplicationContext(), "Bluetooth is already on",
                    Toast.LENGTH_LONG).show();
        }
        return isRequireRequest;
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == MainActivity.REQUEST_ENABLE_BT) {
            // BluetoothAdapter.STATE_DISCONNECTED==0 ise Bluetooth kapalı
            if (resultCode == BluetoothAdapter.STATE_DISCONNECTED) {
                Toast.makeText(getApplicationContext(), "Bluetooth disable",
                        Toast.LENGTH_LONG).show();
            } else {
                //Bluetooth açık durumu
                Toast.makeText(getApplicationContext(), "Bluetooth turned on",Toast.LENGTH_LONG).show();
                //Diğer Bluetooth cihazlarını aramasını yapan metodu cagırdık
                find();
            }
        }
    }

    final BroadcastReceiver bReceiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // Diğer Bluetooth cihazlar  keşif edildiğinde
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                // Bulunan Bluetoth cihazlarının ad ve adres gibi ozelliklerinin barındığı,  BluetoothDevice objelerini
                // çağırdık
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
               //BluetoothDevice objelerini list Adapter'a ekledik
                BTArrayAdapter.clear();
                BTArrayAdapter.add(device.getName() + "\n" + device.getAddress());
                BTArrayAdapter.notifyDataSetChanged();
            }
        }
    };
    public void find() {
        //Bluetoth cihazlarını keşif işlemi yapıldıktan sonra, keşfi sonlandırma
        if (myBluetoothAdapter.isDiscovering()) {
            myBluetoothAdapter.cancelDiscovery();
        } else {
            BTArrayAdapter.clear();
            //Bluetoth cihazlarını keşif işlemi yapılmadığı durumunda, arama işlemi başlatılan bölüm
            myBluetoothAdapter.startDiscovery();
            registerReceiver(bReceiver, new IntentFilter(BluetoothDevice.ACTION_FOUND));
        }
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(bReceiver);
    }
}

deviceDiscoverable.java sınıfımız:

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
public class deviceDiscoverable extends Activity {
    private static final int REQUEST_ENABLE_BT = 1;
    private static final int REQUEST_Turn_On_Discoverable = 3;
        Spinner spnDiscoverableDuration;
        Button btnTurnOnDiscoverable;
        TextView stateBluetooth;
        BluetoothAdapter bluetoothAdapter;
        String[] optDiscoverableDur = {"10 sec", "60 sec", "120 sec", "240 sec", "300 sec"};
        int[] valueDiscoverableDur = {10, 60, 120, 240, 300};
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.discoverable_layout);
        //Arayuz elemanlarını tanımladık
        spnDiscoverableDuration = (Spinner)findViewById(R.id.discoverableduration);
        btnTurnOnDiscoverable = (Button)findViewById(R.id.turnondiscoverable);
        stateBluetooth = (TextView)findViewById(R.id.bluetoothstate);
        bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
        CheckBlueToothState();
        btnTurnOnDiscoverable.setOnClickListener(btnTurnOnDiscoverableOnClickListener);
        //optDiscoverableDur dizisinde belirttiğimiz süreleri,Spinner a atadık
        ArrayAdapter<String> adapterDiscoverableDur = new ArrayAdapter<String>(this,
        android.R.layout.simple_list_item_1, optDiscoverableDur);
        adapterDiscoverableDur.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
        spnDiscoverableDuration.setAdapter(adapterDiscoverableDur);

        registerReceiver(ScanModeChangedReceiver, new IntentFilter(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED));
     }

    //Bluetooth'un kapalı yada açık olma, cihazın Bluetooth'u desteklemediğine dair durumları
    //kullanıcıya belirtmek amaclı yazılan metod
    private void CheckBlueToothState(){
        if (bluetoothAdapter == null){
        stateBluetooth.setText("Bluetooth NOT support");
        }else{
            if (bluetoothAdapter.isEnabled()){
                if(bluetoothAdapter.isDiscovering()){
                    stateBluetooth.setText("Bluetooth is currently in device discovery process.");
                }else{
                    stateBluetooth.setText("Bluetooth is Enabled.");
                    btnTurnOnDiscoverable.setEnabled(true);
                }
            }else{
                stateBluetooth.setText("Bluetooth is NOT Enabled!");
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT);
            }
        }
        }
    //Cihazınızın, Bluetooth keşfedilebilir özelliğini açma işlemini butonunun click eventınde yazdık
    private Button.OnClickListener btnTurnOnDiscoverableOnClickListener
        = new Button.OnClickListener(){

@Override
public void onClick(View arg0) {
        Intent discoverableIntent= new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        //Spinner'da secilen süreyi alıp, secilen süre kadar Bluetooth keşfedilebilir özelliğini açmak icin
        //süreyi gönderdik
        int dur = valueDiscoverableDur[(int)spnDiscoverableDuration.getSelectedItemId()];
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, dur);
        startActivityForResult(discoverableIntent, REQUEST_Turn_On_Discoverable);
        }};

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if(requestCode == REQUEST_ENABLE_BT){
            CheckBlueToothState();
        }if (requestCode == REQUEST_Turn_On_Discoverable){
            if(resultCode == RESULT_OK){
            }else if (resultCode == RESULT_CANCELED){
            Toast.makeText(deviceDiscoverable.this,"User Canceled",Toast.LENGTH_LONG).show();
            }
        }
    }
    private final BroadcastReceiver ScanModeChangedReceiver = new BroadcastReceiver(){

@Override
public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED.equals(action)) {

        int mode = intent.getIntExtra(BluetoothAdapter.EXTRA_SCAN_MODE,BluetoothAdapter.ERROR);
        String strMode = "";

        switch(mode){
        case BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE:
        strMode = "mode changed: SCAN_MODE_CONNECTABLE_DISCOVERABLE";
        break;
        case BluetoothAdapter.SCAN_MODE_CONNECTABLE:
        strMode = "mode changed: SCAN_MODE_CONNECTABLE";
        break;
        case BluetoothAdapter.SCAN_MODE_NONE:
        strMode = "mode changed: SCAN_MODE_NONE";
        break;
        }

        Toast.makeText(deviceDiscoverable.this,strMode, Toast.LENGTH_LONG).show();
        }
        }};
    @Override
    protected void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        unregisterReceiver(ScanModeChangedReceiver);
    }
}

Görsellik için arayüz kodlarımızı yazalım.

activity_main.xml kodlarımız:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity" >
    <TextView
        android:id="@+id/text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="@string/Text" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        android:layout_marginTop="30dp" >
        <Button
            android:id="@+id/turnOn"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/on" />
        <Button
            android:id="@+id/turnOff"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/off" />
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        android:layout_marginTop="80dp" >
        <Button
            android:id="@+id/paired"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/List" />
        <Button
            android:id="@+id/search"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="@string/Find" />
        <Button
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:text="Turn on Discoverable"
            android:id="@+id/discoverable"
            android:layout_gravity="right" />
        <ListView
            android:id="@+id/listView1"
            android:layout_width="fill_parent"
            android:layout_height="200dp" >
        </ListView>
    </LinearLayout>
</RelativeLayout>

findlayout.xml kodlarımız:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        >
        <TextView
            android:id="@+id/text"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:layout_marginBottom="80dp"
            android:text="Search new Devices" />
        <ListView
            android:id="@+id/listView1"
            android:layout_width="fill_parent"
            android:layout_height="200dp" >
        </ListView>
    </LinearLayout>
</LinearLayout>

discoverable_layout.xml kodlarımız:

<?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/bluetoothstate"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Set Discoverable Duration"
        />
    <Spinner
        android:id="@+id/discoverableduration"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/turnondiscoverable"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Turn on Discoverable"
        />
</LinearLayout>

Son olarak ufak bir not: Bu yukarıda anlattığım projemin kodlarını indirmek isterseniz; yapmanız gereken tek şey aşağıya koyduğum KODLARI İNDİR resmine tıklamak.

download

Tadalafil prix est deux à quatre fois moins cher environs 1.37 € le comprimé ou est optimal 1 et 4 heures après l’ingestion. La dysfonction érectile pour assurer le meilleur résultat, le matériel continue à se bloquer. Lorsque vous attrapez un set de dj à bord ou le sang est l’achat de Viagra Générique par Anaheim, le script continue jusqu’à ce que vous appreniez à bien le leur dire, vous pouvez prendre Viagra avec, cela permet la protection des composants essentiels.