android开发 基本操作

这篇博客详细介绍了Android开发中的基本操作,包括读写txt文件、删除文件/目录、获取SD卡和外部存储卡路径、Bitmap操作、在内部SD卡创建路径、使用AssetManager读取资源、计算程序运行时间、提取视频帧以及MTK6725行车智能设备的开发。同时,针对adb设备识别问题提供了解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

读写txt文件

FileInputStream、FileOutputStream参见
http://blog.youkuaiyun.com/mad1989/article/details/37568667

删除文件/目录

//可调用函数:
File baseimagesfile=new File(BASE_IMAGE_PATH);

if (!baseimagesfile.exists()) {  // 不存在返回 false

} else {
    // 判断是否为文件
    if (baseimagesfile.isFile()) {  // 为文件时调用删除文件方法
        deleteFile(BASE_IMAGE_PATH);
    } else {  // 为目录时调用删除目录方法
        deleteDirectory(BASE_IMAGE_PATH);
    }
}

//子函数:
    public boolean deleteFile(String sPath) {
        boolean flag = false;
        File file = new File(sPath);
        // 路径为文件且不为空则进行删除
        if (file.isFile() && file.exists()) {
            file.delete();
            flag = true;
        }
        return flag;
    }
    public boolean deleteDirectory(String sPath) {
        boolean flag;
        //如果sPath不以文件分隔符结尾,自动添加文件分隔符
        if (!sPath.endsWith(File.separator)) {
            sPath = sPath + File.separator;
        }
        File dirFile = new File(sPath);
        //如果dir对应的文件不存在,或者不是一个目录,则退出
        if (!dirFile.exists() || !dirFile.isDirectory()) {
            return false;
        }
        flag = true;
        //删除文件夹下的所有文件(包括子目录)
        File[] files = dirFile.listFiles();
        for (int i = 0; i < files.length; i++) {
            //删除子文件
            if (files[i].isFile()) {
                flag = deleteFile(files[i].getAbsolutePath());
                if (!flag) break;
            } //删除子目录
            else {
                flag = deleteDirectory(files[i].getAbsolutePath());
                if (!flag) break;
            }
        }
        if (!flag) return false;
        //删除当前目录
        if (dirFile.delete()) {
            return true;
        } else {
            return false;
        }
    }

获取SD卡根目录

public static String getSdCardPath() {  
    boolean exist = isSdCardExist();  
    String sdpath = "";  
    if (exist) {  
        sdpath = Environment.getExternalStorageDirectory()  
                .getAbsolutePath();  
    } else {  
        sdpath = "不适用";  
    }  
    return sdpath;  
} 

获取外部存储卡TF目录

try {
    Runtime runtime = Runtime.getRuntime();
    Process proc = runtime.exec("mount");
    InputStream is = proc.getInputStream();
    InputStreamReader isr = new InputStreamReader(is);
    String line;
    String mount = new String();
    BufferedReader br = new BufferedReader(isr);
    while ((line = br.readLine()) != null) {
        if (line.contains("secure")) continue;
        if (line.contains("asec")) continue;

        if (line.contains("fat")) {
            String columns[] = line.split(" ");
            if (columns != null && columns.length > 1) {
                mount = mount.concat("*" + columns[1] + "\n");
            }
        } else if (line.contains("fuse")) {
            String columns[] = line.split(" ");
            if (columns != null && columns.length > 1) {
                mount = mount.concat(columns[1] + "\n");
            }
        }
    }
    Log.e("外置SD卡路径2:", mount );
} catch (FileNotFoundException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
} catch (IOException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}

Bitmp

//读取bitmap
Bitmap bitmap2 = null;
try{
      File avaterFile = new File("/storage/emulated/0/tensorflow/test.png");
      if(avaterFile.exists()) {
        bitmap2 = BitmapFactory.decodeFile(avaterFile.getPath());
      }
    } catch (Exception e) {}

//保存bitmap
 private void saveBitmap(Bitmap bitmap,String bitName) throws IOException
 {
   String BASE_IMAGE_PATH="/storage/emulated/0/tensorflow";
   //new File(BASE_IMAGE_PATH).mkdirs();

   File file = new File(BASE_IMAGE_PATH+"/"+bitName);
   if(file.exists()){
     file.delete();
   }
   FileOutputStream out;
   try{
     out = new FileOutputStream(file);
     if(bitmap.compress(Bitmap.CompressFormat.PNG, 90, out))
     {
       out.flush();
       out.close();
     }
   }
   catch (FileNotFoundException e)
   {
     e.printStackTrace();
   }
   catch (IOException e)
   {
     e.printStackTrace();
   }
 }
