实例介绍
【实例简介】
【实例截图】
【核心代码】
package com.myway.activity; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.Map; import java.util.Random; import java.util.Timer; import java.util.TimerTask; import android.annotation.SuppressLint; import android.app.Activity; import android.app.Dialog; import android.app.ProgressDialog; import android.content.ContentValues; import android.content.Intent; import android.content.pm.PackageInfo; import android.content.pm.PackageManager; import android.content.pm.PackageManager.NameNotFoundException; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Color; import android.media.MediaMetadataRetriever; import android.media.MediaPlayer; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.os.Message; import android.provider.MediaStore; import android.view.Gravity; import android.view.KeyEvent; import android.view.MotionEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.View.OnLongClickListener; import android.view.View.OnTouchListener; import android.view.Window; import android.view.WindowManager; import android.widget.Button; import android.widget.ImageView; import android.widget.LinearLayout; import android.widget.TextView; import android.widget.Toast; import com.lidroid.xutils.exception.HttpException; import com.lidroid.xutils.http.ResponseInfo; import com.lidroid.xutils.http.callback.RequestCallBack; import com.myway.consts.Consts; import com.myway.manager.ContextManger; import com.myway.util.AudioRecorder; import com.myway.util.FileUtil; import com.myway.util.HttpDown; import com.myway.util.StringUtils; public class HomeActivity extends Activity implements OnClickListener,OnTouchListener,OnLongClickListener{ private ContextManger contextManger; protected static int RESULT_PHOTO_FILE = 1; protected static int RESULT_VEDIO_FILE = 2; protected static int RESULT_SONG_FILE = 3; protected static int RESULT_LOAD_FILE = 4; private Button takephoto; private Button takesong; private Button takevideo; private LinearLayout photolay; private LinearLayout songlay; private LinearLayout videolay; private ImageView photoview; private ImageView songview; private TextView songtime; private ImageView videoview; private String filePath=""; private Uri photoUri; private Uri videoUri; private Map<String,String> up_map= new HashMap<String, String>(); private ProgressDialog progressDialog; //图片浏览 //录音 private Dialog dialog; private AudioRecorder mr; private MediaPlayer mediaPlayer; private static int MAX_TIME = 30; //最长录制时间,单位秒,0为无时间限制 private static int MIX_TIME = 1; //最短录制时间,单位秒,0为无时间限制,建议设为1 private static int RECORD_NO = 0; //不在录音 private static int RECORD_ING = 1; //正在录音 private static int RECODE_ED = 2; //完成录音 private static int RECODE_STATE = 0; //录音的状态 private static float recodeTime=0.0f; //录音的时间 private static double voiceValue=0.0; //麦克风获取的音量值 private static boolean playState = false; //播放状态 private ImageView dialog_img; private Thread recordThread; String voicename =""; //程序是否退出 private static Boolean isExit = false; private Bundle bd; @SuppressLint("HandlerLeak") private Handler handler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 1: updateApk(); break; case 2: if(Consts.isupload==1){ contextManger.Uploadfile(new FileUploadRequestCallBack(HomeActivity.this),up_map,filePath); } break; } } }; @SuppressLint("InlinedApi") @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_home); bd = this.getIntent().getExtras(); contextManger = new ContextManger(this); up_map= new HashMap<String, String>(); initView(); progressDialog = new ProgressDialog(this); progressDialog.setMessage("正在上传中请稍后..."); progressDialog.setProgressStyle(ProgressDialog.THEME_DEVICE_DEFAULT_DARK); //提交更新 Message msg = Message.obtain(); msg.what = 1; handler.sendMessageDelayed(msg, 1); } private void initView() { takephoto = (Button) findViewById(R.id.takephoto); takephoto.setOnClickListener(this); takesong = (Button) findViewById(R.id.takesong); takesong.setOnTouchListener(this); takesong.setOnLongClickListener(this); takevideo = (Button) findViewById(R.id.takevideo); takevideo.setOnClickListener(this); photolay = (LinearLayout) findViewById(R.id.photolay); songlay = (LinearLayout) findViewById(R.id.songlay); videolay = (LinearLayout) findViewById(R.id.videolay); photoview = (ImageView) findViewById(R.id.photoview); photoview.setOnClickListener(this); songview = (ImageView) findViewById(R.id.songview); songview.setOnClickListener(this); songtime = (TextView) findViewById(R.id.songtime); videoview = (ImageView) findViewById(R.id.videoview); videoview.setOnClickListener(this); } @Override public void onClick(View v) { switch (v.getId()) { case R.id.takephoto: photolay.setVisibility(View.GONE); songlay.setVisibility(View.GONE); videolay.setVisibility(View.GONE); takePhoto(); break; case R.id.takevideo: photolay.setVisibility(View.GONE); songlay.setVisibility(View.GONE); videolay.setVisibility(View.GONE); takeVideo(); break; case R.id.photoview: if(filePath.indexOf(".jpg")>-1){ File file = new File(filePath); //下方是是通过Intent调用系统的图片查看器的关键代码 Intent intent = new Intent(); intent.setAction(android.content.Intent.ACTION_VIEW); intent.setDataAndType(Uri.fromFile(file), "image/*"); startActivity(intent); }else{ Toast.makeText(this, "无文件", Toast.LENGTH_SHORT).show(); } break; case R.id.songview: if(filePath.indexOf(".amr")>-1){ if (!playState) { mediaPlayer = new MediaPlayer(); String url = "file://" filePath; try { //模拟器里播放传url mediaPlayer.setDataSource(url); mediaPlayer.prepare(); mediaPlayer.start(); playState = true; //设置播放结束时监听 mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { if (playState) { playState = false; } } }); } catch (IllegalArgumentException e){ e.printStackTrace(); } catch (IllegalStateException e){ e.printStackTrace(); } catch (IOException e){ e.printStackTrace(); } }else { if (mediaPlayer.isPlaying()) { mediaPlayer.stop(); playState = false; }else { playState = false; } } }else{ Toast.makeText(this, "无文件", Toast.LENGTH_SHORT).show(); } break; case R.id.videoview: if(filePath.indexOf(".3gp")>-1){ //调用系统播放 //Intent intent = new Intent(Intent.ACTION_VIEW); //intent.setDataAndType(Uri.parse(filePath), "video/3gp"); //startActivity(intent); Intent intent = new Intent(HomeActivity.this, VideoActivity.class); Bundle bd = new Bundle(); bd.putString("filePath", filePath); intent.putExtras(bd); HomeActivity.this.startActivity(intent); }else{ Toast.makeText(this, "无文件", Toast.LENGTH_SHORT).show(); } break; default: break; } } @Override public boolean onLongClick(View v) { if(v.getId()==R.id.takesong){ } return false; } @SuppressLint({ "SimpleDateFormat", "ClickableViewAccessibility" }) @Override public boolean onTouch(View v, MotionEvent event) { photolay.setVisibility(View.GONE); songlay.setVisibility(View.GONE); videolay.setVisibility(View.GONE); switch (event.getAction()){ case MotionEvent.ACTION_DOWN: if (RECODE_STATE != RECORD_ING) { SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_hhmmss"); Date curDate = new Date(System.currentTimeMillis());//获取当前时间 voicename= formatter.format(curDate) new Random().nextInt(1000) new Random().nextInt(100) ".amr"; mr = new AudioRecorder(voicename); RECODE_STATE=RECORD_ING; showVoiceDialog(); try { mr.start(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } mythread(); } break; case MotionEvent.ACTION_UP: if (RECODE_STATE == RECORD_ING) { RECODE_STATE=RECODE_ED; if (dialog.isShowing()) { dialog.dismiss(); } try { mr.stop(); voiceValue = 0.0; } catch (IOException e) { e.printStackTrace(); } if (recodeTime < MIX_TIME) { showWarnToast(); takesong.setText("按住开始录音"); RECODE_STATE=RECORD_NO; }else{ takesong.setText("录音完成!按住重新录音"); songtime.setText(":" ((int)recodeTime)); filePath=Environment.getExternalStorageDirectory().toString() "/mwfile/" voicename; songlay.setVisibility(View.VISIBLE); //提交上传 Message msg = Message.obtain(); msg.what = 2; handler.sendMessageDelayed(msg, 200); } } break; } return false; } //录音时显示Dialog private void showVoiceDialog(){ dialog = new Dialog(HomeActivity.this,R.style.DialogStyle); dialog.requestWindowFeature(Window.FEATURE_NO_TITLE); dialog.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); dialog.setContentView(R.layout.my_dialog); dialog_img=(ImageView)dialog.findViewById(R.id.dialog_img); dialog.show(); } //录音时间太短时Toast显示 private void showWarnToast(){ Toast toast = new Toast(HomeActivity.this); LinearLayout linearLayout = new LinearLayout(HomeActivity.this); linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.setPadding(20, 20, 20, 20); // 定义一个ImageView ImageView imageView = new ImageView(HomeActivity.this); imageView.setImageResource(R.drawable.voice_to_short); // 图标 TextView mTv = new TextView(HomeActivity.this); mTv.setText("时间太短 录音失败"); mTv.setTextSize(14); mTv.setTextColor(Color.WHITE);//字体颜色 //mTv.setPadding(0, 10, 0, 0); // 将ImageView和ToastView合并到Layout中 linearLayout.addView(imageView); linearLayout.addView(mTv); linearLayout.setGravity(Gravity.CENTER);//内容居中 linearLayout.setBackgroundResource(R.drawable.record_bg);//设置自定义toast的背景 toast.setView(linearLayout); toast.setGravity(Gravity.CENTER, 0,0);//起点位置为中间 100为向下移100dp toast.show(); } //录音Dialog图片随声音大小切换 private void setDialogImage(){ if (voiceValue < 200.0) { dialog_img.setImageResource(R.drawable.record_animate_01); }else if (voiceValue > 200.0 && voiceValue < 400) { dialog_img.setImageResource(R.drawable.record_animate_02); }else if (voiceValue > 400.0 && voiceValue < 800) { dialog_img.setImageResource(R.drawable.record_animate_03); }else if (voiceValue > 800.0 && voiceValue < 1600) { dialog_img.setImageResource(R.drawable.record_animate_04); }else if (voiceValue > 1600.0 && voiceValue < 3200) { dialog_img.setImageResource(R.drawable.record_animate_05); }else if (voiceValue > 3200.0 && voiceValue < 5000) { dialog_img.setImageResource(R.drawable.record_animate_06); }else if (voiceValue > 5000.0 && voiceValue < 7000) { dialog_img.setImageResource(R.drawable.record_animate_07); }else if (voiceValue > 7000.0 && voiceValue < 10000.0) { dialog_img.setImageResource(R.drawable.record_animate_08); }else if (voiceValue > 10000.0 && voiceValue < 14000.0) { dialog_img.setImageResource(R.drawable.record_animate_09); }else if (voiceValue > 14000.0 && voiceValue < 17000.0) { dialog_img.setImageResource(R.drawable.record_animate_10); }else if (voiceValue > 17000.0 && voiceValue < 20000.0) { dialog_img.setImageResource(R.drawable.record_animate_11); }else if (voiceValue > 20000.0 && voiceValue < 24000.0) { dialog_img.setImageResource(R.drawable.record_animate_12); }else if (voiceValue > 24000.0 && voiceValue < 28000.0) { dialog_img.setImageResource(R.drawable.record_animate_13); }else if (voiceValue > 28000.0) { dialog_img.setImageResource(R.drawable.record_animate_14); } } //录音计时线程 private void mythread(){ recordThread = new Thread(ImgThread); recordThread.start(); } //录音线程 private Runnable ImgThread = new Runnable() { @Override public void run() { recodeTime = 0.0f; while (RECODE_STATE==RECORD_ING) { if (recodeTime >= MAX_TIME && MAX_TIME != 0) { imgHandle.sendEmptyMessage(0); }else{ try { Thread.sleep(200); recodeTime = 0.2; if (RECODE_STATE == RECORD_ING) { voiceValue = mr.getAmplitude(); imgHandle.sendEmptyMessage(1); } } catch (InterruptedException e) { e.printStackTrace(); } } } } Handler imgHandle = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case 0: //录音超过15秒自动停止 if (RECODE_STATE == RECORD_ING) { RECODE_STATE=RECODE_ED; if (dialog.isShowing()) { dialog.dismiss(); } try{ mr.stop(); voiceValue = 0.0; } catch (IOException e) { e.printStackTrace(); } if (recodeTime < 1.0) { showWarnToast(); takesong.setText("按住开始录音"); RECODE_STATE=RECORD_NO; }else{ takesong.setText("录音完成!点击重新录音"); songtime.setText(":" ((int)recodeTime)); filePath=Environment.getExternalStorageDirectory().toString() "/mwfile/" voicename; } } break; case 1: setDialogImage(); break; default: break; } } }; }; @SuppressLint("SimpleDateFormat") private void takePhoto() { // 执行拍照前,应该先判断SD卡是否存在 String SDState = Environment.getExternalStorageState(); if (SDState.equals(Environment.MEDIA_MOUNTED)) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);// "android.media.action.IMAGE_CAPTURE" /*** * 需要说明一下,以下操作使用照相机拍照,拍照后的图片会存放在相册中的 这里使用的这种方式有一个好处就是获取的图片是拍照后的原图 * 如果不实用ContentValues存放照片路径的话,拍照后获取的图片为缩略图不清晰 */ ContentValues values = new ContentValues(); photoUri = this.getContentResolver().insert( MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values); String name =""; SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_hhmmss"); Date curDate = new Date(System.currentTimeMillis());//获取当前时间 name= formatter.format(curDate) new Random().nextInt(1000) new Random().nextInt(100) ".jpg"; //文件夹mwfile String saveFilePath = Environment.getExternalStorageDirectory().toString() "/mwfile"; File dir = new File(saveFilePath); if(!dir.exists()){ dir.mkdirs(); } File file = new File(dir,name); photoUri = Uri.fromFile(file); intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, photoUri); /** ----------------- */ startActivityForResult(intent, 1); } else { Toast.makeText(this, "内存卡不存在", Toast.LENGTH_LONG).show(); } } @SuppressLint("SimpleDateFormat") private void takeVideo() { // 执行录像前,应该先判断SD卡是否存在 String SDState = Environment.getExternalStorageState(); if (SDState.equals(Environment.MEDIA_MOUNTED)) { Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);// "android.media.action.IMAGE_CAPTURE" /*** * 需要说明一下,以下操作使用录像机录像,拍录像后的视频会存放在文件中 这里使用的这种方式有一个好处就是获取的视频是原来的 * 如果不实用ContentValues存放视频路径的话,视频不清晰 */ ContentValues values = new ContentValues(); videoUri = this.getContentResolver().insert( MediaStore.Video.Media.EXTERNAL_CONTENT_URI, values); String name =""; SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd_hhmmss"); Date curDate = new Date(System.currentTimeMillis());//获取当前时间 name= formatter.format(curDate) new Random().nextInt(1000) new Random().nextInt(100) ".3gp"; //文件夹mwfile String saveFilePath = Environment.getExternalStorageDirectory().toString() "/mwfile"; File dir = new File(saveFilePath); if(!dir.exists()){ dir.mkdirs(); } File file = new File(dir,name); videoUri = Uri.fromFile(file); //设置视频大小10MB //intent.putExtra(android.provider.MediaStore.EXTRA_SIZE_LIMIT,10*1024*1024L); //设置视频时间 毫秒单位 //intent.putExtra(android.provider.MediaStore.EXTRA_DURATION_LIMIT, 45000); intent.putExtra(android.provider.MediaStore.EXTRA_OUTPUT, videoUri); //intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1); // set the video image quality to high /** ----------------- */ startActivityForResult(intent, 2); } else { Toast.makeText(this, "内存卡不存在", Toast.LENGTH_LONG).show(); } } @SuppressLint("SimpleDateFormat") @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); if (resultCode == RESULT_OK) { if (requestCode == 1) { filePath=photoUri.getPath(); Bitmap bm = BitmapFactory.decodeFile(filePath); photoview.setImageBitmap(bm);//不会变形 photolay.setVisibility(View.VISIBLE); //提交上传 Message msg = Message.obtain(); msg.what = 2; handler.sendMessageDelayed(msg, 200); }else if (requestCode == 2) { filePath =videoUri.toString(); if(filePath.indexOf("file://")>-1){ filePath=filePath.replace("file://", ""); } Bitmap bm = getVideoThumbnail(filePath); // if(filePath.indexOf("/")>-1){ // String filename=filePath.split("/")[filePath.split("/").length-1]; // filename=filename.replace(filename.substring(filename.lastIndexOf(".")),".jpg"); // saveMyBitmap(bm,filename); // Bitmap m_bm = BitmapFactory.decodeFile(Environment.getExternalStorageDirectory().toString() "/mwfile/" filename); // } videoview.setImageBitmap(bm);//不会变形 videolay.setVisibility(View.VISIBLE); //提交上传 Message msg = Message.obtain(); msg.what = 2; handler.sendMessageDelayed(msg, 200); }else if (requestCode == 4) { if(data!=null){ if(data.getStringExtra("path")!=null){ filePath = data.getStringExtra("path"); //提交上传 Message msg = Message.obtain(); msg.what = 2; handler.sendMessageDelayed(msg, 200); } } } }else{ if(data!=null){ if(data.getStringExtra("path")!=null){ filePath = data.getStringExtra("path"); //提交上传 Message msg = Message.obtain(); msg.what = 2; handler.sendMessageDelayed(msg, 200); } } } } //视频缩略图保存 public void saveMyBitmap(Bitmap mBitmap,String bitName) { //文件夹mwfile String saveFilePath = Environment.getExternalStorageDirectory().toString() "/mwfile"; File dir = new File(saveFilePath); if(!dir.exists()){ dir.mkdirs(); } File file = new File(dir,bitName); FileOutputStream fOut = null; try { fOut = new FileOutputStream(file); } catch (FileNotFoundException e) { e.printStackTrace(); } mBitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut); try { fOut.flush(); } catch (IOException e) { e.printStackTrace(); } try { fOut.close(); } catch (IOException e) { e.printStackTrace(); } } //视频缩略图 @SuppressLint("NewApi") public Bitmap getVideoThumbnail(String filePath) { Bitmap bitmap = null; MediaMetadataRetriever retriever = new MediaMetadataRetriever(); try { retriever.setDataSource(filePath); bitmap = retriever.getFrameAtTime(); } catch(IllegalArgumentException e) { e.printStackTrace(); } catch (RuntimeException e) { e.printStackTrace(); } finally { try { retriever.release(); } catch (RuntimeException e) { e.printStackTrace(); } } return bitmap; } @Override public boolean onKeyDown(int keyCode, KeyEvent event) { // 监听按下回退键 if (keyCode == KeyEvent.KEYCODE_BACK){ exitByDoubleClick(); // 调用双击退出函数 } return false; } private void exitByDoubleClick() { Timer timer = null; if (isExit == false) { isExit = true; // 准备退出 Toast.makeText(this, "再按一次退出程序", Toast.LENGTH_SHORT).show(); timer = new Timer(); timer.schedule(new TimerTask() { @Override public void run() { isExit = false; // 取消退出 } }, 2000); // 如果2秒钟内没有按下返回键,则启动定时器取消掉刚才执行的任务 } else { Consts.SESSIONID=""; Consts.user=null; Map<String,String> map = new LinkedHashMap<String, String>(); //用户帐号退出 //lm.loginout(new HomeActivityExit(), map); //强制退出 new Timer().schedule(new TimerTask() { @Override public void run() { HomeActivity.this.finish(); System.exit(0); } }, 500); } } private class HomeActivityExit extends RequestCallBack<String> { @Override public void onFailure(HttpException arg0, String arg1) {} @Override public void onSuccess(ResponseInfo<String> arg0) { // app退出回调,无处理 System.out.println("===="); HomeActivity.this.finish(); System.exit(0); } } //apk 更新 private void updateApk() { String str_new_version = bd.getString("app_version"); if (StringUtils.isNotNull(str_new_version)) { PackageManager pm = getPackageManager(); PackageInfo packInfo; try { packInfo = pm.getPackageInfo(getPackageName(), 0); String str_old_version = packInfo.versionName; if (Double.parseDouble(str_new_version) > Double.parseDouble(str_old_version)) { // 远程版本号大于本地版本号 String fileurl = Consts.URL "caseDoc/findCaseDaocFile/" 4 "/" -1 "/" -1; String filename = "mwoa.apk"; String savefilepath = FileUtil.getSaveFilePath("apk"); boolean down_success = HttpDown.downMeeting_sign(fileurl, filename, savefilepath); if (down_success) { FileUtil.openFile(new File(savefilepath, filename), this); } } } catch (NameNotFoundException e) { e.printStackTrace(); } } } public class FileUploadRequestCallBack extends RequestCallBack<String> { private Activity activity; public FileUploadRequestCallBack(Activity activity){ this.activity=activity; } @Override public void onFailure(HttpException arg0, String arg1) { } @Override public void onSuccess(ResponseInfo<String> responseInfo) { String json = responseInfo.result; progressDialog.cancel(); if(json.length()>0 && json.indexOf(".")>-1){ Toast.makeText(activity, "上传成功", Toast.LENGTH_LONG).show(); }else{ Toast.makeText(activity, "上传失败", Toast.LENGTH_LONG).show(); } } } }
好例子网口号:伸出你的我的手 — 分享!
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论