Android-中常用方法集锦

Android中常用方法集锦:

Java代码  收藏代码
  1.           
  2.         EditText ed = new EditText(this);  
  3.         Editable eb = ed.getEditableText();  
  4.   
  5.         //获取光标位置  
  6.         int position = ed.getSelectionStart();  
  7.   
  8.         //指定位置插入字符  
  9.         eb.insert(position, "XXX");  
  10.   
  11.   
  12.         //插入图片  
  13.         //定义图片所占字节数(“Tag”的长度)  
  14.         SpannableString ss = new SpannableString("Tag");  
  15.         //定义插入图片  
  16.         Drawable drawable = getResources().getDrawable(R.drawable.icon);  
  17.         ss.setSpan(new ImageSpan(drawable,ImageSpan.ALIGN_BASELINE), 0, ss.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);  
  18.         drawable.setBounds(20, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());  
  19.         //插入图片  
  20.         eb.insert(position, ss);  
  21.   
  22.   
  23.         //设置可输入最大字节数  
  24.         ed.setFilters(new InputFilter[]{new InputFilter.LengthFilter(10)});  
  25.   
  26.   
  27.         //拉起lancher桌面  
  28.         Intent i = new Intent(Inten.ACTION_MAIN);  
  29.        i.addCategory(Inten.CATEGORT_HOME);  
  30.        startActivity(i);  
  31.   
  32.        //去掉List拖动时的阴影  
  33.         list.setCacheColorHint(0);        
  34.          
  35.       // 通过资源名称获取资源id   
  36.         1.Field f= (Field)R.drawable.class.getDeclaredField("Name");  
  37.         int id=f.getInt(R.drawable.class);  
  38.      2.int id = getResources().getIdentifier(getPackageName()+":drawable/Name"null,null);  
  39.        // timer TimerTask用法  
  40.         mTimer = new Timer();  
  41.         mTimerTask = new TimerTask() {  
  42.             @Override  
  43.             public void run() {  
  44.                 mProgress.setProgress(mMediaPlayer.getCurrentPosition());  
  45.                 mHandler.sendEmptyMessage(0);  
  46.             }  
  47.         };  
  48.         mTimer.schedule(mTimerTask, 01000);  
  49.         // 在a.apk启动b.apk的实现  
  50.          //1.a.apk实现  
  51.     Intent mIntent = new Intent("package.MainActivity");   
  52.     startActivity(mIntent);  
  53.     finish();   
  54.         // b.apk在mainfest中配置  
  55.             <intent-filter>  
  56.                 <action android:name="package.MainActivity" />  
  57.                 <category android:name="android.intent.category.DEFAULT" />  
  58.             </intent-filter>  
  59. //Android 获取存储卡路径和空间使用情况  
  60.        /** 获取存储卡路径 */   
  61. File sdcardDir=Environment.getExternalStorageDirectory();   
  62. /** StatFs 看文件系统空间使用情况 */   
  63. StatFs statFs=new StatFs(sdcardDir.getPath());   
  64. /** Block 的 size*/   
  65. Long blockSize=statFs.getBlockSize();   
  66. /** 总 Block 数量 */   
  67. Long totalBlocks=statFs.getBlockCount();   
  68. /** 已使用的 Block 数量 */   
  69. Long availableBlocks=statFs.getAvailableBlocks();   
  70.   
  71.   
  72. //Android 为Activity屏幕的标题添加图标  
  73. Window win = getWindow();  
  74.   win.requestFeature(Window.FEATURE_LEFT_ICON);  
  75.   setContentView(R.layout.mylayout);  
  76.   win.setFeatureDrawableResource(Window.FEATURE_LEFT_ICON, R.drawable.icon);  
  77. //图片缩放  
  78. 1.ThumbnailUtils.extractThumbnail(bitmap,200,100)  
  79. 2.  //使用Bitmap加Matrix来缩放     
  80.      public static Drawable resizeImage(Bitmap bitmap, int w, int h)     
  81.      {      
  82.         Bitmap BitmapOrg = bitmap;      
  83.          int width = BitmapOrg.getWidth();      
  84.          int height = BitmapOrg.getHeight();      
  85.          int newWidth = w;      
  86.          int newHeight = h;      
  87.      
  88.          float scaleWidth = ((float) newWidth) / width;      
  89.          float scaleHeight = ((float) newHeight) / height;      
  90.      
  91.          Matrix matrix = new Matrix();      
  92.          matrix.postScale(scaleWidth, scaleHeight);      
  93.          // if you want to rotate the Bitmap        
  94.          // matrix.postRotate(45);        
  95.          Bitmap resizedBitmap = Bitmap.createBitmap(BitmapOrg, 00, width,      
  96.                          height, matrix, true);      
  97.          return new BitmapDrawable(resizedBitmap);      
  98.      }    
  99. 3//使用BitmapFactory.Options的inSampleSize参数来缩放     
  100.      public static Drawable resizeImage2(String path,    
  101.              int width,int height)     
  102.      {    
  103.          BitmapFactory.Options options = new BitmapFactory.Options();    
  104.          options.inJustDecodeBounds = true;//不加载bitmap到内存中     
  105.          BitmapFactory.decodeFile(path,options);     
  106.          int outWidth = options.outWidth;    
  107.          int outHeight = options.outHeight;    
  108.          options.inDither = false;    
  109.          options.inPreferredConfig = Bitmap.Config.ARGB_8888;    
  110.          options.inSampleSize = 1;    
  111.              
  112.          if (outWidth != 0 && outHeight != 0 && width != 0 && height != 0)     
  113.          {    
  114.              int sampleSize=(outWidth/width+outHeight/height)/2;    
  115.              Log.d(tag, "sampleSize = " + sampleSize);    
  116.              options.inSampleSize = sampleSize;    
  117.          }    
  118.          
  119.         options.inJustDecodeBounds = false;    
  120.          return new BitmapDrawable(BitmapFactory.decodeFile(path, options));         
  121.      }    

 

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();

 

 

