Android:让蓝牙在其他Activiy中工作

时间:2015-04-28 06:56:55

标签: android android-activity bluetooth connection

我正在尝试连接(通过listview的onclick方法列出所有可用的蓝牙设备)到我的Class Bluetooth中的蓝牙设备。该类启动了intentservice BluetoothService,在那里我创建了一个BluetoothSocket并连接到Device。 连接工作后,我想去我的MainActivity,而我的连接打开,我想发送蓝牙消息。但是BluetoothConnection总是断开连接......

BLUETOOTH.JAVA

    public class Bluetooth extends ActionBarActivity {
    ArrayList arrayList1;
    ListView lv;
    ArrayAdapter<String> arrayAdapter;
    MainActivity ma = new MainActivity();
    BroadcastReceiver mReceiver;
    static final String TAG = "Bluetooth";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.popup);
        Intent intent = getIntent();
        arrayList1=intent.getStringArrayListExtra("values");
        lv= (ListView) findViewById(R.id.listView);
        getSurroundingDevicesandConnect();

    }
    @Override
    protected void onStart(){
        super.onStart();

    }
    public void getSurroundingDevicesandConnect() {
        setContentView(R.layout.popup);

        ma.bluetooth.startDiscovery();
        if (ma.bluetooth.startDiscovery()) {
            System.out.println("discovery started");
            mReceiver = new BroadcastReceiver() {
                public void onReceive(Context context, Intent intent) {
                    String action = intent.getAction();

                    if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                        BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                        arrayAdapter.add(device.getName() + "\n" + device.getAddress());
                        System.out.println("while onreceive" + arrayList1);
                    } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                        Log.v(TAG, "Entered the Finished ");
                        ma.bluetooth.cancelDiscovery();

                    } else {
                        System.out.println("hoppala da funktioniert was nciht");
                    }
                }

            };

            IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
            registerReceiver(mReceiver, filter);
            System.out.println("wurde registriert...");
        }

        setListView();

    }
    public void setListView() {
        lv = (ListView) findViewById(R.id.listView);
        arrayAdapter = new ArrayAdapter<String>(
                this,
                android.R.layout.select_dialog_item,
                arrayList1
        );
        lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> arg0, View arg1, int position,
                                    long arg3) {
                // TODO Auto-generated method stub
                String devicehelper = arrayList1.get(position).toString();
                String[] device = devicehelper.split("\n");
                String deviceName = device[0];
                String deviceMAC = device[1];

                //TODO: das hier muss in service..
                Intent serviceIntent = new Intent();
                serviceIntent.setAction("jritter.stamer.bluetoothtest.BluetoothService");
                serviceIntent.putExtra("deviceMAC", deviceMAC);
                BluetoothService bts = new BluetoothService();
                bts.onHandleIntent(serviceIntent);

//                boolean connected = connectWithDeviceNow(deviceMAC);
//                if (connected) {
//                    System.out.println("Connected!");
//                    Toast.makeText(getApplicationContext(), "Connected", Toast.LENGTH_LONG).show();
//                } else {
//                    System.out.println("Connection Failure");
//                    Toast.makeText(getApplicationContext(), "Connection Failure", Toast.LENGTH_LONG).show();
//                }
//                //onRestart();
//                Toast.makeText(getApplicationContext(), "Mit Gerät " + deviceName + " verbunden", Toast.LENGTH_LONG);
            }
        });

        lv.setAdapter(arrayAdapter);


    }

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


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.bluetooth, menu);
        return true;
    }
    public void onDestroy(){
        super.onDestroy();
        unregisterReceiver(mReceiver);

    }

}

BLUETOOTHSERVICE.JAVA

public class BluetoothService extends IntentService {
MainActivity ma = new MainActivity();
BluetoothSocket btSocket = null;
ConnectedThread mConnectedThread;
public BluetoothService() {
    super("BluetoothService");
}

@Override
protected void onHandleIntent(Intent intent) {
    String MAC = intent.getStringExtra("deviceMAC");

    //   create device and set the MAC address
    BluetoothDevice device = ma.bluetooth.getRemoteDevice(MAC);//mydeviceaddress
    System.out.println("devicename: " + device + device.getName());
    ma.bluetooth.cancelDiscovery();
    try {
        btSocket = ma.createBluetoothSocket(device);
    } catch (IOException e) {
        System.out.println("socket creation failed");
    }
    // Establish the Bluetooth socket connection.
    try {
        btSocket.connect();
        System.out.println("mit geraet verbunden");


    } catch (IOException e) {
        System.out.println("geraet nicht in eichweite");
        try {
            btSocket.close();

        } catch (IOException e2) {
            System.out.println("Socket closing doesnt work!");
        }
    }
    mConnectedThread = new ConnectedThread(btSocket);
    mConnectedThread.setPriority(Thread.MAX_PRIORITY);
    mConnectedThread.start();
}
}

