实例介绍
【实例简介】
【实例截图】
【实例截图】
【核心代码】
package com.ior.activity; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.Date; import android.app.Activity; import android.app.AlertDialog; import android.content.ContentResolver; import android.content.ContentValues; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.content.res.Resources; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.drawable.BitmapDrawable; import android.graphics.drawable.Drawable; import android.net.Uri; import android.os.Bundle; import android.os.Environment; import android.provider.MediaStore; import android.support.v4.content.CursorLoader; import android.text.Editable; import android.text.Html; import android.text.Html.ImageGetter; import android.util.DisplayMetrics; import android.view.KeyEvent; import android.view.View; import android.view.View.OnClickListener; import android.view.WindowManager; import android.view.inputmethod.InputMethodManager; import android.widget.Button; import android.widget.EditText; import android.widget.Toast; import com.ior.dao.DemandDAO; import com.ior.entity.Demand; import com.ior.service.CheckNetworkState; import com.ior.service.LoginService; import com.ior.service.SubmitDemandService; import com.ior.util.ATManager; public class NewDemandActivity extends Activity { /** 公有数据 */ public final static String EXTRA_FILE_CHOOSER = "file_chooser"; /** 私有数据 */ private EditText titleET; // 标题 private EditText contentET; // 内容 private Button attachmentButton; private Button pictureButton; private Button recordButton; private Button saveButton; private Button insertImgButton; // 保存按钮 private ArrayList<String> filepathes = new ArrayList<String>(); private int screeHeight; private int screeWidth; private float MAXSIZE; private ContentResolver contentresolver; private Intent fileChooserIntent; private final int AttachmentCode = 501; private final int INSERTIMG_CODE = 502; private final int PictureButtonCode = 504; private final int RecordButtonCode = 503; // 有没有id private long id = 0; private SimpleDateFormat simpledateformat; private DemandDAO dao; private String content; private String title; private String status = "新建"; private String time; protected void onCreate(Bundle savedInstanceState) { initActivity(savedInstanceState); setListener(); } @Override protected void onResume() { super.onResume(); } private void setListener() { saveButton = (Button) findViewById(R.id.savedemand); attachmentButton = (Button) findViewById(R.id.attachment); pictureButton = (Button) findViewById(R.id.takepicture); insertImgButton = (Button) findViewById(R.id.insertimg); recordButton = (Button) findViewById(R.id.record); titleET = (EditText) findViewById(R.id.editTitle); contentET = (EditText) findViewById(R.id.editContent); // 监听 saveButton.setOnClickListener(new SaveButtonListener()); attachmentButton.setOnClickListener(new AttachmentButtonListener()); pictureButton.setOnClickListener(new PictureButtonListener()); recordButton.setOnClickListener(new RecordButtonListener()); insertImgButton.setOnClickListener(new InsertImgButtonListener()); } private void initActivity(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.newdemand); ATManager.addActivity(this); getWindow().setSoftInputMode( WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN); /** DisplayMetrics获取屏幕信息 */ DisplayMetrics displayMetrics = new DisplayMetrics(); getWindowManager().getDefaultDisplay().getMetrics(displayMetrics); screeWidth = displayMetrics.widthPixels; screeHeight = displayMetrics.heightPixels; // 本应用程序最高可用内存是多少 int maxMemory = (int) (Runtime.getRuntime().maxMemory() / 1024); MAXSIZE = maxMemory / 8; dao = new DemandDAO(getApplicationContext()); contentresolver = NewDemandActivity.this.getContentResolver(); } /** 附件 */ private class AttachmentButtonListener implements OnClickListener { @Override public void onClick(View v) { if (Environment.getExternalStorageState().equals( Environment.MEDIA_MOUNTED)) { startChooseFileActivity(); startActivityForResult(fileChooserIntent, AttachmentCode); } else { toast(getText(R.string.sdcard_unmonted_hint)); return; } } private void startChooseFileActivity() { fileChooserIntent = new Intent(NewDemandActivity.this, FileChooserActivity.class); } } // 插图 private class InsertImgButtonListener implements OnClickListener { @Override public void onClick(View v) { Intent intent = new Intent(); intent.setType("image/*"); intent.setAction(Intent.ACTION_GET_CONTENT); startActivityForResult(intent, INSERTIMG_CODE); } } public void onActivityResult(int requestCode, int resultCode, Intent data) { if (resultCode == RESULT_CANCELED) { return; } // 附件 if (resultCode == RESULT_OK && requestCode == AttachmentCode) { // 获取路径名 String filePath = data.getStringExtra(EXTRA_FILE_CHOOSER); if (filePath != null) { toast("选择文件为: " filePath); filepathes.add(filePath); Uri uri = getDrawableURI(R.drawable.ic_file); Editable eb = contentET.getEditableText(); // 获得光标所在位置 int startPosition = contentET.getSelectionStart(); eb.insert( startPosition, Html.fromHtml("<br/><a href='" uri.toString() "'>附件<img src='" uri.toString() "'/></a><br/>", imageGetter, null)); } else { toast(getText(R.string.open_file_failed)); } } // 插图 if (resultCode == RESULT_OK && requestCode == INSERTIMG_CODE) { Uri uri = data.getData(); if (uri != null) filepathes.add(getRealPathFromURI(uri)); Editable eb = contentET.getEditableText(); // 获得光标所在位置 int startPosition = contentET.getSelectionStart(); eb.insert( startPosition, Html.fromHtml("<br/><img src='" uri.toString() "'/><br/>", imageGetter, null)); } // 拍照 if (resultCode == RESULT_OK && requestCode == PictureButtonCode) { Uri uri = data.getData(); if (uri != null) filepathes.add(getRealPathFromURI(uri)); System.out.println("拍照:" uri); String filestr = getAbsoluteImagePath(uri); System.out.println("filestr" filestr); Editable eb = contentET.getEditableText(); // 获得光标所在位置 int startPosition = contentET.getSelectionStart(); eb.insert( startPosition, Html.fromHtml("<br/><img src='" uri.toString() "'/><br/>", imageGetter, null)); } // 录音 if (resultCode == RESULT_OK && requestCode == RecordButtonCode) { Uri recordUri = data.getData(); if (recordUri != null) filepathes.add(getRealPathFromURI(recordUri)); System.out.println("录音:" recordUri); String filestr = getAbsoluteImagePath(recordUri); System.out.println("filestr" filestr); Uri uri = getDrawableURI(R.drawable.record_icon); Editable eb = contentET.getEditableText(); // 获得光标所在位置 int startPosition = contentET.getSelectionStart(); eb.insert( startPosition, Html.fromHtml("<br/><a href='" uri.toString() "'>录音文件<img src='" uri.toString() "'/></a><br/>", imageGetter, null)); } } /** 获取项目资源的URI */ private Uri getDrawableURI(int resourcesid) { Resources r = getResources(); Uri uri = Uri.parse(ContentResolver.SCHEME_ANDROID_RESOURCE "://" r.getResourcePackageName(resourcesid) "/" r.getResourceTypeName(resourcesid) "/" r.getResourceEntryName(resourcesid)); return uri; } private ImageGetter imageGetter = new ImageGetter() { @Override public Drawable getDrawable(String source) { try { Uri uri = Uri.parse(source); Bitmap bitmap = getimage(contentresolver, uri); return getMyDrawable(bitmap); } catch (Exception e) { e.printStackTrace(); return null; } } }; private static Drawable getMyDrawable(Bitmap bitmap) { Drawable drawable = new BitmapDrawable(bitmap); int imgHeight = drawable.getIntrinsicHeight(); int imgWidth = drawable.getIntrinsicWidth(); drawable.setBounds(0, 0, imgWidth, imgHeight); return drawable; } private Bitmap getimage(ContentResolver cr, Uri uri) { try { Bitmap bitmap = null; BitmapFactory.Options newOpts = new BitmapFactory.Options(); // options.inJustDecodeBounds=true,图片不加载到内存中 newOpts.inJustDecodeBounds = true; BitmapFactory.decodeStream(cr.openInputStream(uri), null, newOpts); newOpts.inJustDecodeBounds = false; int imgWidth = newOpts.outWidth; int imgHeight = newOpts.outHeight; // 缩放比,1表示不缩放 int scale = 1; if (imgWidth > imgHeight && imgWidth > screeWidth) { scale = (int) (imgWidth / screeWidth); } else if (imgHeight > imgWidth && imgHeight > screeHeight) { scale = (int) (imgHeight / screeHeight); } newOpts.inSampleSize = scale;// 设置缩放比例 bitmap = BitmapFactory.decodeStream(cr.openInputStream(uri), null, newOpts); return bitmap; } catch (Exception e) { System.out.println("文件不存在"); return null; } } private void toast(CharSequence hint) { Toast.makeText(this, hint, Toast.LENGTH_SHORT).show(); } /** 拍照 */ class PictureButtonListener implements OnClickListener { @Override public void onClick(View v) { Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE); startActivityForResult(intent, PictureButtonCode); } } /** 录音 */ class RecordButtonListener implements OnClickListener { @Override public void onClick(View v) { // 调用Android自带的音频录制应用 Intent intent = new Intent( MediaStore.Audio.Media.RECORD_SOUND_ACTION); startActivityForResult(intent, RecordButtonCode); } } class SaveButtonListener implements OnClickListener { @Override public void onClick(View v) { saveDemand(); } } private void saveDemand() { hideSoftInputWin(); content = contentET.getText().toString(); title = titleET.getText().toString(); if (title == null || title.equals("") || content == null || content.equals("")) { prompt("保存失败", "标题或内容为空"); return; } if (content.length() > MAXSIZE) { Toast.makeText(getApplicationContext(), "数据太大,保存失败", 1).show(); return; } if (id == 0) { insert(); } else { update(); } uploadDataToWeb(); } /** 数据同步到云端 */ private void uploadDataToWeb() { if (CheckNetworkState.isWifi(getApplicationContext())) { startService(); loadsqlite(); backtoMainTab(); } else { prompt2("数据同步提示", "当前不是Wifi网络,是否提交数据到云端服务器"); } } private void backtoMainTab() { Intent intent = new Intent(NewDemandActivity.this, MainTabActivity.class); titleET.setText(""); contentET.setText(""); startActivity(intent); } /** 插入数据 */ private void insert() { // 富文本转为html Editable eb = contentET.getEditableText(); content = Html.toHtml(eb); time = getTime(); dao.open(); ContentValues initValues = new ContentValues(); initValues.put("title", title); initValues.put("content", content); initValues.put("createtime", time); initValues.put("status", status); initValues.put("fileuri", filepathes.toString()); dao.insertDemand(initValues); dao.close(); Toast.makeText(getApplicationContext(), "需求数据已经保存", 1).show(); } // 得到当前时间 private String getTime() { this.simpledateformat = new SimpleDateFormat("yyyy年MM月dd日HH时:mm分:ss秒 "); return this.simpledateformat.format(new Date()); } private void update() { // 富文本转为html Editable eb = contentET.getEditableText(); content = Html.toHtml(eb); time = getTime(); dao.open(); ContentValues initValues = new ContentValues(); initValues.put("title", title); initValues.put("content", content); initValues.put("createtime", time); initValues.put("status", status); initValues.put("fileuri", filepathes.toString()); dao.update(initValues, id); dao.close(); Toast.makeText(getApplicationContext(), "文件已经保存", 1).show(); } @Override protected void onPause() { super.onPause(); hideSoftInputWin(); } /** 退出程序 */ @Override protected void onDestroy() { ATManager.exitClient(getApplicationContext()); super.onDestroy(); } private void hideSoftInputWin() { /** 隐藏虚拟键盘 */ InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE); imm.hideSoftInputFromWindow(contentET.getWindowToken(), 0); } /** 返回键 退出 */ @Override public boolean onKeyDown(int keyCode, KeyEvent event) { if (keyCode == KeyEvent.KEYCODE_BACK) { exit(); return true; } else { return super.onKeyDown(keyCode, event); } } private void exit() { new AlertDialog.Builder(this).setTitle("退出").setMessage("你确定要退出程序吗?") .setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { saveDemand(); onDestroy(); // 退出程序 } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }).show(); } /** 提示 */ private void prompt(String title, String proinfo) { new AlertDialog.Builder(this).setTitle(title).setMessage(proinfo) .setPositiveButton("确定", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { } }).show(); } /** 提示 */ private void prompt2(String title, String proinfo) { new AlertDialog.Builder(this).setTitle(title).setMessage(proinfo) .setPositiveButton("同步", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { startService(); loadsqlite(); backtoMainTab(); } }) .setNegativeButton("取消", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int which) { loadsqlite(); backtoMainTab(); } }).show(); } /** 启动同步服务 */ private void startService() { Intent intent = new Intent(this, SubmitDemandService.class); getApplicationContext().startService(intent); } private void loadsqlite() { Demand demand = new Demand(); String author = LoginActivity.sharedPreferences.getString("name", ""); demand.setAuthor(author); demand.setTime(time); demand.setTitle(title); demand.setStatus(status); LoginService loginService = new LoginService(); // 这里不是真的校验用户信息,是重新给 LoginService.demandlistSQLITE 赋值 loginService.checkUser(getApplicationContext()); } private String getAbsoluteImagePath(Uri uri) { String[] proj = { MediaStore.Images.Media.DATA }; Cursor cursor = managedQuery(uri, proj, null, null, null); int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } /** 从uri获取文件路径,uri以content开始 */ private String getRealPathFromURI(Uri contentUri) { String[] proj = { MediaStore.Images.Media.DATA }; CursorLoader loader = new CursorLoader(getApplicationContext(), contentUri, proj, null, null, null); Cursor cursor = loader.loadInBackground(); int column_index = cursor .getColumnIndexOrThrow(MediaStore.Images.Media.DATA); cursor.moveToFirst(); return cursor.getString(column_index); } }
好例子网口号:伸出你的我的手 — 分享!
小贴士
感谢您为本站写下的评论,您的评论对其它用户来说具有重要的参考价值,所以请认真填写。
- 类似“顶”、“沙发”之类没有营养的文字,对勤劳贡献的楼主来说是令人沮丧的反馈信息。
- 相信您也不想看到一排文字/表情墙,所以请不要反馈意义不大的重复字符,也请尽量不要纯表情的回复。
- 提问之前请再仔细看一遍楼主的说明,或许是您遗漏了。
- 请勿到处挖坑绊人、招贴广告。既占空间让人厌烦,又没人会搭理,于人于己都无利。
关于好例子网
本站旨在为广大IT学习爱好者提供一个非营利性互相学习交流分享平台。本站所有资源都可以被免费获取学习研究。本站资源来自网友分享,对搜索内容的合法性不具有预见性、识别性、控制性,仅供学习研究,请务必在下载后24小时内给予删除,不得用于其他任何用途,否则后果自负。基于互联网的特殊性,平台无法对用户传输的作品、信息、内容的权属或合法性、安全性、合规性、真实性、科学性、完整权、有效性等进行实质审查;无论平台是否已进行审查,用户均应自行承担因其传输的作品、信息、内容而可能或已经产生的侵权或权属纠纷等法律责任。本站所有资源不代表本站的观点或立场,基于网友分享,根据中国法律《信息网络传播权保护条例》第二十二与二十三条之规定,若资源存在侵权或相关问题请联系本站客服人员,点此联系我们。关于更多版权及免责申明参见 版权及免责申明
网友评论
我要评论