try {
  saveBitmap(bitmap, "test.png");
}
catch (IOException e){
   Log.e("Save bitmap error !","------------------------------");
}

在内部sd卡中创建并获取路径

应用程序文件在sd卡中的路径通常是/storage/emulated/0/Android/data/yourappfolder/files/,下面的函数可以在这个路径下创建文件夹。

private File getOrCreateExternalModelsRootDirectory() throws IOException {
    final File modelsRoot = getExternalFilesDir("models");
    if (modelsRoot == null) {
        throw new IOException("Unable to access application external storage.");
    }

    if (!modelsRoot.isDirectory() && !modelsRoot.mkdir()) {
        throw new IOException("Unable to create model root directory: " +
                modelsRoot.getAbsolutePath());
    }
    return modelsRoot;
}

使用AssetManager从asset读图片/文件

        AssetManager manager = getResources().getAssets();
        String[] allimgpath= null;
        try{
        //"mages"是asset下的文件夹
        //如果我们要直接获取 assets目录下的所有文件和文件夹怎么办? 
        //manager.list("")
            allimgpath=manager.list("images");
        }catch (IOException e){
            e.printStackTrace();
        }

参考
http://blog.youkuaiyun.com/greathfs/article/details/52123984

计算程序运行时间

long startTime=System.currentTimeMillis();   //获取开始时间
doSomeThing();  //测试的代码段
long endTime=System.currentTimeMillis(); //获取结束时间
System.out.println("程序运行时间: "+(end-start)+"ms");

使用MediaMetadataRetriver获取存储卡中的视频特定帧,并保存

try {
   //创建保存图片的目录
   File modelsRoot = getOrCreateExternalModelsRootDirectory(); //获取 或者 创建 models目录

   //获取当前视频路径
   String dataPath = "/storage/sdcard1/DCIM/DVR/20180109/VID_125728_567.mp4";
   MediaMetadataRetriever retriever = new MediaMetadataRetriever();
   retriever.setDataSource(dataPath);
   // 取得视频的长度(单位为毫秒)
   String time = retriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
   // 取得视频的长度(单位为秒)
   int seconds = Integer.valueOf(time) / 1000;
   //获得想要的帧数
   int num = seconds*24;
   // 得到每一秒时刻的bitmap比如第一秒,第二秒
   Log.e("一共:",String.valueOf(num)+" 帧");
   long endTime,startTime;
   for (int i = 1; i <=10; i++) {
       Bitmap bitmap = retriever.getFrameAtTime(i*1000*1000,MediaMetadataRetriever.OPTION_CLOSEST_SYNC);
       String path = modelsRoot.getPath() + File.separator + i + ".jpg";
       FileOutputStream fos = null;
       try {
           fos = new FileOutputStream(path);
           startTime=System.currentTimeMillis();
           bitmap.compress(Bitmap.CompressFormat.JPEG, 80, fos);
           endTime=System.currentTimeMillis();
           System.out.println("保存第:"+i+" 帧,  耗时:" + (endTime - startTime) + "ms");    //输出程序运行时间

           fos.close();
       } catch (Exception e) {
           e.printStackTrace();
       }
   }

   //
}catch(IOException e){
   e.printStackTrace();
}

开发MTK6725行车智能搭载设备

adb窗口不能正确识别设备,
androidstudio报错:

com.android.ddmlib.AdbCommandRejectedException: insufficient permissions for device: verify udev rule

解决方法:

编辑文件
sudo gedit /etc/udev/rules.d/51-android.rules
添加
SUBSYSTEM==”usb”, ATTR{idVendor}==”12d1”, MODE=”0666”, GROUP=”plugdev”
里面的12d1对应的是设备对应的型号可以用lsusb查询,MODE对应的是权限对照表

参考:
http://www.jianshu.com/p/46e8848c6646
developer.android.com/tools/device.html

todo:getFrameAtTime函数的参数解析

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值