这是对上一篇文件进行优化,加入了服务service

主界面代码:

import java.util.ArrayList;
import java.util.List;

import net.intelink.express.SZYDPDA.R;
import net.intelink.express.adapter.CommonAdapter;
import net.intelink.express.adapter.ViewHolder;
import net.intelink.express.service.MyBlueService;
import net.intelink.lib.util.UIUtils;
import android.app.ProgressDialog;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnKeyListener;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ListView;
import android.widget.TextView;

public class BlueToothActivity extends BaseActivity implements OnClickListener{

	BluetoothAdapter adapter;
	private TextView tv_weight;

	private List<String> devices;
	private List<BluetoothDevice> deviceList;

	private ListView list;
	private ProgressDialog dialog = null;
	
	private ProgressDialog isingDialog=null;

	private CommonAdapter<String> commonAdapter;
	
	private Button btn_search,btn_disconnect;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		setContentView(R.layout.activity_blue_tooth);

		list = (ListView) findViewById(R.id.list);
		tv_weight = (TextView) findViewById(R.id.tv_weight);
		devices = new ArrayList<String>();
		deviceList = new ArrayList<BluetoothDevice>();
		
		btn_search=(Button) findViewById(R.id.btn_search);		
		btn_disconnect=(Button) findViewById(R.id.btn_disconnect);
		
		btn_search.setOnClickListener(this);
		btn_disconnect.setOnClickListener(this);
		
		search();
	}

	private void search() {
		adapter = BluetoothAdapter.getDefaultAdapter();
		if (!adapter.isEnabled()) {
			adapter.enable();
		}
		// Intent enable = new
		// Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
		// enable.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 3600);
		// startActivity(enable);

		 IntentFilter filter = new IntentFilter();
		 filter.addAction(BluetoothDevice.ACTION_FOUND);
		 filter.addAction(MyBlueService.ACTION_NAME);
		 registerReceiver(receiver, filter);
		
//		adapter.startDiscovery();
//		dialog = ProgressDialog.show(this, "", "正在搜索");
//		dialog.setCancelable(false);
//		dialog.setOnKeyListener(onKeyListener);

		list.setOnItemClickListener(new AdapterView.OnItemClickListener() {

			@Override
			public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
				BluetoothDevice device = deviceList.get(position);
				mApplication.startBlueToothService(device);
				
				isingDialog = ProgressDialog.show(BlueToothActivity.this, "", "连接中..");
				isingDialog.setCancelable(false);
				isingDialog.setOnKeyListener(onKeyListener);
			}
		});
		
		commonAdapter=new CommonAdapter<String>(this, devices, R.layout.activity_blue_tooth_item) {

			@Override
			public void convert(ViewHolder holder, String item) {
				holder.setText(R.id.tv_address, item);
			}
		};
		list.setAdapter(commonAdapter);
		
	}

	private BroadcastReceiver receiver = new BroadcastReceiver() {

		@Override
		public void onReceive(Context context, Intent intent) {
			String action = intent.getAction();
			// 搜索设备时,取得设备的MAC地址
			if (BluetoothDevice.ACTION_FOUND.equals(action)) {
				final BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
				if (isLock(device)) {
					commonAdapter.add("设备:"+device.getName());
					deviceList.add(device);
				}
				showDevices();
			}
			
			if(MyBlueService.ACTION_NAME.equals(action)){
				if(isingDialog!=null){
					isingDialog.dismiss();
					isingDialog=null;
					UIUtils.makeCustomToast(BlueToothActivity.this, "蓝牙连接成功..");
				}
				String weight=intent.getStringExtra("weight");
				tv_weight.setText(weight);
			}else if(MyBlueService.ERROR.equals(action)){
				if(isingDialog!=null){
					isingDialog.dismiss();
				}
				UIUtils.makeCustomToast(BlueToothActivity.this, "蓝牙连接失败..");
			}
		}
	};

	private void showDevices() {
		if(devices!=null && devices.size()>0){
			commonAdapter.notifyDataSetChanged();
		}
	}

	private boolean isLock(BluetoothDevice device) {
		boolean isSingleDevice = devices.indexOf(device.getName()) == -1;
		return isSingleDevice;
	}

	protected void onDestroy() {
		unregisterReceiver(receiver);
		super.onDestroy();
	};

	private OnKeyListener onKeyListener = new OnKeyListener() {
		@Override
		public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
			if (keyCode == KeyEvent.KEYCODE_BACK && event.getAction() == KeyEvent.ACTION_DOWN) {
				if (dialog != null) {
					dialog.dismiss();
				}
				if(isingDialog!=null){
					isingDialog.dismiss();
				}
				if (adapter.isDiscovering()) {
					adapter.cancelDiscovery();
				}
			}
			return false;
		}
	};

	@Override
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case F5:
			blueSearch();
			break;
		case F6:
			disconnect();
		}
		return super.onKeyDown(keyCode, event);
	}

	@Override
	public void onClick(View view) {
		switch (view.getId()) {
		case R.id.btn_search:
			blueSearch();
			break;
		case R.id.btn_disconnect:
			disconnect();
			break;
		}
	}
	
	private void blueSearch(){
		adapter = BluetoothAdapter.getDefaultAdapter();
		if (!adapter.isEnabled()) {
			adapter.enable();
		}
		
		if(!adapter.isDiscovering()){
			adapter.startDiscovery();
			dialog = ProgressDialog.show(this, "", "正在搜索");
			dialog.setCancelable(false);
			dialog.setOnKeyListener(onKeyListener);
		}
	}
	
	private void disconnect(){
		adapter.disable();
		UIUtils.makeCustomToast(BlueToothActivity.this, "蓝牙已经关闭..");
		tv_weight.setText("0.00");
	}
}
APP应用调用代码:

