第二部分  工作项目中以及平时看视频、看书或者看博客时整理的个人觉得挺有用的笔记

 

1.Activity界面切换: 
  if(条件1){ 
       setContentView(R.layout.main); 
  }else{ 
       setContentView(R.layout.other); 

  }
 
2.带有返回的Activity消息传递:
MainActivity中核心代码如下:
    Button.setOnClickListener(listener);
          View.OnClickListener   listener=new OnClickListener(){
         Public void   onClick(View   v){
             String   msg=EditText.getText().toString().trim();
             Intent   intent=new   Intent();
             intent.setClass(MainActivity.this,OtherActivity.class);
             Bundle  bundle=new  Bundle();
             bundle.putString(“msg”,msg);
             intent.putExtras(bundle);
             startActivityForResult(intent , requestCode);
       }
  }
Public  void   onActivityResult(int requestCode,int resultCode, Intent data){
    switch(条件:判断请求Code与响应Code){
    case   判别选项:
         Bundle   bundle=data.getExtras();
         String    msg=bundle.getString(“msg”);
         处理得到的msg;
    }
}
OtherActivity中的核心代码:
     Bundle   bundle=this.getIntent().getExtras();
     String   msg=bundle.getString(“msg”);
         处理msg;
     button.setOnClickListener(new  View.OnClickListener(
        public   void   onClick(View  v){
                OtherActivity.this.setResult(resultCode  ,OtherActivity.this.getIntent());
         }
     ));
 
3.发送广播Broadcast 
MainActivity中的核心代码如下: 
    protected  void  onCreate(Bundle  savedInstanceState){ 
    启动服务: Intent   intent=new  Intent(MainActivity.this,MyService.class); 
                    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
                    startService(intent);  
    停止服务: Intent  intent=new Intent(MainActivity.this,MyService.class); 
                    boolean  isYes = stopService(intent); 
    } 
    public  void  onResume(){ 
               super.onResume(); 
注册广播:IntentFilter  intentFilter=new IntentFilter(MyService.FLAG); 
               MyBroadcastReceiver  mReceiver=new MyBroadcastReceiver(); 
              registerReceiver(mReceiver,intentFilter); 
    } 
    public  void  onPause(){ 
              super.onPause(); 
取消广播:MyBroadcastReceiver  mReceiver=new MyBroadcastReceiver(); 
               unregisterReceiver(mReceiver); 
    } 

MyService中的核心代码: 
    public  int  onStartCommand(Intent  intent,int flags,int startId){ 
        新建个线程,用来处理服务; 
    创建意图:Intent  intent=new  Intent(FLAG); 
                      intent.putExtra("msg",MSG); 
      发送广播: sendBroadcast(i); 
    }  
    public  void   onDestroy(){ 
         flag=false; 
          super.onDestroy(); 
    } 

MyBroadcastReceiver中的核心代码: 
    public   void  onReceive(Context  context,Intent  intent){ 
         Bundle  bundle=intent.getExtras(); 
          String  msg=bundle.getString("msg"); 
          处理msg; 
    } 
 
4.利用广播查看手机电量 
MainActivity中的核心代码: 
      int level;//当前电量值 
      int scale;//总的电量值 
      Handler  hd=new Handler(){ 
         public void handleMessage(Message msg){ 
              switch(msg.what){ 
                   处理消息; 
               } 
         } 
      } 
      BroadcastReceiver  br=new BroadcastReceiver(){
          public void onReceive(Context context,Intent intent){ 
               String s=intent.getAction(); 
                if(Intent.ACTION_BATTERY_CHANGED.equals(s)){ 
                     level=intent.getIntExtra("level",0); 
                     scale=intent.getIntExtra("scale",100); 
                     hd.sendEmptyMessage(0); 
               } 
          } 
      }; 
      public  void  onCreate(Bundle  savedInstanceState){ 
            注册广播:MainActivity.this.registerReceiver(br,new IntentFilter(Intent.ACTIVITY_BATTERY_CHANGED)); 
      } 
 
