package com.example.bluetooth;

import java.io.IOException;
import java.io.OutputStream;
import java.util.UUID;

import android.os.Bundle;
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.content.IntentFilter;
import android.util.Log;
import android.view.Gravity;
import android.view.Menu;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {

 private ArrayAdapter<String> adapter;
 private BluetoothSocket btSocket;
 private BluetoothAdapter mBluetoothAdapter;
 Spinner spinner1;
 Button btn1;

 @Override
 protected void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.activity_main);

  IntentFilter intent=new IntentFilter();
     intent.addAction(BluetoothDevice.ACTION_FOUND);
     intent.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
     intent.addAction(BluetoothAdapter.ACTION_SCAN_MODE_CHANGED);
     intent.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
     registerReceiver(searchDevices, intent);

     adapter = new ArrayAdapter<String>(MainActivity.this,android.R.layout.simple_spinner_item);
  onBlueToothSearch();

  spinner1=(Spinner)findViewById(R.id.spinner1); 
  spinner1.setOnItemSelectedListener(new OnItemSelectedListener(){
   @Override
   public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3)
   {
    String str=spinner1.getSelectedItem().toString();
    EditText et=(EditText)findViewById(R.id.editText1);
    et.append(str);
    String[] var=str.split(";");

    connect(mBluetoothAdapter.getRemoteDevice(var[1]));

   }

   @Override
   public void onNothingSelected(AdapterView<?> arg0) {
    // TODO Auto-generated method stub

   }



  });


  btn1=(Button)findViewById(R.id.button1);
  btn1.setOnClickListener(new View.OnClickListener(){

   @Override
   public void onClick(View arg0) {
    EditText et=(EditText)findViewById(R.id.editText2);
    String str=et.getText().toString();
    try
    {
     OutputStream dos=btSocket.getOutputStream(); 
     dos.write(str.getBytes());
     dos.flush();
    }
    catch(Exception e)
    {


    }

   }



  });


 }

 //蓝牙操作
 public void onBlueToothSearch()
 {

  mBluetoothAdapter=BluetoothAdapter.getDefaultAdapter();
  if (mBluetoothAdapter==null)
  {
    Toast imagetoast=Toast.makeText(getApplicationContext(), "设备不支持蓝牙", Toast.LENGTH_LONG);  
    imagetoast.setGravity(Gravity.TOP|Gravity.CENTER, 0, 100); 

     ImageView imageView= new ImageView(getApplicationContext());   //创建图像      
     imageView.setImageResource(R.drawable.ic_launcher);            //设置图像
     LinearLayout toastView = (LinearLayout) imagetoast.getView();  //对toast设置布局
     toastView.setOrientation(LinearLayout.VERTICAL);   
     toastView.addView(imageView, 0);   

     imagetoast.show();
  }
  else if (!mBluetoothAdapter.isEnabled())
  {
    Intent intent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);    
    startActivityForResult(intent, 0x1);        
    mBluetoothAdapter.enable(); 
    mBluetoothAdapter.startDiscovery(); 
    super.onResume();
  }
  else 
  { 
   mBluetoothAdapter.cancelDiscovery();
   mBluetoothAdapter.startDiscovery();   
   super.onResume();
  }

 };

        //触发器,扫描到蓝牙设备后执行,更新spinner
 private BroadcastReceiver searchDevices = new BroadcastReceiver() {

  public void onReceive(Context context, Intent intent) {  

   String action = intent.getAction();
            Bundle b = intent.getExtras();  
            String str;
            Toast imagetoast;
   if (BluetoothDevice.ACTION_FOUND.equals(action))
   {
      BluetoothDevice device=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);

      switch (device.getBondState())
      {
      //未配对 
       case BluetoothDevice.BOND_NONE:     
        str="未配对:"+device.getName()+";"+device.getAddress();    
        break;
       case BluetoothDevice.BOND_BONDED:
        str="已配对:"+device.getName()+";"+device.getAddress();
        break;
       default:
        str="正配对:"+device.getName()+";"+device.getAddress();
        break;     
      }
      if (adapter.getPosition(str)==-1)
      adapter.add(str);

   };         

   Spinner spinner1=(Spinner)findViewById(R.id.spinner1);    

            adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);   
            spinner1.setAdapter(adapter);


         }
    };

    private void connect(BluetoothDevice btDev) {  
        final UUID SPP_UUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); 
        UUID uuid = SPP_UUID;   
        try {   
            btSocket = btDev.createRfcommSocketToServiceRecord(uuid);   
            Log.d("BlueToothTestActivity", "开始连接...");   
            btSocket.connect();   
        } catch (IOException e) {   
            // TODO Auto-generated catch block   
            e.printStackTrace();   
        }   
    }  




 @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;
 }

}

 

 

FROM:http://7478265.blog.51cto.com/7468265/1261097

創作者介紹

資訊園

shadow 發表在 痞客邦 PIXNET 留言(0) 人氣()