MAINACTIVITY.JAVA

public class MainActivity extends ActionBarActivity {
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
static final boolean D = true;
static final int REQUEST_ENABLE_BT = 2;
static final String TAG = "Bluetooth";
// String for MAC address
static String mydeviceaddress;
// SPP UUID service - this should work for most devices
static final UUID BTMODULEUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB");
VerticalSeekBar Master, Channel1, Channel2, Channel3, Channel4, Channel5, Channel6, FX1, FX2, FX3, FX4;
CheckBox MuteMaster, Mute1, Mute2, Mute3, Mute4, Mute5, Mute6;
Button connect;
TextView textView;
ArrayList arrayList;
Spinner effects;
List<String> spinnerArray =  new ArrayList<String>(Arrays.asList("no effect", "Hall A", "Hall B"));
VerticalSeekBar vsb;
private static long back_pressed;
//BroadcastReceiver mReceiver;
Intent intent;
//BluetoothService btservice;
ConnectedThread mConnectedThread;
@Override
protected void onCreate(final Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    initializeVariables();
    deviceSupportBluetooth();//?
    turnBluetoothOn();
    intent = getIntent();

}

@Override
public synchronized void onResume() {
    super.onResume();
    if (D) Log.e(TAG, "+ ON RESUME +");

    effectsConfig(effects);
    connect.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
    //do something...
    //connect bluetooth activity

            sendMessage(v);
        }


    });


    seekbarConfig(Master, "Master");
    seekbarConfig(Channel1, "Channel1");
    seekbarConfig(Channel2, "Channel2");
    seekbarConfig(Channel3, "Channel3");
    seekbarConfig(Channel4, "Channel4");
    seekbarConfig(Channel5, "Channel5");
    seekbarConfig(Channel6, "Channel6");
    muteConfig(MuteMaster);
    muteConfig(Mute1);
    muteConfig(Mute2);
    muteConfig(Mute3);
    muteConfig(Mute4);
    muteConfig(Mute5);
    muteConfig(Mute6);
}

//TODO: MCONNECTEDTHREAD
public void sendMessage(View view) {
    Intent intent = new Intent(this, Bluetooth.class);
    intent.putExtra("values", arrayList);
    startActivity(intent);

}


private void initializeVariables() {
    Master = (VerticalSeekBar) findViewById(R.id.Seekbar);
    Channel1 = (VerticalSeekBar) findViewById(R.id.Seekbar1);
    Channel2 = (VerticalSeekBar) findViewById(R.id.seekbar2);
    Channel3 = (VerticalSeekBar) findViewById(R.id.seekbar3);
    Channel4 = (VerticalSeekBar) findViewById(R.id.seekbar4);
    Channel5 = (VerticalSeekBar) findViewById(R.id.seekbar5);
    Channel6 = (VerticalSeekBar) findViewById(R.id.seekbar6);
    vsb = (VerticalSeekBar) findViewById(R.id.impulse2);
    textView = (TextView) findViewById(R.id.textView);
    MuteMaster = (CheckBox) findViewById(R.id.muteMaster);
    Mute1 = (CheckBox) findViewById(R.id.mute1);
    Mute2 = (CheckBox) findViewById(R.id.mute2);
    Mute3 = (CheckBox) findViewById(R.id.mute3);
    Mute4 = (CheckBox) findViewById(R.id.mute4);
    Mute5 = (CheckBox) findViewById(R.id.mute5);
    Mute6 = (CheckBox) findViewById(R.id.mute6);
    connect = (Button) findViewById(R.id.connect);
    effects = (Spinner) findViewById(R.id.spinner2);
    arrayList = new ArrayList();
}

//android...
@Override
public void onStart() {
    super.onStart();
    if (D) Log.e(TAG, "++ ON START ++");

}

