ANDROID -- Bluetooth

AndroidManifest.xml 添加权限:

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

Main.xml 布局:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/t"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button
        android:id="@+id/button1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button" />

    <Button
        android:id="@+id/button2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Button" />





    <ImageView
        android:id="@+id/imageView1"
        android:layout_width="wrap_content"
        android:layout_height="65dp"
        android:src="@drawable/ic_launcher" />

</LinearLayout>

MainActivity :

package com.zxl;

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.provider.MediaStore.Images;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
	public TextView statuUpdate;
	public Button connect;
	public Button disconnect;
	public ImageView logo;
	private BluetoothAdapter btAdapter;
	
	 BroadcastReceiver bluetoothState=new BroadcastReceiver(){
		 public void onReceive(Context context,Intent intent){
			 String prevStateExtra=BluetoothAdapter.EXTRA_PREVIOUS_STATE;
			 String stateExtra=BluetoothAdapter.EXTRA_STATE;
			 int state=intent.getIntExtra(stateExtra, -1);
			 //int previouState=intent.getIntExtra(prevStateExtra, -1);
			 String toastText="";
			 switch (state) {
			case (BluetoothAdapter.STATE_TURNING_ON):
				toastText="Bluetooth turning on";
			Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();	
				break;
			case (BluetoothAdapter.STATE_ON):
				toastText="Bluetooth on";
			Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();	
				setupUI();
				break;
			case (BluetoothAdapter.STATE_TURNING_OFF):
				toastText="Bluetooth turning off";
			Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();	
			break;
			case (BluetoothAdapter.STATE_OFF):
				toastText="Bluetooth off";
			Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();	
				break;
			default:
				break;
			}
		 }
	 };
	
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setupUI();
    }
	
	private void setupUI(){
		//get refernces
		final TextView statuUpdate=(TextView)findViewById(R.id.t);
		final Button connect=(Button)findViewById(R.id.button1);
		final Button disconnect=(Button)findViewById(R.id.button2);
		final ImageView logo=(ImageView)findViewById(R.id.imageView1);
		//set display view
		
		disconnect.setVisibility(View.GONE);
		logo.setVisibility(View.GONE);
		btAdapter=BluetoothAdapter.getDefaultAdapter();
		if(btAdapter.isEnabled()){
			String address=btAdapter.getAddress();
			String name=btAdapter.getName();
			String statusText=name+":"+address;
			statuUpdate.setText(statusText);
			disconnect.setVisibility(View.VISIBLE);
			logo.setVisibility(View.VISIBLE);
			connect.setVisibility(View.GONE);
		}else{
			connect.setVisibility(View.GONE);
			statuUpdate.setText("bluetooth is not on");
		}
		connect.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				String actionStateChanged=BluetoothAdapter.ACTION_STATE_CHANGED;
				String actionRequesEnableString=BluetoothAdapter.ACTION_REQUEST_ENABLE;
				IntentFilter filter=new IntentFilter(actionStateChanged);
				registerReceiver(bluetoothState, filter);
				startActivityForResult(new Intent(actionRequesEnableString), 0);
				
			}
		}); //end connect onclicklistener
		
		disconnect.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				btAdapter.disable();
				disconnect.setVisibility(View.GONE);
				logo.setVisibility(View.GONE);
				connect.setVisibility(View.VISIBLE);
				statuUpdate.setText("Bluetooth OFF");
			}
		});
		
	}
	
}


改写:

package com.zxl;

import java.util.Set;

