在Android中通过蓝牙发送文件

时间:2018-09-11 20:19:13

标签: android android-bluetooth

目标:我需要创建一个基本的Android应用,在这里我可以连接到附近的蓝牙设备,并通过单击按钮从我的图库向他们发送图像。这是我到目前为止的事情,我对从这里去哪里有些困惑。 (这是我在Android上的第一个项目,所以请放心吧。)

public class MainActivity extends AppCompatActivity {
    private static final int Discover_duration = 300;
    private static final int request_bluetooth = 1;
    String path;
    private static final int Initial_request = 1337;
    private static final int request_write_storage = Initial_request + 4;
    private BluetoothAdapter mBTA = null;
    Button sendfile_button;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        sendfile_button = (Button)findViewById(R.id.sendfile_button);


         mBTA = BluetoothAdapter.getDefaultAdapter();
        if (mBTA == null) {
            Toast.makeText(this, "Bluetooth is not supported on this device", Toast.LENGTH_LONG).show();
        }
        if (!mBTA.isEnabled()) {
            Intent enableBtIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
            startActivityForResult(enableBtIntent, request_bluetooth);
        }
        Intent discoverableIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
        discoverableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
        startActivity(discoverableIntent);

        mBTA.startDiscovery();

        //Register for Broadcasts when a device is discovered.
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(mReceiver, filter);

    }

}

private final BroadcastReceiver mReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                //Bluetooth device has been discovered, retrive its info
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String deviceName = device.getName();
                String deviceHardwareAddress = device.getAddress();
            }
        }
    };

    @override
    protected void onDestroy() {
        super.onDestroy();

        unregisterReceiver(mReceiver);
    }
}

0 个答案:

没有答案