public void startBlueToothService(BluetoothDevice device){
		MyBlueService service=new MyBlueService(getApplicationContext(),device);
		service.connect();
	}
服务端执行代码:

import java.io.InputStream;
import java.util.Arrays;
import java.util.UUID;

import android.app.Service;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Context;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;

public class MyBlueService extends Service{
	
	private BluetoothDevice device;
	private Context context;
	private StringBuffer sBuffer=new StringBuffer();
	public static String ACTION_NAME="MyBlueService";
	public static String ERROR="ERROR";
	public static String CLOSE="CLOSE";
	
//	private static MyBlueService instance=new MyBlueService();
//	
//	private MyBlueService() {}
//	
//	public static MyBlueService getInstance(){
//		return instance;
//	}
	
	public MyBlueService() {}
	
	public MyBlueService(Context context,BluetoothDevice device) {
		this.device=device;
		this.context=context;
	}
	
	private BluetoothSocket bluetoothSocket = null;
	
	private InputStream inputStream = null;
	private boolean mIsRunning = false;
	
	private Intent intent=new Intent(ACTION_NAME);
	
	@Override
	public IBinder onBind(Intent intent) {
		return null;
	}
	
	public void connect(){
		intent=new Intent(ACTION_NAME);
		if(device!=null){
			connectBlueTooth(device);
		}
	}
	
	private void connectBlueTooth(final BluetoothDevice device) {
		
		new Thread(new Runnable() {

			@Override
			public void run() {
				try {
					UUID uuid = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
					bluetoothSocket = device.createInsecureRfcommSocketToServiceRecord(uuid);
					new Thread(new Runnable() {

						@Override
						public void run() {
							try {
								if (bluetoothSocket != null) {
									bluetoothSocket.connect();

									inputStream = bluetoothSocket.getInputStream();
									mIsRunning = true;
									
									while (mIsRunning) {
										byte[] buffer = new byte[16];
										if (inputStream != null && inputStream.read(buffer) > 0 && mIsRunning) {
											
											String result = String.valueOf(new String(buffer)).trim().replace("\n", "").replace("\r", "");
											if (result != null && !"".equals(result)) {
												sBuffer.append(result);
												
												String myResult=sBuffer.toString();
												System.out.println(myResult);
												if(myResult.contains("wn") && myResult.contains("kg")){
													if (myResult.indexOf("wn") < myResult.lastIndexOf("kg")) {
														if(!myResult.contains("kgwn")){
															Log.i("www",myResult.substring(myResult.indexOf("wn") + 2, myResult.lastIndexOf("kg")));
															intent.putExtra("weight", myResult.substring(myResult.indexOf("wn") + 2, myResult.lastIndexOf("kg")));
															context.sendBroadcast(intent);
														}
													}
												}
												sBuffer.delete(0,  myResult.lastIndexOf("kg")+2);
											}
											
											Log.i("OIJOI", new String(buffer));
											Arrays.fill(buffer, (byte) 0);
										}
									}
								}

							} catch (Exception e) {
								e.printStackTrace();
								context.sendBroadcast(new Intent("ERROR"));
							}

						}
					}).start();

				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}).start();
	}

	
	
}




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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值