2013-02-27 1 views
0

나는 안드로이드에서 블루투스 응용 프로그램을 개발 중입니다. 먼저 사용 가능한 블루투스 장치를 스캔 한 다음 연결해야합니다. 연결이 끝나면 데이터를 보내야합니다. 나는 연결까지 했어. 그러나 연결된 장치에 데이터를 보내는 공통 기능을 찾지 못했습니다. 내 응용 프로그램에서이 함수를 여러 번 사용해야합니다. 다음은 연결에 대한 내 코드는 응용 프로그램의 백그라운드에서 실행하고 모든 활동에서 해당 액세스 할 수 있도록, 백그라운드 서비스로 블루투스를 사용할 필요가 ... 도와일반적인 블루투스 기능은 안드로이드에서 BluetoothDevice를 사용하여 데이터를 전송합니다.

import java.io.File; 
import java.io.FileOutputStream; 
import java.io.IOException; 
import java.io.OutputStream; 
import java.text.SimpleDateFormat; 
import java.util.Calendar; 
import java.util.Date; 
import java.util.Random; 
import java.util.Set; 
import java.util.TimeZone; 
import java.util.UUID; 

import android.annotation.SuppressLint; 
import android.app.Activity; 
import android.app.AlertDialog; 
import android.app.Dialog; 
import android.app.ProgressDialog; 
import android.bluetooth.BluetoothAdapter; 
import android.bluetooth.BluetoothDevice; 
import android.bluetooth.BluetoothSocket; 
import android.content.Context; 
import android.content.DialogInterface; 
import android.content.Intent; 
import android.content.SharedPreferences; 
import android.content.res.Configuration; 
import android.graphics.Bitmap; 
import android.graphics.Canvas; 
import android.graphics.Color; 
import android.graphics.ColorMatrix; 
import android.graphics.ColorMatrixColorFilter; 
import android.graphics.PorterDuff.Mode; 
import android.graphics.drawable.BitmapDrawable; 
import android.graphics.drawable.Drawable; 
import android.os.Bundle; 
import android.os.Environment; 
import android.os.Handler; 
import android.os.Message; 
import android.preference.PreferenceManager; 
import android.provider.Settings; 
import android.util.Log; 
import android.view.KeyEvent; 
import android.view.MotionEvent; 
import android.view.View; 
import android.view.View.OnTouchListener; 
import android.view.Window; 
import android.view.WindowManager; 
import android.view.inputmethod.InputMethodManager; 
import android.widget.Button; 
import android.widget.EditText; 
import android.widget.ImageView; 
import android.widget.TextView; 
import android.widget.Toast; 

@SuppressLint("NewApi") 
public class Main extends Activity implements Runnable 
{ 
    protected static final String TAG = "TAG"; 
    private static final int REQUEST_CONNECT_DEVICE = 1; 
    private static final int REQUEST_ENABLE_BT = 2; 
    Button mScan; 
    BluetoothAdapter mBluetoothAdapter; 
    private UUID applicationUUID = UUID.fromString("00001101-0000-1000-8000-00805F9B34FB"); 
    private ProgressDialog mBluetoothConnectProgressDialog; 
    private BluetoothSocket mBluetoothSocket; 
    BluetoothDevice mBluetoothDevice; 

    String MESSAGEPASS; 