@Override
public void onDestroy() {

    super.onDestroy();
    if (D) Log.e(TAG, "++ ON DESTROY ++");
}
protected void onStop() {
    Log.w(TAG, "App stopped");

    super.onStop();
}

public void onBackPressed(){
    onResume();

    if (back_pressed + 2000 > System.currentTimeMillis()) super.onBackPressed();
    else Toast.makeText(getBaseContext(), "Press once again to exit!", Toast.LENGTH_SHORT).show();
    back_pressed = System.currentTimeMillis();
}


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

@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();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
    super.onConfigurationChanged(newConfig);
}


// TODO GUI...
public void effectsConfig(Spinner spinner){
    ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            this, android.R.layout.simple_spinner_item, spinnerArray);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    Spinners abc = new Spinners();
    abc.setSpinner(spinner);
    abc.setmConnectedThread(mConnectedThread);
    spinner.setOnItemSelectedListener(abc);
}
public void muteConfig(CheckBox mute){
    Checkboxes abc = new Checkboxes();
    abc.setmConnectedThread(mConnectedThread);
    mute.setOnClickListener(abc);
}
public void seekbarConfig(VerticalSeekBar seekBar, final String fadername) {
    Seekbars abc = new Seekbars();
    abc.setFadername(fadername);
    abc.setmConnectedThread(mConnectedThread);
    seekBar.setOnSeekBarChangeListener(abc);
}

// TODO Bluetooth handling...
public BluetoothSocket createBluetoothSocket(BluetoothDevice device) throws IOException {
    return device.createInsecureRfcommSocketToServiceRecord(BTMODULEUUID);
//creates secure outgoing connecetion with BT device using UUID
}


public void deviceSupportBluetooth() {
    if (bluetooth == null) {
        Toast.makeText(this, "Your Device does not support Bluetooth", Toast.LENGTH_LONG).show();
        finish();
        return;

    }
}

public void turnBluetoothOn() {
    if (!bluetooth.isEnabled()) {
        Intent enableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
        startActivityForResult(enableIntent, REQUEST_ENABLE_BT);
        // Otherwise, setup the control session
    }
}
} 

CONNECTEDTHREAD.JAVA

class ConnectedThread extends Thread {
MainActivity ma = new MainActivity();
private final InputStream mmInStream;
private final OutputStream mmOutStream;
final int handlerState = 0; //used to identify handler message
Handler bluetoothIn;


//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[256];
    int bytes;
    // Keep looping to listen for received messages
    while (true) {
        try {
            bytes = mmInStream.read(buffer); //read bytes from input buffer
            String readMessage = new String(buffer, 0, bytes);
        // Send the obtained bytes to the UI Activity via handler
            bluetoothIn.obtainMessage(handlerState, bytes, -1, readMessage).sendToTarget();
        } catch (IOException e) {
            break;
        }
    }
}

//write method
public void write(String input) {
    byte[] msgBuffer = input.getBytes(); //converts entered String into    bytes
    try {
        mmOutStream.write(msgBuffer); //write bytes over BT connection         via outstream
    } catch (IOException e) {
   //if you cannot write, close the application

        Toast.makeText(ma.getBaseContext(), "Connection Failure",        Toast.LENGTH_LONG).show();
        ma.finish();
    }
}

}

1 个答案:

答案 0 :(得分:0)

您不希望使用IntentService。如果没有更多的工作要做,IntentService会自行关闭。这意味着只要您从onHandleIntent()返回,您的服务就会关闭。只需展开Service,然后将onHandleIntent()中的代码移至onStartCommand()即可。确保您从START_STICKY返回onHandleIntent()并确保您的代码在完成后停止Service

下一个问题是在几个课程中你这样做:

MainActivity ma = new MainActivity();

这很糟糕。您无法使用new实例化Android组件。只有Android框架可以实例化Android组件(ServiceActivityBroadcastReceiverContentProvider),因为框架需要设置正确的Context。如果您需要调用Activity中的方法,则需要引用(Android创建的)Activity,或者您需要创建方法static

你的代码很乱:-(你应该管理Service中的所有蓝牙内容,而不是部分地在Service和部分Activity中分发逻辑。你的课程这些都是相互依赖的。这是糟糕的设计并导致你出现问题。你需要在ServiceActivity之间创建一个清晰,干净的界面。

查看你的logcat,看看有什么讨厌的异常被抛出。这很可能是导致“蓝牙断开连接”的原因