Android蓝牙服务

时间:2015-01-04 08:43:12

标签: java android

我制作了一个程序,可以将蓝牙连接到我的设备并从我的设备获取字节。 但该程序无法在后台运行。

我只想在后台获取字节。

我创建了另一个扩展Service并尝试让我的程序运行的类。

public class NickyService extends Service  {
    public int onStartCommand(Intent intent, int flags, int startId) {
        super.onStartCommand(intent,flags,startId);

        //Wrong code
        MainActivity a1 = new MainActivity();

        return START_NOT_STICKY;
    }
}

我不知道解决这个问题。 我该如何解决这个大问题?

以下代码是对的! 它可以获取字节并连接到设备,但不能在后台运行!!

MainActivity.java

package com.example.bluetooth10;

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

import org.apache.http.util.ByteArrayBuffer;

import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.bluetooth.BluetoothSocket;
import android.content.Intent;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.os.Vibrator;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuItem;
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 ActionBarActivity {

    // textview for connection status
    ListView pairedListView;
    private ArrayAdapter<String> mPairedDevicesArrayAdapter;
    TextView sensorView0, title_paired_devices;
    String paired = "";
    Handler bluetoothIn;
    private TextView connecting_str;
    private TextView textView1;

    final int handlerState = 0;      // used to identify handler message
    private BluetoothAdapter btAdapter = null;
    private BluetoothSocket btSocket = null;
    private ByteArrayBuffer baf1 = new ByteArrayBuffer(32);
    String path = Environment.getExternalStorageDirectory().toString();

    private ConnectedThread mConnectedThread;  
    private static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); // SPP UUID service - this should work for most devices
    private static String address;   // String for MAC address


    protected void onHandleIntent(Intent workIntent) {
        // Gets data from the incoming Intent
        String dataString = workIntent.getDataString();
        // Do work here, based on the contents of dataString
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        textView1 = (TextView) findViewById(R.id.textView1); 
        title_paired_devices = (TextView) findViewById(R.id.title_paired_devices);
        ...

        bluetoothIn = new Handler() {
            public void handleMessage(android.os.Message msg) {
                connecting_str.setText("Connection!!");
                byte[] readBuf = (byte[]) msg.obj;  // obj = buffer from connect thread
                for (int i=0; i<msg.arg1; i++) {
                    baf1.append((byte)readBuf[i]);
                    if (baf1.length()>1){
                        String str1 = String.format("%02X",(byte)baf1.byteAt(baf1.length()-2));
                        String str2 = String.format("%02X",(byte)baf1.byteAt(baf1.length()-1));
                        if (str1.equals("01") && str2.equals("FF")){
                            int tmpb = (byte)baf1.byteAt(13);
                            baf1.clear();
                        }
                    }
                }
            }
            int toInt( byte[] bytes ) {
                int result = 0;
                for (int i=0; i<bytes.length; i++) {
                  result = ( result << 8 ) - Byte.MIN_VALUE + (int) bytes[i];
                }
                return result;
            }
        };

        btAdapter = BluetoothAdapter.getDefaultAdapter();       // get Bluetooth adapter
        checkBTState();
    }


    private BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException
    {
        return  device.createRfcommSocketToServiceRecord(BTMODULEUUID);
        //creates secure outgoing connecetion with BT device using UUID
    }

    public void onResume() {
        super.onResume(); 
        checkBTState();
        btAdapter = BluetoothAdapter.getDefaultAdapter();
        Set<BluetoothDevice> pairedDevices = btAdapter.getBondedDevices();
        if (pairedDevices.size() > 0) {
            findViewById(R.id.title_paired_devices).setVisibility(View.VISIBLE);//make title viewable
            for (BluetoothDevice device : pairedDevices) {
                if (!paired.equals("")) paired = paired + ",";
                paired = paired + device.getName() + ";" + device.getAddress();
            }
        } else {
            paired = "no devices paired";
        }       

        String str0[] = paired.split(","); 
        String str1 = str0[0]; //pairedListView.getItemAtPosition(0).toString(); //Get MAC address from DeviceListActivity
        String str2[] = str1.split(";");
        address = str2[1];    //Get the MAC address from the DeviceListActivty via EXTRA        

        BluetoothDevice device = btAdapter.getRemoteDevice(address); //create device and set the MAC address 
        try {
            btSocket = createBluetoothSocket(device);
        } catch (IOException e) {
            Toast.makeText(getBaseContext(), "Socket creation failed", Toast.LENGTH_LONG).show();
        }    
        try {
            btSocket.connect();
        } catch (IOException e) {
            try {
                btSocket.close();
            } catch (IOException e2) {  }
        }    
        mConnectedThread = new ConnectedThread(btSocket);
        mConnectedThread.start();    
    }

    public void onPause() {
        super.onPause();     
        try {           
            btSocket.close(); //Don't leave Bluetooth sockets open when leaving activity
        } catch (IOException e2) {  }
    }

    private void checkBTState() {
        btAdapter = BluetoothAdapter.getDefaultAdapter(); // CHECK THIS OUT THAT IT WORKS!!!
        if(btAdapter==null) {
            Toast.makeText(getBaseContext(), "Device does not support Bluetooth", Toast.LENGTH_SHORT).show();
            finish();
        } else {
            if (!btAdapter.isEnabled()) {
                //Prompt user to turn on Bluetooth
                Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(enableBtIntent, 1);
            }
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    // ***********************************************************
    //  create new class for connect thread
    // ***********************************************************
    private class ConnectedThread extends Thread {
        private final InputStream mmInStream;
        private final OutputStream mmOutStream;

        //creation of the connect thread
        public ConnectedThread(BluetoothSocket socket) {
            InputStream tmpIn = null;
            OutputStream tmpOut = null;
            try {
                //Create I/O streams for connection
                tmpIn = socket.getInputStream();
                tmpOut = socket.getOutputStream();
            } catch (IOException e) { }
            mmInStream = tmpIn;
            mmOutStream = tmpOut;
        }

        public void run() {         
            byte[] buffer = new byte[40];  //The arduino is sending a small amount of data so a large buffer is not needed
            int bytes;
            // Keep looping to listen for received messages
            while (true) {
                try {
                    bytes = mmInStream.read(buffer);   //read bytes from input buffer
                    bluetoothIn.obtainMessage(handlerState, bytes, -1, buffer).sendToTarget();  //Send message to handler
                } catch (IOException e) {
                        break;
                }
            }
        }           
    }    
}

0 个答案:

没有答案
相关问题