    @Override 
    public void onCreate(Bundle mSavedInstanceState) 
    { 
     super.onCreate(mSavedInstanceState); 
     requestWindowFeature(Window.FEATURE_NO_TITLE); 
     getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 
      WindowManager.LayoutParams.FLAG_FULLSCREEN); 
     setContentView(R.layout.main); 
     mScan = (Button) findViewById(R.id.Scan); 
     mScan.setOnClickListener(new View.OnClickListener() 
     { 
      public void onClick(View mView) 
      { 
       mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter(); 
       if (mBluetoothAdapter == null) 
       { 
        Toast.makeText(Main.this, "Message1", 2000).show(); 
       } 
       else 
       { 
        if (!mBluetoothAdapter.isEnabled()) 
        { 
         Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); 
         startActivityForResult(enableBtIntent, REQUEST_ENABLE_BT); 
        } 
        else 
        { 
         ListPairedDevices(); 
         Intent connectIntent = new Intent(Main.this, DeviceListActivity.class); 
         startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE); 
        } 
       } 
      } 
     }); 

    } 

    public void onActivityResult(int mRequestCode, int mResultCode, Intent mDataIntent) 
    { 
     super.onActivityResult(mRequestCode, mResultCode, mDataIntent); 

     switch (mRequestCode) 
     { 
      case REQUEST_CONNECT_DEVICE: 
       if (mResultCode == Activity.RESULT_OK) 
       { 
        Bundle mExtra = mDataIntent.getExtras(); 
        String mDeviceAddress = mExtra.getString("DeviceAddress"); 
        Log.v(TAG, "Coming incoming address " + mDeviceAddress); 
        mBluetoothDevice = mBluetoothAdapter.getRemoteDevice(mDeviceAddress); 
        mBluetoothConnectProgressDialog = ProgressDialog.show(this, "Connecting...", mBluetoothDevice.getName() + " : " + mBluetoothDevice.getAddress(), true, false); 

        Thread mBlutoothConnectThread = new Thread(this); 
        mBlutoothConnectThread.start(); 



        //pairToDevice(mBluetoothDevice); This method is replaced by progress dialog with thread 


       } 
       break; 

      case REQUEST_ENABLE_BT: 
       if (mResultCode == Activity.RESULT_OK) 
       { 
        ListPairedDevices(); 
        Intent connectIntent = new Intent(Main.this, DeviceListActivity.class); 
        startActivityForResult(connectIntent, REQUEST_CONNECT_DEVICE); 
       } 
       else 
       { 
        Toast.makeText(Main.this, "Message", 2000).show(); 
       } 
       break; 
     } 
    } 

    private void ListPairedDevices() 
    { 
     Set<BluetoothDevice> mPairedDevices = mBluetoothAdapter.getBondedDevices(); 
     if (mPairedDevices.size() > 0) 
     { 
      for (BluetoothDevice mDevice : mPairedDevices) 
      { 
       Log.v(TAG, "PairedDevices: " + mDevice.getName() + " " + mDevice.getAddress()); 
      } 
     } 
    } 

    public void run() 
    { 
     try 
     { 
      mBluetoothSocket = mBluetoothDevice.createRfcommSocketToServiceRecord(applicationUUID); 
      mBluetoothAdapter.cancelDiscovery(); 
      mBluetoothSocket.connect(); 
      mHandler.sendEmptyMessage(0); 
     } 
     catch (IOException eConnectException) 
     { 
      Log.d(TAG, "CouldNotConnectToSocket", eConnectException); 
      closeSocket(mBluetoothSocket); 
      return; 
     } 
    } 

    private void closeSocket(BluetoothSocket nOpenSocket) 
    { 
     try 
     { 
      nOpenSocket.close(); 
      Log.d(TAG, "SocketClosed"); 
     } 
     catch (IOException ex) 
     { 
      Log.d(TAG, "CouldNotCloseSocket"); 
     } 
    } 

    private Handler mHandler = new Handler() 
    { 
     @Override 
     public void handleMessage(Message msg) 
     { 
      mBluetoothConnectProgressDialog.dismiss(); 
      Toast.makeText(Main.this, "Device Connected", 5000).show(); 

      Intent in = new Intent(getBaseContext(), Option.class); 
      startActivity(in); 

     } 
    }; 



} 

답변

0

을주세요 ...입니다 check this out

+0

이 이봐, 난이를 발견하지만 난 {다른 활동에 MAC 주소 .. –

+0

개인 무효 sendDataToPairedDevice (문자열 메시지, BluetoothDevice 장치) 장치를 전달하는 방법을 잘 모릅니다 바이트 [] (=의 message.getBytes toSend) ; 시도 { BluetoothSocket socket = device.createInsecureRfcommSocketToServiceRecord (applicationUUID); OutputStream mmOutStream = socket.getOutputStream(); mmOutStream.write (toSend); // 귀하의 데이터는 페어링 된 페어링 된 ENGOY 장치로 전송됩니다. } catch (IOException e) { Log.e (TAG, "쓰기 중 예외", e); } } –

관련 문제