1、设置应用当前语言
     /**
      * 设置应用当前语言,如: lan=""(表示当前系统语言), lan="zh "(中文),lan=" ja"(日语)
      * @param lan
      */
     public void setLanguage(String lan) {
          Locale locale = new Locale(lan);
          Locale. setDefault(locale);
          Configuration config = new Configuration();
          config. locale = locale;
          getBaseContext().getResources().updateConfiguration(config,
                   getBaseContext().getResources().getDisplayMetrics());
     }
2、重启Activity
    /**
      * 重启Activity,很是巧妙
      */
      public void reload() {
 
          Intent intent = getIntent();
          overridePendingTransition(0, 0);
          intent.addFlags(Intent. FLAG_ACTIVITY_NO_ANIMATION );
          finish();
 
          overridePendingTransition(0, 0);
          startActivity(intent);
     }
3、更改系统亮度
     /**
      * 更改系统亮度
      * @param value
      */
     public void changeBrightness (int value) {
          System. putInt(getContentResolver(), System.SCREEN_BRIGHTNESS, value);
          LayoutParams layoutpars = getWindow().getAttributes();
          layoutpars. screenBrightness = value / ( float) 255;
          getWindow().setAttributes(layoutpars);
     }
4、设置全屏
     /**
      * 设置全屏
      */
    protected void setFullScreen () {
       getWindow().requestFeature(Window.FEATURE_NO_TITLE );
       getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams. FLAG_FULLSCREEN);
     }
5、打开网页(recommended_url在strings.xml文件中配置的,如:http://www.baidu.com
        Button buttonRecommended = (Button)findViewById(R.id.buttonRecommended );
        buttonRecommended.setOnClickListener( new OnClickListener() {
               @Override
               public void onClick(View v) {
                    final Intent intent = new Intent(Intent .ACTION_VIEW , Uri.parse(getString(R.string.recommended_url)));
                  startActivity(intent);
              }
        });
 
6、打开系统相册
     private void picture () {
           final Intent imageIntent = new Intent(Intent.ACTION_PICK , android.provider.MediaStore.Images.Media.INTERNAL_CONTENT_URI );
          imageIntent.setType( "image/*");
          startActivityForResult(imageIntent, REQUEST_CODE_CAMERA);
     }
7、启动拍照
     public void startCamera () {
           filename =( imageList.size() + 1) + ".jpg";
           pictureUri = Uri. fromFile(new File(fileUri, filename));
           if ( sp == null)
               sp = getPreferences( MODE_PRIVATE);
          Editor editor = sp.edit();
          editor.putString( "pictureUri", pictureUri.toString());
          editor.commit();
          Intent intent = new Intent();
          intent.setAction( "android.media.action.IMAGE_CAPTURE" );
          intent.putExtra(MediaStore. EXTRA_OUTPUT, pictureUri);
          startActivityForResult(intent, REQUEST_CODE_CAMERA_SHOOT );
     }

       /**

        * 照相功能

         */

        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);

 

        }

8、启动录像
   public void startVideo(){
        filename ="video_template" +System.currentTimeMillis ()+".mp4" ;
        videoUri=Uri. fromFile( new File(fileUri ,filename ));
        if( sp== null){
             sp=getPreferences( MODE_PRIVATE);
        }
        Editor editor= sp.edit();
        editor.putString( "videoUri"videoUri .toString());
       
        Intent mIntent = null;
        mIntent= new Intent();
        mIntent.setAction("android.media.action.VIDEO_CAPTURE" );
        //mIntent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri);
        //mIntent = new Intent(MediaStore.ACTION_VIDEO_CAPTURE);
        //mIntent.putExtra(MediaStore.EXTRA_OUTPUT, videoUri);//指定照片存放路径,默认是在/mnt/sdcard/DICM/Camera/目录下,
        //     
        //mIntent.putExtra("android.intent.extra.sizeLimit", 999999999L);
        //mIntent.putExtra(MediaStore.EXTRA_VIDEO_QUALITY, 0);// 0表示low Quality
        // mIntent.putExtra("android.intent.extra.durationLimit", 3600);
        startActivityForResult(mIntent, REQUEST_CODE_VIDEO_SHOOT );

   }

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);

        }

