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

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

 

Android项目笔记整理(1)的更多相关文章

  1. android项目笔记整理(3)

    61.AlphabetIndexer字母索引辅助类       实现对链表类型的数据进行快速索引. 应用于类似联系人列表右侧的导航栏 注意:       1.链表里的元素必须是Object类型,并实现 ...

  2. android项目笔记整理(2)

    31.利用SharedPreferences存储时间     读取时间:     SharedPreferences sp=this.getSharedPreferences("actm&q ...

  3. android项目笔记(一)

    1.getInstance:单例模式创建类的实例,getInstance在单例模式(保证一个类仅有一个实例,并提供一个访问它的全局访问点)的类中常见,用来生成唯一的实例,getInstance往往是s ...

  4. [APP] Android 开发笔记 002-命令行创建默认项目结构说明

    接上节:[APP] Android 开发笔记 001 4. 默认项目结构说明: 这里我使用Sublime Text 进行加载.

  5. Android 项目优化(七):阿里巴巴Android开发手册整理总结

    本来之前觉得Android项目优化系列的文章基本整理完毕了,但是近期看了一下<阿里Android开发手册>有了很多收获,想再整理一篇,下面就开始吧. 先在这里列一下之前整理的文章及链接: ...

  6. [APP] Android 开发笔记 001-环境搭建与命令行创建项目

    1. 安装JDK,SDK JDK http://www.oracle.com/technetwork/java/javase/downloads/index.html Android SDK http ...

  7. Android Studio安卓学习笔记(二)Android项目结构

    上一篇代码,我们学习了Android的功能以及如何用Android Studio开发第一个安卓程序.下面就要介绍Android项目结构.为日后学习打基础. 一:Android项目结构 打开MyFris ...

  8. Android笔记(七十三) Android权限问题整理 非常全面

    Android权限系统非常庞大,我们在Android系统中做任何操作都需要首先获取Android系统权限,本文记录了所有的Android权限问题,整理一下分享给大家. 访问登记属性 android.p ...

  9. (1)-Android学习笔记之:初识Android系统架构和项目结构

    Android系统架构 Android程序结构 创建一个Android项目,为初学便于理解,将程序项目结构切换为Project模式,项目结构如下 .gradle和.idea:这两个目录下放的都是And ...

随机推荐

  1. [Bayes] Maximum Likelihood estimates for text classification

    Naïve Bayes Classifier. We will use, specifically, the Bernoulli-Dirichlet model for text classifica ...

  2. koa中 log4js使用

    一.新建一个log4js.js配置文件 let path = require('path'); // 日志根目录 let baseLogPath = path.resolve(__dirname, ' ...

  3. 【作品集】UX作品集

    https://www.uisdc.com/10-inspiring-ux-portfolios http://jeya.io http://antonmircea.com/FinalUX.pdf h ...

  4. Linux信号、信号处理和信号处理函数

    信号(signal)是一种软件中断,它提供了一种处理异步事件的方法,也是进程间惟一的异步通信方式.在Linux系统中,根据POSIX标准扩展以后的信号机制,不仅可以用来通知某种程序发生了什么事件,还可 ...

  5. Android 中View的工作原理

    Android中的View在Android的知识体系中扮演着重要的角色.简单来说,View就是Android在视觉的体现.我们所展现的页面就是Android提供的GUI库中控件的组合.但是当要求不能满 ...

  6. GitHub快速搭建个人博客

    > 正所谓前人栽树,后人乘凉.> > 感谢[Huxpro](https://github.com/huxpro)提供的博客模板> > [我的的博客](https://fl ...

  7. c++学习笔记_2

    前言:本笔记所对应的课程为中国大学mooc中北京大学的程序设计与算法(三)C++面向对象程序设计,主要供自己复习使用,且本笔记建立在会使用c和java的基础上,只针对与c和java的不同来写 第二章 ...

  8. 最新 顺网科技java校招面经 (含整理过的面试题大全)

    从6月到10月,经过4个月努力和坚持,自己有幸拿到了网易雷火.京东.去哪儿.顺网科技得等10家互联网公司的校招Offer,因为某些自身原因最终选择了顺网科技.6.7月主要是做系统复习.项目复盘.Lee ...

  9. 深入剖析Java虚拟机内存结构

    深入剖析Java虚拟机内存模型 JVM整体架构 JVM整体架构如下: 通过编写代码来分析整个内存区域 public class Math { public static final Integer C ...

  10. The Maze II

    There is a ball in a maze with empty spaces and walls. The ball can go through empty spaces by rolli ...