BLUETOOTH THREAD
Diğer Yazılarımız
MainActivity Java Kodu
import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.view.View; import android.widget.AdapterView; import android.widget.ArrayAdapter; import android.widget.Button; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import java.util.ArrayList; import java.util.Set; public class MainActivity extends AppCompatActivity { BluetoothAdapter myBluetooth; //etrafımızdaki cihazları taryıp ekliyeceğimiz bir dizi oluşturuyoruz //V1 private Set<BluetoothDevice> pairedDevices; //V2 Button toggle_button; //V1 Button pair_button; //V2 ListView pairedlist; //diğer calass da kullanmak üzere bir EXTRA_ADDRESS belirlenir //V2 public static String EXTRA_ADDRESS= "device_address"; //bir sonraki javada kullanmak üzere adres belirlenir //V3 ArrayAdapter<String> adapter; //V3 @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); myBluetooth=BluetoothAdapter.getDefaultAdapter();//bu kod cihazımızın bluetooth özelliği olup olmadığını göstericek //V1 toggle_button=(Button) findViewById(R.id.button_toggle); //bu butona basılınca bluetooth durumuna göre aktif/pasif durumuna getiricez //V1 pair_button=(Button) findViewById(R.id.button_pair); //V2 pairedlist=(ListView) findViewById(R.id.device_list); //V2 toggle_button.setOnClickListener(new View.OnClickListener() { //V1 @Override public void onClick(View v) { toggleBluetooth(); //method oluşturuldu //V1 } }); pair_button.setOnClickListener(new View.OnClickListener() { //V2 @Override public void onClick(View v) { //V2 listdevice(); //V2 } }); } private void listdevice() { //V2 pairedDevices = myBluetooth.getBondedDevices();//eşleşmiş cihazları pairedDevices içine attık //V2 ArrayList list = new ArrayList(); //V2 if (pairedDevices.size() > 0)//eşleşmiş cihazların boyutu sıfırdan büyükse //V2 { for (BluetoothDevice bt: pairedDevices) //V2 { list.add(bt.getName()+"\n"+ bt.getAddress()); //V2 } } else { Toast.makeText(getApplicationContext(),"Eşleşmiş Cihaz Yok!",Toast.LENGTH_SHORT).show(); //V2 } final ArrayAdapter adapter = new ArrayAdapter(this,android.R.layout.simple_list_item_1,list); //V2 pairedlist.setAdapter(adapter); //V2 pairedlist.setOnItemClickListener(selectDevices); //V3 } private void toggleBluetooth() { //yapmamız gereken işlemi bluetooth özelliğinin açık olup olmadığını tespid ederek yapıcaz //V1 if (myBluetooth==null){ Toast.makeText(getApplicationContext(), "Bluetooth Cihazı Yok!",Toast.LENGTH_SHORT).show(); //V1 } if (!myBluetooth.isEnabled()) { Intent enableBTIntent= new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivity(enableBTIntent); //burada bluetooth açma isteği gönderilmiş olacak //V1 } if (myBluetooth.isEnabled()) { myBluetooth.disable(); } } public AdapterView.OnItemClickListener selectDevices = new AdapterView.OnItemClickListener() { //V3 @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { //V3 String info = ((TextView) view).getText().toString(); //V3 String address = info.substring(info.length()-17); //V3 //yeni bir activity başlatmak için bir Intent tanımlanır Intent comintent = new Intent(MainActivity.this, CommunicationActivity.class); //V3 comintent.putExtra(EXTRA_ADDRESS, address); //V3 //herhangi bir veriyi bir layout dan diğer bir layouta aktarıyor startActivity(comintent); //V3 } }; }
CommunicationActivity.java Kodu
import android.app.ProgressDialog; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.bluetooth.BluetoothServerSocket; import android.bluetooth.BluetoothSocket; import android.os.AsyncTask; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.Toast; import java.io.IOException; import java.util.UUID; public class CommunicationActivity extends AppCompatActivity { String address= null; //V3 private ProgressDialog progress;//V3 BluetoothAdapter myBluetooth =null;//V3 BluetoothSocket btSocket =null;//V3 BluetoothDevice remoteDevice;//V3 BluetoothServerSocket mmServer;//V3 private boolean isBtConnected = false;//V3 static final UUID myUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");//V3 //https://stackoverflow.com/questions/16265504/uuid-bluetooth-and-android-devices //https://stackoverflow.com/questions/5088474/how-can-i-get-the-uuid-of-my-android-phone-in-an-application @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_communication); new BTbaglan().execute(); //V3 } private void Disconnect(){ //Thread Kodları if (btSocket != null) //Thread Kodları { try { //Thread Kodları btSocket.close(); //Thread Kodları }catch (IOException e){ //Thread Kodları //msg("Error"); //Thread Kodları } } finish(); //Thread Kodları } //Thread Kodları @Override public void onBackPressed() { //Thread Kodları super.onBackPressed(); //Thread Kodları Disconnect(); //Thread Kodları } //Thread Kodları private class BTbaglan extends AsyncTask<Void, Void, Void> { //Thread Kodları private boolean ConnectSuccess = true; //Thread Kodları @Override protected void onPreExecute() { //önceki yapması gereken işlem //burada bağlanıyor //Thread Kodları progress = ProgressDialog.show(CommunicationActivity.this, "Baglanıyor...", "Lütfen Bekleyin"); //Thread Kodları } //Thread Kodları // https://gelecegiyazanlar.turkcell.com.tr/konu/android/egitim/android-301/asynctask @Override protected Void doInBackground(Void... devices) { //sürekli arkada devam eden işlem //Thread Kodları try { if (btSocket == null || !isBtConnected) { //Thread Kodları myBluetooth = BluetoothAdapter.getDefaultAdapter(); //Thread Kodları BluetoothDevice cihaz = myBluetooth.getRemoteDevice(address); //Thread Kodları btSocket = cihaz.createInsecureRfcommSocketToServiceRecord(myUUID); //Thread Kodları BluetoothAdapter.getDefaultAdapter().cancelDiscovery(); //Thread Kodları btSocket.connect(); //Thread Kodları } } catch (IOException e) { //Thread Kodları ConnectSuccess = false; //Thread Kodları } return null; //Thread Kodları } //Thread Kodları @Override protected void onPostExecute(Void result) { //daha sonra yapması gereken işlem //Thread Kodları super.onPostExecute(result); //Thread Kodları if (!ConnectSuccess) { //Thread Kodları // msg("Baglantı Hatası, Lütfen Tekrar Deneyin"); Toast.makeText(getApplicationContext(), "Bağlantı Hatası Tekrar Deneyin", Toast.LENGTH_SHORT).show(); //Thread Kodları finish(); //Thread Kodları } else { //Thread Kodları // msg("Baglantı Basarılı"); Toast.makeText(getApplicationContext(), "Bağlantı Başarılı", Toast.LENGTH_SHORT).show(); //Thread Kodları isBtConnected = true; //Thread Kodları } progress.dismiss(); //Thread Kodları } //Thread Kodları } //Thread Kodları }
activty_main.xml Kodu
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".MainActivity"> <Button android:id="@+id/button_toggle" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:layout_marginRight="10dp" android:layout_marginLeft="10dp" android:padding="10dp" android:background="@android:color/holo_blue_light" android:text="Bluetooth On/Off" android:layout_alignParentTop="true"/> <Button android:id="@+id/button_pair" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="30dp" android:layout_marginRight="10dp" android:layout_marginLeft="10dp" android:padding="5dp" android:background="@android:color/holo_green_light" android:text="Bluetooth Cihazları Listele" android:layout_below="@id/button_toggle" android:gravity="center"/> <ListView android:id="@+id/device_list" android:layout_marginTop="30dp" android:layout_marginRight="10dp" android:layout_marginLeft="10dp" android:padding="5dp" android:layout_below="@id/button_pair" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginBottom="10dp"/> </RelativeLayout>
activty_communication.xml Kodu
<?xml version="1.0" encoding="utf-8"?> <android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" tools:context=".CommunicationActivity"> </android.support.constraint.ConstraintLayout>