import android.R.integer;
import android.R.string;
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.content.SharedPreferences;
import android.os.Bundle;
import android.provider.MediaStore.Images;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
	public TextView statuUpdate;
	public Button connect;
	public Button disconnect;
	public ImageView logo;
	private BluetoothAdapter btAdapter;
	
	protected static final int DISCOVERY_REQUEST=1;
	public String toastText;
	private BluetoothDevice remoteDevice;
	
	//create a broadcastreceiver to receive state changes
	 BroadcastReceiver bluetoothState=new BroadcastReceiver(){
		 public void onReceive(Context context,Intent intent){
			 String prevStateExtra=BluetoothAdapter.EXTRA_PREVIOUS_STATE;
			 String stateExtra=BluetoothAdapter.EXTRA_STATE;
			 int state=intent.getIntExtra(stateExtra, -1);
			 //int previouState=intent.getIntExtra(prevStateExtra, -1);
			 //String toastText="";
			 switch (state) {
			case (BluetoothAdapter.STATE_TURNING_ON):
				toastText="Bluetooth turning on";
			Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();	
				break;
			case (BluetoothAdapter.STATE_ON):
				toastText="Bluetooth on";
			Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();	
				setupUI();
				break;
			case (BluetoothAdapter.STATE_TURNING_OFF):
				toastText="Bluetooth turning off";
			Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();	
			break;
			case (BluetoothAdapter.STATE_OFF):
				toastText="Bluetooth off";
			Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();	
				break;
			default:
				break;
			}
		 }
	 };
	
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        setupUI();
    }
	
	private void setupUI(){
		//get refernces
		final TextView statuUpdate=(TextView)findViewById(R.id.t);
		final Button connect=(Button)findViewById(R.id.button1);
		final Button disconnect=(Button)findViewById(R.id.button2);
		final ImageView logo=(ImageView)findViewById(R.id.imageView1);
		//set display view
		
		disconnect.setVisibility(View.GONE);
		logo.setVisibility(View.GONE);
		btAdapter=BluetoothAdapter.getDefaultAdapter();
		if(btAdapter.isEnabled()){
			String address=btAdapter.getAddress();
			String name=btAdapter.getName();
			String statusText=name+":"+address;
			statuUpdate.setText(statusText);
			disconnect.setVisibility(View.VISIBLE);
			logo.setVisibility(View.VISIBLE);
			connect.setVisibility(View.GONE);
		}else{
			connect.setVisibility(View.GONE);
			statuUpdate.setText("bluetooth is not on");
		}
		connect.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				/*String actionStateChanged=BluetoothAdapter.ACTION_STATE_CHANGED;
				String actionRequesEnableString=BluetoothAdapter.ACTION_REQUEST_ENABLE;
				IntentFilter filter=new IntentFilter(actionStateChanged);
				registerReceiver(bluetoothState, filter);
				startActivityForResult(new Intent(actionRequesEnableString), 0);
				*/
				
				//register for discovery ecents
				String scanModeChanged=BluetoothAdapter.ACTION_SCAN_MODE_CHANGED;
				String beDiscoveroble=BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE;
				IntentFilter filter=new IntentFilter(scanModeChanged);
				registerReceiver(bluetoothState, filter);
				startActivityForResult(new Intent(beDiscoveroble), DISCOVERY_REQUEST);
				
			}
		}); //end connect onclicklistener
		
		disconnect.setOnClickListener(new OnClickListener() {
			
			public void onClick(View v) {
				// TODO Auto-generated method stub
				btAdapter.disable();
				disconnect.setVisibility(View.GONE);
				logo.setVisibility(View.GONE);
				connect.setVisibility(View.VISIBLE);
				statuUpdate.setText("Bluetooth OFF");
			}
		});
		
	}
	
	protected void onActivityResult(int requestCode,int resultCode,Intent data){
		if(requestCode==DISCOVERY_REQUEST){
			Toast.makeText(MainActivity.this, "discovery in progress",Toast.LENGTH_SHORT).show();
			setupUI();
			findDevices();
		}
	}
	private void findDevices(){
		String lastUserRemoteDevice=getlastUserRemoteDevice();
		if(lastUserRemoteDevice!=null){
			toastText="checking for know paired devixes namely:"+lastUserRemoteDevice;
			Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
			//see if this device is in a list of currently visible(?) 。paired devices
			Set<BluetoothDevice> pairedDevices=btAdapter.getBondedDevices();
			for(BluetoothDevice paireDevice : pairedDevices){
				if(paireDevice.getAddress().equals(lastUserRemoteDevice)){
					toastText="found device:"+paireDevice.getName()+"@"+lastUserRemoteDevice;
					Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
					remoteDevice=paireDevice;
				}
				
			}
			
		}
		if(remoteDevice==null){
			toastText="starting discovery for remote devixes...";
			Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
			registerReceiver(discoveryResult, new IntentFilter(BluetoothDevice.ACTION_FOUND));
		}
	}
	
	BroadcastReceiver discoveryResult=new BroadcastReceiver() {
		
		@Override
		public void onReceive(Context context, Intent intent) {
			// TODO Auto-generated method stub
			String remoteDeciceName=intent.getStringExtra(BluetoothDevice.EXTRA_NAME);
			BluetoothDevice remoteDevice;
			remoteDevice=intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
			toastText="discovered:"+remoteDeciceName;
			Toast.makeText(MainActivity.this, toastText, Toast.LENGTH_SHORT).show();
		}
	};
	
	private String getlastUserRemoteDevice(){
		SharedPreferences prefs=getPreferences(MODE_PRIVATE);
		String result=prefs.getString("LAST_REMOTE_DEVICE_ADDRESS", null);
		return result;
	}

}









  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值