最近学习安卓开发,到经典蓝牙这一章的作业题时候,发现难度与之前的作业相比提高了不少,因为本节视频讲解的非常简略,并且作业里包含了一些以前没有接触过的知识点。最后作业的完成离不开自学,这里将困难杂疑和需要自学的知识点及相关代码记录如下:
1.如何从手机图库中调用图片:
这个功能不仅作业中用的到,各类app里也出现频繁,比如调用图库里的图片并设置为用户的头像,比如发送图片等等,代码如下:
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btn_select:
Intent galleryIntent = new Intent(Intent.ACTION_GET_CONTENT);
galleryIntent.addCategory(Intent.CATEGORY_OPENABLE);
galleryIntent.setType("image/*");
startActivityForResult(galleryIntent, IMAGE_REQUEST_CODE);
break;}
/**
* startActivityForResult()的回调结果
*
* @param requestCode
* @param resultCode
* @param data returned data
*/
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode){
case IMAGE_REQUEST_CODE:
/*这里是调整图片的格式等,可以自行更改或删除 */
Intent intent = new Intent("com.android.camera.action.CROP");
intent.setDataAndType(data.getData(), "image/*");
intent.putExtra("crop", "true");
intent.putExtra("aspectX", 1);
intent.putExtra("aspectY", 1);
intent.putExtra("outputX", 300);
intent.putExtra("outputY", 300);
intent.putExtra("return-data", true);
startActivityForResult(intent, SHOW_REQUEST_CODE);
break;
case SHOW_REQUEST_CODE:
if(data!=null){
Bundle extras = data.getExtras();
if (extras != null) {
Bitmap photo = extras.getParcelable("data");
bitmapToSend=photo;
mImageHeader.setImageBitmap(photo);
}
}
break;
}
}
2.如何将照片存储到SD卡里,以及如何删除这些图片,使功能更加完善
注意在存储之前应该申请权限以及判断sd卡是否可用,这些都不难
/**
* 存储图片到SD卡的指定路径
*
* @param bm 要存的图片
* @param fileName 图片文件名加格式,如"test.jpg"
*/
private void saveImg(Bitmap bm, String fileName) {
try {
String ALBUM_PATH = Environment.getExternalStorageDirectory() + "/**********任意文件名/";
File dirFile = new File(ALBUM_PATH);
// 判断文件是否已经存在
if(!dirFile.exists()){
dirFile.mkdir();
}
File myCaptureFile = new File(ALBUM_PATH + fileName);
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
bm.compress(Bitmap.CompressFormat.JPEG, 80, bos);
bos.flush();
bos.close();
} catch (IOException e) {
}
}
/**
* 删除图片,可以删除单张图片,也可以删除指定文件夹下的所有图片
*
* @param file 要执行删除操作的文件
*/
private void deleteFile(File file) {
if(TextUtils.equals(Environment.getExternalStorageState(),Environment.MEDIA_MOUNTED)) {
// 判断给文件是文件夹还是图片
if (file.exists()) {
if (file.isFile()) {
file.delete();
}
else if (file.isDirectory()) {
// 声明目录下的所有文件 : files[];
File files[] = file.listFiles();
for (int i = 0; i < files.length; i++) {
// 遍历目录下的所有文件
deleteFile(files[i]); // 用此方法迭代每一个文件
}
}
file.delete();
}
}
}
3.用经典蓝牙在设备之间传,收图片。是本次作业的中心功能
以下代码源自慕课网学习资料,仅作出部分修改
/**
* This thread runs during a connection with a remote device.
* It handles all incoming and outgoing transmissions.
*/
private class ConnectedThread extends Thread {
private final BluetoothSocket mmSocket;
private final InputStream mmInStream;
private final OutputStream mmOutStream;
public ConnectedThread(BluetoothSocket socket) {
mmSocket = socket;
InputStream tmpIn = null;
OutputStream tmpOut = null;
// Get the BluetoothSocket input and output streams
try {
tmpIn = socket.getInputStream();
tmpOut = socket.getOutputStream();
} catch (IOException e) {
}
mmInStream = tmpIn;
mmOutStream = tmpOut;
}
public void run() {
setName("ConnectedThread");
// Keep listening to the InputStream while connected
while (mState == Constans.STATE_CONNECTED) {
try {
// 从输入流里读出图片
Bitmap map= BitmapFactory.decodeStream(mmInStream);
// Send the bitmap to the UI Activity
mHandler.obtainMessage(Constans.MESSAGE_IMAGE_READ, -1, -1, map)
.sendToTarget();
} catch (Exception e) {
connectionLost();
// Start the service over to restart listening mode
BluetoothService.this.start();
break;
}
}
}
/**
* Write to the connected OutStream.
*
* @param bitmap The photo to send
*/
public void sendImage(Bitmap bitmap) {
//利用输出流发送图片
try {
ByteArrayOutputStream byStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, byStream);
byte[] byteArray = byStream.toByteArray();
mmOutStream.write(byteArray);
} catch (IOException e) {
}
// Share the sent message back to the UI Activity
mHandler.obtainMessage(Constans.MESSAGE_SEND_IMAGE, -1, -1)
.sendToTarget();
}
- ActionBar 上面菜单栏的实现
/**
* 填充视图
*/
@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu,menu);
return true;
}
/**
* 设置监听事件
*/
@Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.item_discoverable:
//设置给设备在其他蓝牙设备扫描时可见
if(bluetoothAdapter.getScanMode()!=BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE){
Intent discovrableIntent=new Intent(BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
discovrableIntent.putExtra(BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,300);
startActivity(discovrableIntent);
T.showToast(MainActivity.this,"设备现在可见");
}
else {
T.showToast(MainActivity.this,"设备已可见");
}
return true;
case R.id.item_delete_photo:
//删除图片,详情在之前已经讲过
File myCaptureFile = new File(ALBUM_PATH );
deleteFile(myCaptureFile);
return true;
case R.id.item_scan:
//扫描设备
if(bluetoothAdapter!=null){
startActivityForResult(new Intent(MainActivity.this,DeviceDialogActivity.class),DEVICE_CHOSEN_BACK);
}
}
return false;
}
res\menu\main_menu.xml 其中showAsAction属性是显示时的样式,共有三种,可以显示文字,显示图片以及显示在可展开的菜单栏中
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item
android:id="@+id/item_scan"
android:icon="@drawable/ic_action_device_access_bluetooth_searching"
app:showAsAction="ifRoom"
android:title="@string/bluetooth"/>
<item
android:id="@+id/item_discoverable"
app:showAsAction="never"
android:title="@string/main_menu_item1" />
<item
android:id="@+id/item_delete_photo"
app:showAsAction="never"
android:title="@string/main_mmenu_item2" />
</menu>
以上就是在完成这次作业的过程中自学到的一些小知识,本人第一次发现和使用手记这个功能,再加上纯小白一枚,因此以上有错误或者理解不到位的地方,希望大佬们可以批评指正,同样在学习该路径的同学也欢迎讨论。