5.使用上下文菜单 
public void onCreate(Bundle savedInstanceState){ 
     为相应的组件注册上下文菜单: 
     this.registerForContextMenu(findViewById(R.id.EditText01)); 

public void onCreateContextMenu(ContextMenu menu,View v,ContextMenuInfo menuInfo){ 
     menu.add(组号,菜单号,顺序号,R.string.title); 

public  boolean  onContextItemSelected(MenuItem mi){ 
     switch(mi.getItemId()){ 
         case MENU1: 
         case MENU2: 
                  处理菜单选中事件; 
                 break; 
     }
}
6.添加链接事件 
     Linkify.addLinks(TextView,Linkify.WEB_URLS|Linkfy.EMAIL_ADDRESSED|Linkify.PHONE_NUMBERS); 
 
7.发送Email 
MainActivity中的核心代码: 
    private Cursor  cursor; 
    private ContactsAdapter  myCa; 
    static final String[] PEOPLE_PROJECTION={ 
         Contacts.People._ID,//联系人的id 
         Contacts.People.PRIMARY_PHONE_ID,//电话id 
         Contacts.People.TYPE, 
         Contacts.People.NUMBER,//号码 
         Contacts.People.LABEL,//标签 
         Contacts.People.NAME 
    }; 
    protected void onCreate(Bundle savedInstanceState){ 
获取内容解析:ContentResolver  content=getContentResolver(); 
                      cursor=content.query(Contacts.People.CONTENT_URI,PEOPLE_PROJECTION, 
                                     null,null,Contacts.People.DEFAULT_SORT_ORDER); 
                      myCa=new  ContactsAdapter(this,cursor); 
                       autoCompleteTextView.setAdapter(myCa); 
                       autoCompleteTextView.setOnItemClickListener( 
                             new AdapterView.OnItemClickListener() { 
                                     public void onItemClick(AdapterView<?> parent, View view,  int position, long id){ 
                                         Cursor  c=myCa.getCursor(); 
                                         c.moveToPosition(position); 
           获得联系人的电话:  String number=c.getString(c.getColumnIndexOrThrow(Contacts.People.Number)); 
                             }); 
                        } 
ContactsAdapter中的核心代码: 
    ContentResolver  myCr; 
    public ContentResolver(Context context,Cursor c){ 
          myCr=context.getContentResolver(); 
    } 
    public View newView(Context context, Cursor cursor, ViewGroup parent) { 
         final LayoutInflater myLi=LayoutInflater.from(context); 
         final TextView tv=(TextView)myLi.inflate(android.R.layout.simple_dropdown_item_1line, parent,false); 
         tv.setText(cursor.getColumnIndexOrThrow(Contacts.People.NAME));   
         return tv; 
    } 
    public void bindView(View view, Context context, Cursor cursor) { 
         ((TextView)view).setText(cursor.getString(cursor.getColumnIndexOrThrow(Contacts.People.NAME)));  
    } 
    public CharSequence convertToString(Cursor cursor) { 
         String str=cursor.getString(cursor.getColumnIndexOrThrow(Contacts.People.NAME)); 
         return str; 
    } 
    public Cursor runQueryOnBackgroundThread(CharSequence constraint) { 
         if(getFilterQueryProvider()!=null) 
             return getFilterQueryProvider().runQuery(constraint); 
         StringBuilder sb=new StringBuilder(); 
         String[] str=null; 
         if(constraint!=null){ 
              sb.append("UPPER("); 
             sb.append(Contacts.People.NAME); 
             sb.append(") GLOB ?"); 
             str=new String[]{constraint.toString().toUpperCase()+"*"};   
         }   
        return myCr.query(Contacts.People.CONTENT_URI, MainActivity.PEOPLE_PROJECTION,sb==null?null:sb.toString(), str, Contacts.People.DEFAULT_SORT_ORDER); 
    } 
需要添加权限  <uses-permission android:name="android.permission.READ_CONTACTS"/> 

8.当电话打进来时监听电话状态并回复短信消息 
MainActivity中的核心代码: 
    Handler hd=new Handler(){ 
        public void handleMessage(Message msg){ 
             switch(msg.what){ 
                 case 0: 
                     Bundle b=msg.getData(); 
                     String incomingNumber=(String)b.get("number"); 
                     SmsManager smsManager=SmsManager.getDefault(); 
                     PendingIntent pi=PendingIntent.getBroadcaset(context,0,new Intent(),0); 
                     smsManager.sendTextMessage(incomingNumber,null,msg,pi,null); 
            } 
       } 
   } 
            protected void onCreate(Bundle savedInstance){ 
监听电话状态:myPhoneStateListener  mPSL=new myPhoneStateListener(); 
                     TelephonyManager tm=(TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE); 
                     tm.listen(mPSL,PhoneStateListener.LISTEN_CALL_STATE); 
            } 
内部类:public class myPhoneStateListener  extends PhoneStateListener{ 
                     public void onCallStateChanged(int state,String incomingNumber){ 
                         switch(state){ 
                             case TelephonyManager.CALL_STATE_IDLE: 
                                     Bundle bundle=new Bundle(); 
                                     bundle.putString("number",incomingNumber); 
                                    Message m=new Message(); 
                                    m.what=1; 
                                    m.setData(bundle); 
                                    hd.sendMessage(m); 
                            } 
                        } 
               } 

9.利用绝对布局移动图片框 
MainActivity中的核心代码: 
    DisplayMetrics  dm=new DisplayMetrics(); 
    getWindowManger().getDefaultDisplay().getMetrix(dm); 
    int screenHeight=dm.heightPixels; 
    int screenWidth=dm.widthPixels; 
    ImageView.setLayoutParams(new AbsoluteLayout.LayoutParams(Image_Width,Image_Height,Image_X,Image_Y)); 

10.发送短信息 
MainActivity中的核心代码: 
判断是否为合法电话号码,返回boolean:
    PhoneNumberUtils.isGlobalPhoneNumber(numberStr);
    PendingIntent pi=PendingIntent.getActivity(this,0,new Intent(this,MainActivity.class),0); 
    SmsManager  sms=SmsManager.getDefault(); 
    sms.sendTextMessage(phoneNumber,null,smsBody,pi,null);
 
11.代码中添加选项菜单
MainActivity中的代码如下:
public boolean onCreateOptionMenu(Menu menu){
    SubMenu subMenuGender=menu.addSubMenu(上一级菜单ID,子菜单项ID,子菜单排序序号,子菜单标题);
    subMenuGender.setIcon(R.drawable.gender);//设置菜单图标
    MenuItem  male = subMenuGender.add(菜单组号,子菜单号,序号,标题);
    male.setChecked(true);  //子菜单被选中
    OnMenuItemClickListener  lsn=new OnMenuItemClickListener(){
         public boolean onMenuItemClick(MenuItem item){
             子菜单项单击事件;
         }
    }
}
public boolean onOptionsItemSelected(MenuItem mi){
    int id=mi.getItemId();
     被选中事件;
}
12.打电话
获取电话号码:String number=EditText.getText().toString().trim();
                      判断是否为合法电话号码;
            打电话:Intent intent=new Intent("android.intent.action.CALL",Uri.parse("tel://"+number));
                   startActivity(intent);
13.设置手机情景模式
获得震动服务: Vibrator vibrator=(Vibrator)getApplication().getSystemService(Service.VIBRATOR_SERVICE);
       开启震动: vibrator.vibrate(new long[]{100,10,100,1000},0);
       取消震动: vibrator.cancel();

设置情景模式: AudioManager  audioManager=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
 设置静音:      audioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
设置音量:    audioManager.getStreamVolume(AudioManager.STREAM_RING);
14.访问APK中的资源文件
String result=null;
try{
    InputStream  in=this.getResources().getAssets().open(fileName);
    int ch=0;
    ByteArrayOutputStream  baos=new ByteArrayOutputSream();
    while((ch=in.read())!=-1){
         baos.write(ch);
    }
    byte[] buff=baos.toByteArray();
    baos.close();
    in.close();
    result=new String(buff,"GB2312");
    result=result.replaceAll("\\r\\n","\n");
}catch(Exception e){
    Toast.makeText(this,"对不起,没有找到指定文件",Toast.LENGTH_SHORT).show();
}
15.SDcard中文件操作
    File rootFile=new File("/sdcard");
    File[] files=rootFile.listFiles();
    file.delete();
    file.isDestory();
    file.length();
    file.getName();
需要加上操作权限
    <uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
16.修改SDcard中文件的名字
MainActivity中的核心代码:
public Dialog onCreateDialog(int id){
    Dialog result=null;
     switch(id){
         case 0:
             AlertDialog.Builder b=new AlerDialog.Builder(this);
             b.setItems(null,null);
              b.setCancelable(false);
             gmDialog=b.create();
              result=gmDialog;
     }
    return result;
}
public void onPrepareDialog(int id,final Dialog dialog){
     switch(id){
         case 0:
设置对话框界面:
                dialog.setContentView(R.layout.dialog);
                button.setOnClickListener(new ....{
                     String newName=et.getText().toString().trim();
                     File xgf=new File(leavePath);
                    String newPath=xgf.getParentFile().getPath()+"/"+newName;
  重命名文件: xgf.renameTo(new File(newPath));
  取消对话框: dialog.cancel();
               })
        }
}

17.读取SDcard的使用情况信息
判断SDcard是否装载:
    装载:Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)
未装载:Environment.getExternalStorageState().equals(Environment.MEDIA_REMOVED)
获取存储根目录文件:
           File path=Environment.getExternalStorageDirectory();
           StatFs  sf=new StatFs(path.getPath());
获取SDcard总容量:
            long total=sf.getTotalBytes();
获取sdcard可用容量:
            long available=sf.getFreeBytes();
           String totalSize=total/1024>=1024?total/1024/1024+"MB":total/1024+"KB";

18.接收短信息
class  MyReceiver extends BroadcastReceiver{
    public void onReceive(Context context,Intent intent){
         if(intent.getAction().equals("android.provider.Telephony.SMS_RECEIVED")){
               Bundle bundle=intent.getExtras();
               if(bundle!=null){
                    Object[] obj=(Object[])bundle.get("pdus");
                     SmsMessage[] sm=new SmsMessage[obj.length];
                    for(int i=0;i<obj.length();i++){
                         sm[i]=SmsMessage.createFromPdu((byte[])obj[i]);
                     }
获取发信人的手机号:
                     String numComing=sm[i].getDiplayOriginatingAddress();
获取短消息内容: 
                     String smsBody=sm[i].getMessageBody();
           }  
     }
}

19.查看运行的进程数量
更新ListView的数据信息: 
    listView.invalidateViews();
查看进程:
    try{
        ActivityManager am=(ActivityManager)MainActivity.this.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> list=am.getRunningTasks(20);
        for(int i=0;i<list.size();i++){
进程信息:
            listArray.add(i+"."+list.get(i).baseActivity.getClassName()+",ID="+list.get(i).id);
        }
    }
20.改变屏幕方向
获取屏幕方向:
    if(getRequestedOrientation()==-1){
         无法区分横竖屏;
    }else if(getRequestedOrientation()==ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE){
         横屏;
    }else if(getRequestedOrientation()==ActivityInfo.SCREEN_ORIENTATION_PORTARIT){
         竖屏;
    }

设置竖屏:
     MainActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
设置横屏:
     MainActivity.this.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

public void onConfigurationChanged(Configuration config){
    if(config.orientation==Configuration.ORIENTATION_LANDSCAPE){
         处理横屏事务;
     }else if(config.orientation==Configuration.ORIENTATION_PORTRAIT){
          处理竖屏事务;
     }
}

21.读取SDcard中的文件内容
    String result=null;
    try{
         File f=new File("/sdcard"+fileName);
          byte[] buff=new byte[(int)f.length];
          FileInputStream fin=new FileInputStream(f);
          fin.read(buff);
         fin.close();
          result=new String(buff,"GB2312");
          result=result.replaceAll("\\r\\n","\\n");
    }catch(Exception e){
          异常处理;
    }

22.传感器应用
获取传感器服务:
    SensorManager sm=(SensorManager)getSystemService(Context.SENSOR_SERVICE);
获取音频管理服务:
    try{
        AudioManager am=(AudioManager)getSystemService(Context.AUDIO_SERVICE);
       if(am!=null){
获取响铃模式:
            int msg=am.getRingerMode();
        }
    }
    switch(msg){
        case AudioManager.RINGER_MODE_NORMAL:
              正常模式;
        case AudioManager.RINGER_MODE_SILENT:
              静音模式;
        case AudioManager.RINGER_MODE_VIBRATE:
              震动模式;
    }
传感器监听:
private SensorListener  mySensorListener = new  SensorListener(){
     public void onSensorChanged(int sensor,float[] values){
             float yaw=values[SensorManager.DATA_X];
             float pitch=values[SensorManager.DATA_Y];
             float row=values[SensorManager.DATA_Z];
设置响铃模式:
             am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
      }
     public void onAccuracyChanged(int sensor,int accuracy){ }
}
注册传感器监听:
protected void onResume(){
     super.onResume();
     sm.registerListener(mySensorListener,SensorManager.SENSOR_ORIENTATION , SensorManager.SENSOR_DELAY_NORMAL);
}
取消传感器监听:
protected void onPause(){
    super.onPause();
    sm.unregisterListener(mySensorListener);
}
23.进度条调节音量
获取音频服务:
    AudioManager  am=(AudioManager)this.getSystemService(Context.AUDIO_SERVICE);
获取进度条:
    final ProgressBar pb=(ProgressBar)this.findViewById(R.id.ProgressBar01);
获取当前音量:
    int volume=am.getStreamVolume(AudioManager.STREAM_RING);
    pb.setMax(70);
    pb.setProgress(volume*10);

增加音量:
    am.adjustVolume(AudioManager.ADJUST_RAISE,0);
    volume=am.getStreamVolume(AudioManager.STREAM_RING);
    pb.setProgress(volume*10);
减少音量:
    am.adjustVolume(AudioManager.ADJUST_LOWER,0);
24.利用SurfaceView显示图像
public class MySurface extends SurfaceView implements SurfaceHolder.Callback{
    MainActivity activity;
     Paint paint;
    public MySurfaceView(MainActivity activity){
         super(activity);
         this.activity=activity;
为SurfaceView添加回调事件:
          this.getHolder().addCallback(this);
         paint=new Paint();
         paint.setAntiAlias(true);
     }
     public void draw(canvas){
         绘制图像图形;
        canvas.drawBitmap(bitmapTmp,0,0,paint);
    }
    public void surfaceCreated(SurfaceHolder holder){
         Canvas canvas=holder.lockCanvas();
         try{
              synchronized(holder){
                 draw(canvas);
              }
          }catch(Exception e){
                e.printStackTrace();
          }finally{
              if(canvas!=null){
                     holder.unlockCanvasAndPost(canvas);
               }
         }
    }
     .......................
}

25.检测网络是否连通
ConnectionDetector中的核心代码:
private Context  _context;
public boolean isConnectingToInternet(){
获得连通性服务:
     ConnectivityManager  connectivity=(ConnectivityManager)_context.getSystemService(Context.CONNECTIVITY_SERVICE);
     if(connectivity!=null){
        NetworkInfo[] info=connectivity.getAllNetworkInfo();
        if(info!=null)
             for(int i=0;i<info.length;i++)
                 if(info[i].getState()==NetworkInfo.State.CONNECTED){
                     return true;
                 }
    }
    return false;
 }
 
​26.采集图像数据
protected void onCreate(Bundle savedInstanceState){
设置横屏:
    this.setRequestedOrientation(ActivitInfo.SCREEN_ORIENTATION_LANDSCAPE);
取消标题:
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
全屏:    
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

    SurfaceView mySurfaceView=(SurfaceView)this.findViewById(R.id.surfaceView01);
    SurfaceHolder mySurfaceHolder=mySurfaceView.getHolder();
    mySurfaceHolder.addCallback(this);
    mySurfaceHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
}
protected void onPause(){
    super.onPause();
    isView=false;
    if(myCamera!=null){
停止预览:
       myCamera.stopPreview();
释放照相机资源:
       myCamera.release();
释放对象资源:
       myCamera=null;
    }
}
public void initCamera() throws IOException{
     if(myCamera==null&&!isView){
          myCamera=Camera.open();
     }
     if(myCamera!=null&&!isView){
         try{
获取照相机参数:
                Camera.Parameters  myParameters=myCamera.getParameters();
设置参数:    
                myParameters.setPictureFormat(PixelFormat.JPEG);
                myCamera.setParameters(myParameters);
开启照相机预览:
                myCamera.startPreview();
                isView=true;
          }catch(Exception e){
                e.printStackTrace();
         }
     }
}
照相:
ShutterCallback myShutterCallback=new ShutterCallback(){
    public void onShutter(){}
}
PictureCallback myRawCallback=new PictureCallback(){
    public void onPictureTaken(byte[] data,Camera camera){}
}
PictureCallback myjpegCallback=new PictureCallback(){
     public void onPictureTaken(byte[] data,Camera camera){
         bm=BitmapFactory.decodeByteArray(data,0,data.length);
         ImageView myImageView=(ImageView)findViewById(R.id.mySurfaceView);
         myImageView.setImageBitmap(bm);
         isView=false;
         myCamera.stopPreview();
         myCamera.release();
         myCamera=null;
     }
}
      
if(isView&&myCamera!=null){
启动照相:
    myCamera.takePicture(myShutterCallback,myRawCallback,myjpegCallback);
}

保存图像:
String path=Environment.getExternalStorageDirectory();
int c=0;
File fTest=new File(path+"/mc"+c+".jpeg");
while(fTest.exists()){
    c++;
    fTest=new File(path+"/mc"+c+".jpeg");
}
try{
    FileOutputStream fout=new FileOutputStream(fTest);
    BufferedOutputStream bos=new BufferedOutputStream();
    bm.compress(Bitmap.CompressFormat.JPEG,80,bos);
    bos.flush();
    bos.close();
   }catch(Exception e){
   异常处理;
}

27.录制视频
开始录制:
       MediaRecorder  recorder=new MediaRecorder();
       File outf=File.createTempFile("fileName" , ".mp4" , Environment.getExternalStorageDirectory());
       recorder.setPreviewDisplay(mSurfaceHolder.getSurface());
       recorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);
       recorder.setAudioSource(MediaRecorder.AudioSource.MIC);
       recorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
       recorder.setVideoSize(640,480);
       recorder.setVideoFrameRate(20);
       recorder.setVideoEncoder(MediaRecorder.VideoEncoder.H264);
       recorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
       recorder.setMaxDuration(10000);
       recorder.setOutputFile(outf.getAbsolutePath);
       recorder.prepare();
       recorder.start();
停止录制:
      recorder.stop();
       recorder.release();
       recorder=null;
 
​28.录制音频
    File myFile=File.createTempFile("myAudio",".amr",Environment.getExternalStorageDirectory());
    MediaRecorder myMediaRecorder=new MediaRecorder();
    myMediaRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
    myMediaRecorder.setOutputFormat(MediaRecorder.OutputFormat.DEFAULT);
    myMediaRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.DEFAULT);
    myMediaRecorder.setOutputFile(myFile.getAbsolutePath());
    myMediaRecorder.prepare();
    myMediaRecorder.start();

29.获得手机中的图片
    button.setOnClickListener(new OnClickListener(){
         public void onClick(View v){
             Intent intent=new Intent();
             intent.setType("image/*");
             intent.setAction(Intent.ACTION_GET_CONTENT);
             startActivityForResult(intent,1);
         }
    });
    protected void onActivityResult(int requestCode,int resultCode,Intent data){
        if(resultCode==RESULT_OK){
获取选中图片uri:
             Uri uri=data.getData();
             ContentResolver cr=this.getContentResolver();
             try{
获取图片保存在Bitmap对象中:
                 Bitmap bitmap=BitmapFactory.decodeStream(cr.openInputStream(uri));
                 ImageView imageView=(ImageView)findViewById(R.id.imageview);
                 imageView.setImageBitmap(bitmap);
             }catch(Exception e){
                 e.printStackTrace();
            }
         }
         super.onActivityResult(requestCode,resultCode,data);
    }

30.发送短信
    button.setOnClickListener(new View.OnClickListener(){
         public void onClick(View v){
             msg=et.getText().toString().trim();
             Uri uri=Uri.parse("content://contacts/people");
             Intent intent=new Intent(Intent.ACTION_PICK,uri);
             startActivityForResult(intent,0);
        }
    });
    public void onActivityResult(int requestCode,int resultCode,Intent intent){
       switch(requestCode){
           case 0:
                 Uri uri=intent.getData();
                 if(uri!=null){
                     try{
                         Cursor cursor=getContentResolver().query(ContactsContract.Contacts.CONTENET_URI,null,null,null,null);
                        while(cursor.moveToNext()){
                            String phoneName=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
获取用户的id,用来查找电话号码:
                            String contactId=cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
                            String hasPhone=cursor.getString(cursor.getColumnIndexOrThrow(ContactsContract.Contacts.HAS_PHONE_NUMBER));
                            if(hasPhone.compareTo("1")==0){
                                  Cursor phones=getContentResolver().query(ContactsContract.CommonDatakinds.Phone.CONTENT_URI,null
                                                  ,ContactsContract.CommonDatakinds.Phone.CONTACT_ID+"="+contactId,null,null);
                                 while(phones.moveToNext()){
                                      String phoneNumber=phones.getString(phones.getColumnIndex(ContactsContract.CommonDatakinds.Phone.NUMBER));
                                      String phoneType=phones.getString(phones.getColumnIndex(ContactsContract.CommonDatakinds.Phone.TYPE));
                                      if(phoneType.equals("2")){
                                             SmsManager smsManager=SmsManager.getDefault();
                                             PendingIntent pi=PendingIntent.getBroadcast(MainActivity.this,0,new Intent(),0);
                                             smsManager.sendTextMessage(phoneName,null,msg,pi,null);
                                     }
                             }
                              phones.close();
                         }
                        }
                     }catch(Exception e){e.printStackTrace();}
                   }
         }
}