10、启动录音

   /**

         * 录音功能

         */

        private void soundRecorderMethod() {

                Intent intent = new Intent(Intent.ACTION_GET_CONTENT);

                intent.setType("audio/amr");

                startActivityForResult(intent, RESULT_CAPTURE_RECORDER_SOUND);

        }

 
11、取得系统中所有的Audio文件(AudioInfo是自定义的bean类):
     public AudioInfo getMp3Info(String audioPath) {
              String selection = MediaStore.Audio.Media.DATA + " like ?" ; // like String path="/mntsdcard/music";
              String[] selectionArgs = { "%"+ audioPath +"%"};
              String[] projection = {
                         // MediaStore.Audio.Media._ID,
                        MediaStore.Audio.Media. TITLE,
                        MediaStore.Audio.Media. ARTIST,
                        MediaStore.Audio.Media. ALBUM,
                        MediaStore.Audio.Media. DURATION,
                        MediaStore.Audio.Media. SIZE,
                        MediaStore.Audio.Media. DISPLAY_NAME,
                        MediaStore.Audio.Media. DATA  // -->File Full Path
              };
              Cursor cursor = null;
              cursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI ,projection, selection, selectionArgs, null);
               //cursor = managedQuery(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,projection, null, null, null);//select all audio file 
               //Cursor cursor2 =query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI, null,null, null, MediaStore.Audio.Media.DEFAULT_SORT_ORDER)
              AudioInfo audioInfo= new AudioInfo();
                for(cursor.moveToFirst();!cursor.isAfterLast();cursor.moveToNext()){
                   audioInfo.setTitle(cursor.getString(0).toString());
                   audioInfo.setArtist(cursor.getString(1).toString());
                   audioInfo.setAlbum(cursor.getString(2).toString());
                   audioInfo.setDuration(cursor.getString(3).toString());
                   audioInfo.setSize(cursor.getString(4).toString());
                   audioInfo.setFilename(cursor.getString(5).toString());
                   audioInfo.setFilePath(cursor.getString(6).toString());
              Log. e(LOG, audioInfo.toString()+"," +cursor.getString(5).toString()+","+cursor.getString(6).toString());
              }
               return audioInfo;
     }
 
注:取得视频文件的信息有点类似
12、发送电子邮件:

    // 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;  

    }  

}  

13、打电话发短信:
调用打电话和发短信功能(ANDROID ) 1.打电话 可以自己写界面,在button的单击事件中添加如下代码即可:        Intent intent = new Intent();        intent.setAction("android.intent.action.CALL");        intent.setData(Uri.parse("tel:"+ mobile));//mobile为你要拨打的电话号码,模拟器中为模拟器编号也可       startActivity(intent);       或者
       Intent myIntentDial = new Intent(Intent.ACTION_CALL, Uri.parse("tel:" +mobile));        startActivity(myIntentDial);
调用拨打电话界面:
       Intent intent = new Intent();        intent.setAction("android.intent.action.DIAL");        intent.setData(Uri.parse("tel:"+ mobile));//mobile为你要拨打的电话号码,模拟器中为模拟器编号也可        startActivity(intent);
      或者
      Intent myIntentDial = new Intent(Intent.ACTION_DIAL,Uri.parse("tel:" + mobile));
      startActivity(myIntentDial);
需要添加打电话权限: <uses-permission Android:name="android.permission.CALL_PHONE" />
14.发短信 和打电话差不多,在button的单击事件中添加如下代码:     SmsManager smsManager = SmsManager.getDefault();     ArrayList<String> texts = smsManager.divideMessage(content);//拆分短信,短信字数太多了的时候要分几次发     for(String text : texts){      smsManager.sendTextMessage(mobile, null, text, null, null);//发送短信,mobile是对方手机号     } 对应发短信权限: <uses-permissionAndroid:name="android.permission.SEND_SMS" />
附:调用系统 发送短信 和 已发送短信界面 a. 调用系统发送短信界面(并指定短信接收人和短信内容)     Uri smsToUri = Uri.parse("smsto:10086");        Intent mIntent = new Intent( android.content.Intent.ACTION_SENDTO, smsToUri );      mIntent.putExtra("sms_body", "The SMS text");      startActivity( mIntent );
b. 调用系统已发送短信界面    Uri  smsUri = Uri.parse("smsto:106900867734");    Intent intent = new Intent(Intent.ACTION_MAIN, smsUri);    intent.setType("vnd.android-dir/mms-sms");    startActivity(intent);
15、全屏、亮度、模糊度设置
//设置窗体全屏 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
//设置窗体始终点亮 getWindow().setFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON,       WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
//设置窗体背景模糊
getWindow().setFlags(WindowManager.LayoutParams.FLAG_BLUR_BEHIND,                 WindowManager.LayoutParams.FLAG_BLUR_BEHIND);
posted @ 2013-06-12 21:48  火腿骑士  阅读(689)  评论(0编辑  收藏  举报