Android中常用方法集锦:
- EditText ed = new EditText(this);
- Editable eb = ed.getEditableText();
- //获取光标位置
- int position = ed.getSelectionStart();
- //指定位置插入字符
- eb.insert(position, "XXX");
- //插入图片
- //定义图片所占字节数(“Tag”的长度)
- SpannableString ss = new SpannableString("Tag");
- //定义插入图片
- Drawable drawable = getResources().getDrawable(R.drawable.icon);
- ss.setSpan(new ImageSpan(drawable,ImageSpan.ALIGN_BASELINE), 0, ss.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
- drawable.setBounds(2, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
- //插入图片
- eb.insert(position, ss);
- //设置可输入最大字节数
- ed.setFilters(new InputFilter[]{ new InputFilter.LengthFilter(10)});
- //拉起lancher桌面
- Intent i = new Intent(Inten.ACTION_MAIN);
- i.addCategory(Inten.CATEGORT_HOME);
- startActivity(i);
- //去掉List拖动时的阴影
- list.setCacheColorHint(0);
- // 通过资源名称获取资源id
- 1.Field f= (Field)R.drawable.class.getDeclaredField("Name");
- int id=f.getInt(R.drawable.class);
- 2.int id = getResources().getIdentifier(getPackageName()+":drawable/Name", null,null);
- // timer TimerTask用法
- mTimer = new Timer();
- mTimerTask = new TimerTask() {
- @Override
- public void run() {
- mProgress.setProgress(mMediaPlayer.getCurrentPosition());
- mHandler.sendEmptyMessage(0);
- }
- };
- mTimer.schedule(mTimerTask, 0, 1000);
- // 在a.apk启动b.apk的实现
- //1.a.apk实现
- Intent mIntent = new Intent("package.MainActivity");
- startActivity(mIntent);
- finish();
- // b.apk在mainfest中配置
- <intent-filter>
- <action android:name="package.MainActivity" />
- <category android:name="android.intent.category.DEFAULT" />
- </intent-filter>
- //Android 获取存储卡路径和空间使用情况
- /** 获取存储卡路径 */
- File sdcardDir=Environment.getExternalStorageDirectory();
- /** StatFs 看文件系统空间使用情况 */
- StatFs statFs=new StatFs(sdcardDir.getPath());
- /** Block 的 size*/
- Long blockSize=statFs.getBlockSize();
- /** 总 Block 数量 */
- Long totalBlocks=statFs.getBlockCount();
- /** 已使用的 Block 数量 */
- Long availableBlocks=statFs.getAvailableBlocks();
- //Android 为Activity屏幕的标题添加图标
- Window win = getWindow();
- win.requestFeature(Window.FEATURE_LEFT_ICON);
- setContentView(R.layout.mylayout);
- win.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.icon);
- //图片缩放
- 1.ThumbnailUtils.extractThumbnail(bitmap,200,100)
- 2. //使用Bitmap加Matrix来缩放
- public static Drawable resizeImage(Bitmap bitmap, int w, int h)
- {
- Bitmap BitmapOrg = bitmap;
- int width = BitmapOrg.getWidth();
- int height = BitmapOrg.getHeight();
- int newWidth = w;
- int newHeight = h;
- float scaleWidth = ((float) newWidth) / width;
- float scaleHeight = ((float) newHeight) / height;
- Matrix matrix = new Matrix();
- matrix.postScale(scaleWidth, scaleHeight);
- // if you want to rotate the Bitmap
- // matrix.postRotate(45);
- Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 0, 0, width,
- height, matrix, true);
- return new BitmapDrawable(resizedBitmap);
- }
- 3. //使用BitmapFactory.Options的inSampleSize参数来缩放
- public static Drawable resizeImage2(String path,
- int width,int height)
- {
- BitmapFactory.Options options = new BitmapFactory.Options();
- options.inJustDecodeBounds = true;//不加载bitmap到内存中
- BitmapFactory.decodeFile(path,options);
- int outWidth = options.outWidth;
- int outHeight = options.outHeight;
- options.inDither = false;
- options.inPreferredConfig = Bitmap.Config.ARGB_8888;
- options.inSampleSize = 1;
- if (outWidth != 0 && outHeight != 0 && width != 0 && height != 0)
- {
- int sampleSize=(outWidth/width+outHeight/height)/2;
- Log.d(tag, "sampleSize = " + sampleSize);
- options.inSampleSize = sampleSize;
- }
- options.inJustDecodeBounds = false;
- return new BitmapDrawable(BitmapFactory.decodeFile(path, options));
- }
1.使用AlertDialog的setContentView()方法抛出异常:E/AndroidRuntime( 408): android.util.AndroidRuntimeException: requestFeature() must be called before
解决:出现上面异常的原因:由于dialog.show()之前调用了dialog.setContentView()了,正确的应该是dialog.show()之后调用dialog.setContentView()
2.AlertDialog背景无法填充满
解决:dialog.setIcon(android.R.drawable.ic_dialog_alert);
dialog.setTitle("可选的AlertDialog");
dialog.setView(myListViewLayout, 0, 0, 0, 0);//为自定义View
dialog.show();
/**
* 照相功能
*/
private void cameraMethod() {
Intent imageCaptureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
strImgPath = Environment.getExternalStorageDirectory().toString() + "/CONSDCGMPIC/";//存放照片的文件夹
String fileName = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date()) + ".jpg";//照片命名
File out = new File(strImgPath);
if (!out.exists()) {
out.mkdirs();
}
out = new File(strImgPath, fileName);
strImgPath = strImgPath + fileName;//该照片的绝对路径
Uri uri = Uri.fromFile(out);
imageCaptureIntent.putExtra(MediaStore.EXTRA_OUTPUT, uri);//指定照片存放路径,默认是在/mnt/sdcard/DICM/Camera/目录下
imageCaptureIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 1);
startActivityForResult(imageCaptureIntent, RESULT_CAPTURE_IMAGE);
}
}
9、 拍摄视频
private void videoMethod() {
Intent intent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
intent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);
startActivityForResult(intent, REQUEST_CODE_TAKE_VIDEO);
}
/**
* 录音功能
*/
private void soundRecorderMethod() {
Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
intent.setType("audio/amr");
startActivityForResult(intent, RESULT_CAPTURE_RECORDER_SOUND);
}
// you need config the mail app in your android moble first,and the mail will send by the mail app. and there are one big bug:
//you can't send the mail Silently and you need to click the send button
//第一种方法是调用了系统的mail app,你首先要配置系统的mail app,但是这个方法的最大问题是,你运行这个方法后它并不会默认的发送邮件,而是弹出mail的app界面,你需要手动的点击发送
public int sendMailByIntent() {
String[] reciver = new String[] { "181712000@qq.com" };
String[] mySbuject = new String[] { "test" };
String myCc = "cc";
String mybody = "测试Email Intent";
Intent myIntent = new Intent(android.content.Intent.ACTION_SEND);
myIntent.setType("plain/text");
myIntent.putExtra(android.content.Intent.EXTRA_EMAIL, reciver);
myIntent.putExtra(android.content.Intent.EXTRA_CC, myCc);
myIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, mySbuject);
myIntent.putExtra(android.content.Intent.EXTRA_TEXT, mybody);
startActivity(Intent.createChooser(myIntent, "mail test"));
return 1;
}
/*this method can't be used in android mobile successful,but it can run normally in PC.
Because it will cause the java.lang.NoClassDefFoundError: javax.activation.DataHandler error
May be there are some way to solove it ......there are always javax package not found in android virtual mobile.
By the way ,the method use Apache mail jar
*/
//第二种,是调用了apache的common库,在pc上可以正常运行,但是在android虚拟机中会报错java.lang.NoClassDefFoundError: javax.activation.DataHandler error //javax包无法找到,我看了下这个问题还是比较普遍的,大家普遍表示虚拟机是被阉割的版本,javax好像存在不全,这个实际上就无法运行
public int sendMailByApache() {
try {
HtmlEmail email = new HtmlEmail();
// 这里是发送服务器的名字
email.setHostName("smtp.gmail.com");
// 编码集的设置
email.setTLS(true);
email.setSSL(true);
email.setCharset("gbk");
// 收件人的邮箱
email.addTo("181712000@qq.com");
// 发送人的邮箱
email.setFrom("wcf0000@gmail.com");
// 如果需要认证信息的话,设置认证:用户名-密码。分别为发件人在邮件服务器上的注册名称和密码
email.setAuthentication("wcf1000", "00000");
email.setSubject("测试Email Apache");
// 要发送的信息
email.setMsg("测试Email Apache");
// 发送
email.send();
} catch (EmailException e) {
// TODO Auto-generated catch block
Log.i("IcetestActivity", e.getMessage());
}
return 1;
}
/*
* this method use javamail for android ,it is a good jar,
* you can see the demo in http://www.jondev.net/articles/Sending_Emails_without_User_Intervention_(no_Intents)_in_Android
* and you also need three jars ,which I offered in attachement
*
* */
//第三种,实际是javamail有人做了移植,专门为android做了开发,这下就比较好了,网上的demo代码也比较到位,只有一个问题,就是要自己添加一个mail.java,而且对stmp要手动添加。 //其实理论上还应该有一种,自己实现smtp服务器,全程采用socket编程,直接与目标服务器交流,这个win下面我写过,但是android下就算了,而且长期来讲面临着smtp服务器以后会被进行方向查询,以提高安全性。
public int sendMailByJavaMail() {
Mail m = new Mail("wcfXXXX@gmail.com", "XXXXX");
m.set_debuggable(true);
String[] toArr = {
"18170000@qq.com"};m.set_to(toArr);
m.set_from("18170000@qq.com");
m.set_subject("This is an email sent using icetest from an Android device");
m.setBody("Email body. test by Java Mail");
try {
//m.addAttachment("/sdcard/filelocation");
if(m.send()) {
Log.i("IcetestActivity","Email was sent successfully.");
} else {
Log.i("IcetestActivity","Email was sent failed.");
}
} catch (Exception e) {
// Toast.makeText(MailApp.this,
// "There was a problem sending the email.",
// Toast.LENGTH_LONG).show();
Log.e("MailApp", "Could not send email", e);
}
return 1;
}
}