package cpulisenner.ujs.com.cpulisenner; import android.Manifest; import android.app.ActivityManager; import android.content.Context; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.graphics.drawable.BitmapDrawable; import android.media.MediaPlayer; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.os.StatFs; import android.support.v4.app.ActivityCompat; import android.support.v4.content.ContextCompat; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.format.Formatter; import android.util.Log; import android.view.MenuItem; import android.view.SurfaceHolder; import android.view.SurfaceView; import android.view.View; import android.widget.Button; import android.widget.EditText; import android.widget.ImageView; import android.widget.SeekBar; import android.widget.TextView; import android.widget.Toast; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import java.text.DecimalFormat; import java.util.ArrayList; import java.util.List; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import java.util.UUID; public class MainActivity extends AppCompatActivity { private TextView mGetCpu; private Button msave; private TextView tv_show; private Button read; private Button accessImg; private Button save_picture; private ImageView showImg; private ImageView img; private String fileName1; private TextView showText; private SurfaceView sfv;//能够播放图像的控件 private SeekBar sb;//进度条 private String path ;//本地文件路径 private SurfaceHolder holder; private MediaPlayer player;//媒体播放器 private Button Play;//播放按钮 private Timer timer;//定时器 private TimerTask task;//定时器任务 private int position = 0; private EditText et; private boolean createFlag = true; private boolean threadFlag = true; private boolean dthreadFlag = true; private boolean isFirstStart = true; private boolean disFirstStart = true; private Thread thread1,thread2; // ActivityManager mActivityManager; private static final String TAG = "MainActivity"; private static final int UPDATE = 0; private static final int SHOW = 1; private static final int UNSHOW = 2; private static final int TOAST_WRITE = 3; private static final int TOAST_DELETE = 4; private static final int DELETES = 5; GetCpu getcpu = new GetCpu(); Handler handler = new Handler(){ public void handleMessage(Message msg){ switch (msg.what){ case UPDATE: mGetCpu.setText(""); mGetCpu.append("CPU最大频率为:"+ Integer.toString(getcpu.getMaxCPU()) + "\n"); mGetCpu.append("CPU最小频率为:"+ Integer.toString(getcpu.getMinCPU()) + "\n"); mGetCpu.append("CPU当前频率为:"+ Integer.toString(getcpu.getCurCPU()) + "\n"); mGetCpu.append("当前SD总存储为:" + getUnitString(getSDTotalSize()) + "\n"); mGetCpu.append("当前SD可用存储为:" + getUnitString(getSDAvailableSize()) + "\n"); // mGetCpu.append("当前ROM总存储为:" + getUnitString(getRomTotalSize()) + "\n"); // mGetCpu.append("当前ROM可用存储为:" + getUnitString(getRomAvailableSize()) + "\n"); break; case SHOW: tv_show.setTextColor(Color.BLUE); tv_show.setText("正在不断写图片中..."); break; case UNSHOW: tv_show.setTextColor(Color.RED); tv_show.setText("文件正在删除中,请等待..."); break; case TOAST_WRITE: Toast.makeText(MainActivity.this, getString(R.string.file), Toast.LENGTH_SHORT).show(); break; case TOAST_DELETE: Toast.makeText(MainActivity.this,getString(R.string.filesuccess),Toast.LENGTH_SHORT).show(); Log.d(TAG, "deleteFile: success"); break; case DELETES: tv_show.setTextColor(Color.GREEN); tv_show.setText("文件删除成功!"); default: break; } super.handleMessage(msg); } }; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); mGetCpu = (TextView)findViewById(R.id.getcpu); msave = (Button) findViewById(R.id.save); tv_show = findViewById(R.id.tv_show); /*read = (Button) findViewById(R.id.read); accessImg = (Button) findViewById(R.id.access_Img); save_picture = (Button) findViewById(R.id.save_picture);*/ showImg = (ImageView)findViewById(R.id.showImg); img = (ImageView) findViewById(R.id.set_img); showText = (TextView) findViewById(R.id.showText); //mActivityManager = (ActivityManager)getSystemService(Context.ACTIVITY_SERVICE); if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_CONTACTS) != PackageManager.PERMISSION_GRANTED) { // Should we show an explanation? if (ActivityCompat.shouldShowRequestPermissionRationale(this, Manifest.permission.WRITE_EXTERNAL_STORAGE)) { // Show an expanation to the user *asynchronously* -- don't block // this thread waiting for the user's response! After the user // sees the explanation, try again to request the permission. } else { // No explanation needed, we can request the permission. ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE}, 1); // MY_PERMISSIONS_REQUEST_READ_CONTACTS is an // app-defined int constant. The callback method gets the // result of the request. } } new Thread(){ public void run(){ try{ while (true){ Thread.sleep(1000);//设置时间间隔为3s Message msg = new Message(); msg.what = UPDATE; handler.sendMessage(msg); } }catch (InterruptedException e){ e.printStackTrace(); } } }.start(); //获取内部存储状态 String state = Environment.getExternalStorageState(); //如果状态不是mounted,无法读写 if (!state.equals(Environment.MEDIA_MOUNTED)) { return; } initBack(); initView(); } private void initBack() { ActionBar action = getSupportActionBar(); if(action != null){ action.setHomeButtonEnabled(true); action.setDisplayHomeAsUpEnabled(true); } } public boolean onOptionsItemSelected(MenuItem item){ int id = item.getItemId(); switch (id){ case android.R.id.home: this.finish(); System.exit(0); return true; } return super.onOptionsItemSelected(item); } //將佈局中的文件放到sd卡中 public void saveImage (View view) { createFlag = true; File file = Environment.getExternalStorageDirectory(); String path = file + "/test_data"; File file_test = new File(path); if(!file_test.exists()){ file_test.mkdir(); } Message msg = new Message(); msg.what = SHOW; handler.sendMessage(msg); new Thread(){ @Override public void run() { try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } for (int i = 1; createFlag; i++) { Log.d(TAG, "saveImage: " + i); writeFile(R.drawable.eleven); writeFile(R.drawable.five); writeFile(R.drawable.four); writeFile(R.drawable.nine); writeFile(R.drawable.one); writeFile(R.drawable.six); writeFile(R.drawable.ten); writeFile(R.drawable.test); writeFile(R.drawable.three); writeFile(R.drawable.twlve); writeFile(R.drawable.two); } } }.start(); } public void deleteFile(View v) { //threadFlag = true; createFlag = false; Message msg = new Message(); msg.what = UNSHOW; handler.sendMessage(msg); new Thread() { @Override public void run() { super.run(); File file = Environment.getExternalStorageDirectory(); String path = file + "/test_data"; File file_test = new File(path); if(!file_test.exists()) { Message msg = new Message(); msg.what = TOAST_WRITE; handler.sendMessage(msg); } else { // Message msg = new Message(); dFile(file_test); while (file_test.exists()){ dFile(file_test); continue; } Message msg2 = new Message(); msg2.what = DELETES; handler.sendMessage(msg2); } } }.start(); } //效果展示 public void readImg(View view){ String path=Environment.getExternalStorageDirectory()+"/"+fileName1+".jpg"; Bitmap bitmap= BitmapFactory.decodeFile(path); showImg.setImageBitmap(bitmap); } DecimalFormat df = new java.text.DecimalFormat("#.00"); private String getUnitString(long size) { String unitString = ""; if (size / 1024 / 1024 / 1024 > 0) { unitString = df.format((double)size / 1024 / 1024 / 1024) + "GB"; } else if (size / 1024 / 1024 > 0) { unitString = df.format((double)size / 1024 / 1024) + "MB"; } else if (size / 1024 > 0) { unitString = df.format((double)size / 1024) + "KB"; } else if (size > 0) { unitString = df.format((double)size) + "KB"; } else { unitString = "0B"; } return unitString; } public static long getSDAvailableSize() { try { File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSizeLong(); long availableBlocks = stat.getAvailableBlocksLong(); return blockSize * availableBlocks; } catch (Exception e) { e.printStackTrace(); } return -1; } private static long getRomTotalSize(){ try { File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSizeLong(); long totalBlocks = stat.getBlockCountLong(); return blockSize * totalBlocks; } catch (Exception e) { e.printStackTrace(); } return -1; } private static long getRomAvailableSize() { try { File path = Environment.getDataDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSizeLong(); long availableBlocks = stat.getAvailableBlocksLong(); return blockSize * availableBlocks; } catch (Exception e) { e.printStackTrace(); } return -1; } public static long getSDTotalSize() { try { File path = Environment.getExternalStorageDirectory(); StatFs stat = new StatFs(path.getPath()); long blockSize = stat.getBlockSizeLong(); long totalBlocks = stat.getBlockCountLong(); return blockSize * totalBlocks; } catch (Exception e) { e.printStackTrace(); } return -1; } //初始化控件,并且为进度条和图像控件添加监听 private void initView() { sfv = (SurfaceView) findViewById(R.id.sfv); sb = (SeekBar) findViewById(R.id.sb); Play = (Button) findViewById(R.id.play); et = (EditText) findViewById(R.id.et); Play.setEnabled(false); holder = sfv.getHolder(); holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS); sb.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() { @Override public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) { } @Override public void onStartTrackingTouch(SeekBar seekBar) { } @Override public void onStopTrackingTouch(SeekBar seekBar) { //当进度条停止拖动的时候,把媒体播放器的进度跳转到进度条对应的进度 if (player != null) { player.seekTo(seekBar.getProgress()); } } }); holder.addCallback(new SurfaceHolder.Callback() { @Override public void surfaceCreated(SurfaceHolder holder) { //为了避免图像控件还没有创建成功,用户就开始播放视频,造成程序异常,所以在创建成功后才使播放按钮可点击 Log.d("zhangdi","surfaceCreated"); Play.setEnabled(true); } @Override public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) { Log.d("zhangdi","surfaceChanged"); } @Override public void surfaceDestroyed(SurfaceHolder holder) { //当程序没有退出,但不在前台运行时,因为surfaceview很耗费空间,所以会自动销毁, // 这样就会出现当你再次点击进程序的时候点击播放按钮,声音继续播放,却没有图像 //为了避免这种不友好的问题,简单的解决方式就是只要surfaceview销毁,我就把媒体播放器等 //都销毁掉,这样每次进来都会重新播放,当然更好的做法是在这里再记录一下当前的播放位置, //每次点击进来的时候把位置赋给媒体播放器,很简单加个全局变量就行了。 Log.d("zhangdi","surfaceDestroyed"); if (player != null) { position = player.getCurrentPosition(); stop(); } } }); } private void play() { Play.setEnabled(false);//在播放时不允许再点击播放按钮 if (isPause) {//如果是暂停状态下播放,直接start isPause = false; player.start(); return; } path = Environment.getExternalStorageDirectory().getPath()+"/"; path = path + et.getText().toString();//sdcard的路径加上文件名称是文件全路径 File file = new File(path); if (!file.exists()) {//判断需要播放的文件路径是否存在,不存在退出播放流程 Toast.makeText(this,"文件路径不存在",Toast.LENGTH_LONG).show(); return; } try { player = new MediaPlayer(); player.setDataSource(path); player.setDisplay(holder);//将影像播放控件与媒体播放控件关联起来 player.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) {//视频播放完成后,释放资源 Play.setEnabled(true); stop(); } }); player.setOnPreparedListener(new MediaPlayer.OnPreparedListener() { @Override public void onPrepared(MediaPlayer mp) { //媒体播放器就绪后,设置进度条总长度,开启计时器不断更新进度条,播放视频 Log.d("zhangdi","onPrepared"); sb.setMax(player.getDuration()); timer = new Timer(); task = new TimerTask() { @Override public void run() { if (player != null) { int time = player.getCurrentPosition(); sb.setProgress(time); } } }; timer.schedule(task,0,500); sb.setProgress(position); player.seekTo(position); player.start(); } }); player.prepareAsync(); } catch (IOException e) { e.printStackTrace(); } } public void play(View v) { play(); Log.d("zhangdi",path); } private boolean isPause; private void pause() { if (player != null && player.isPlaying()) { player.pause(); isPause = true; Play.setEnabled(true); } } public void pause(View v) { pause(); } private void replay() { isPause = false; if (player != null) { stop(); play(); } } public void replay(View v) { replay(); } private void stop(){ isPause = false; if (player != null) { sb.setProgress(0); player.stop(); player.release(); player = null; if (timer != null) { timer.cancel(); } Play.setEnabled(true); } } public void stop(View v) { stop(); } @Override protected void onDestroy() { super.onDestroy(); stop(); } //flie:要删除的文件夹的所在位置 private void dFile(File file) { if (file.isDirectory()) { File[] files = file.listFiles(); for (int i = 0; i < files.length; i++) { File f = files[i]; dFile(f); } file.delete();//如要保留文件夹,只删除文件,请注释这行 } else if (file.exists()) { file.delete(); } } public void writeFile(int id) { FileOutputStream fos = null; File file = Environment.getExternalStorageDirectory(); String path = file + "/test_data"; try { fileName1 = UUID.randomUUID().toString(); //BitmapDrawable bitmapDrawable = (BitmapDrawable) getResources().getDrawable(id); //Bitmap bitmap = bitmapDrawable.getBitmap(); Bitmap bitmap = BitmapFactory.decodeResource(MainActivity.this.getResources(), id); fos = new FileOutputStream(path + "/" + fileName1 + ".jpg"); bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos); } catch (FileNotFoundException e) { e.printStackTrace(); } finally { if (fos != null) { try { fos.close(); } catch (IOException e) { e.printStackTrace(); } } } } // 从assets复制文件到sd卡,耗时操作 public static void copyAssetsFileToSdDir(Context context, String AssetsFileName, String sdFilePath) { InputStream is = null; OutputStream os = null; try { is = context.getResources().getAssets().open(AssetsFileName); File targetFile = new File(sdFilePath); if (targetFile.exists()) { return; } File parentFile = targetFile.getParentFile(); if (!parentFile.exists()) { parentFile.mkdirs(); } os = new FileOutputStream(targetFile); // copy file byte[] buffer = new byte[1024]; int len = -1; if (is != null && os != null) { while ((len = is.read(buffer)) != -1) { // 将Buffer中的数据写到outputStream对象中 os.write(buffer, 0, len); } } } catch (Exception e) { e.printStackTrace(); } finally { try { if (is != null) { is.close(); } if (os != null) { os.close(); } } catch (IOException e2) { e2.printStackTrace(); } } } } -----------------------------------------------------------package cpulisenner.ujs.com.cpulisenner; import android.util.Log; import java.io.BufferedReader; import java.io.FileNotFoundException; import java.io.FileReader; import java.io.IOException; import static android.content.ContentValues.TAG; /** * Created by Administrator on 2018/1/22. */ public class GetCpu { //保存当前CPU频率 private final static String CurPath = "/sys/devices/system/cpu/cpu0/cpufreq/scaling_cur_freq"; //获取当前CPU频率 public static int getCurCPU(){ int result = 0; FileReader fr = null; BufferedReader br = null; try{ fr = new FileReader(CurPath); br = new BufferedReader(fr); String text = br.readLine(); Log.d(TAG, "getCurCPU: text"+text); result = Integer.parseInt(text.trim()); }catch (FileNotFoundException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); }finally { if (fr != null) try{ fr.close(); }catch (IOException e){ e.printStackTrace(); } if (br != null) try{ br.close(); }catch (IOException e){ e.printStackTrace(); } } return result; } private final static String MaxPath = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_max_freq";//保存CPU可运行最大频率 //获取CPU可运行最大频率 public static int getMaxCPU(){ int result = 0; FileReader fr = null; BufferedReader br = null; try{ fr = new FileReader(MaxPath); br = new BufferedReader(fr); String text = br.readLine(); result = Integer.parseInt(text.trim()); }catch (FileNotFoundException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); }finally { if (fr != null) try{ fr.close(); }catch (IOException e){ e.printStackTrace(); } if (br != null) try{ br.close(); }catch (IOException e){ e.printStackTrace(); } } return result; } private final static String MinPath = "/sys/devices/system/cpu/cpu0/cpufreq/cpuinfo_min_freq";//保存CPU可运行最小频率 //获取CPU可运行最小频率 public static int getMinCPU(){ int result = 0; FileReader fr = null; BufferedReader br = null; try{ fr = new FileReader(MinPath); br = new BufferedReader(fr); String text = br.readLine(); result = Integer.parseInt(text.trim()); }catch (FileNotFoundException e){ e.printStackTrace(); }catch (IOException e){ e.printStackTrace(); }finally { if (fr != null) try{ fr.close(); }catch (IOException e){ e.printStackTrace(); } if (br != null) try{ br.close(); }catch (IOException e){ e.printStackTrace(); } } return result; } }-------------------------------------------------------------------------<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context="cpulisenner.ujs.com.cpulisenner.MainActivity"> <TextView android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/getcpu" /> <LinearLayout android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal"> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Save" android:id="@+id/save" android:onClick="saveImage" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Delete" android:id="@+id/delete" android:onClick="deleteFile" android:layout_marginLeft="50dp" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/tv_show" android:layout_marginLeft="50dp" /> </LinearLayout> <!--<Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Read" android:onClick="readImg" android:id="@+id/read" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Access to network information" android:id="@+id/access_Img" /> <Button android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Save Picture" android:id="@+id/save_picture" />--> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/set_img" android:src="@mipmap/ic_launcher" android:visibility="gone" /> <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/showImg" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:id="@+id/showText" /> <EditText android:id="@+id/et" android:layout_width="match_parent" android:layout_height="wrap_content" android:hint="请输入文件名称例如:aa.mp4,务必确保文件放在sdcard目录下"/> <SurfaceView android:id="@+id/sfv" android:layout_width="match_parent" android:layout_marginTop="10dp" android:layout_height="350dp" /> <SeekBar android:id="@+id/sb" android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp"/> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_marginTop="10dp" android:orientation="horizontal"> <Button android:id="@+id/play" android:layout_width="0dp" android:layout_height="60dp" android:layout_weight="1" android:onClick="play" android:text="播放"/> <Button android:id="@+id/pause" android:layout_width="0dp" android:layout_height="60dp" android:layout_marginLeft="10dp" android:layout_weight="1" android:onClick="pause" android:text="暂停"/> <Button android:layout_width="0dp" android:layout_height="60dp" android:layout_marginLeft="10dp" android:layout_weight="1" android:onClick="stop" android:text="停止"/> <Button android:layout_width="0dp" android:layout_height="60dp" android:layout_marginLeft="10dp" android:layout_weight="1" android:onClick="replay" android:text="重播"/> </LinearLayout> </LinearLayout>
copyResouseFileToSdcard
最新推荐文章于 2021-05-31 10:47:18 发布