Android情景模式、文件管理器 完整示例编程详解

Aadroid应用开发实例
第一部分 情景模式
   main.xml
   <?xml version="1.0" encoding="utf-8"?>
    <TabHost
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:id="@android:id/tabhost"
     android:layout_width="fill_parent"
     android:layout_height="fill_parent">
     <LinearLayout
      android:orientation="vertical"
      android:layout_width="fill_parent"
      android:layout_height="fill_parent">
      <TabWidget
       android:id="@android:id/tabs"
       android:layout_width="fill_parent"
       android:layout_height="wrap_content" />
       <FrameLayout
        android:id="@android:id/tabcontent"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <RadioGroup
         android:id="@+id/RadioGroup01"
         android:orientation="vertical"
         android:layout_height="wrap_content"
         android:layout_width="wrap_content"
         android:layout_centerInParent="true">
         <RadioButton
          android:text="@string/ring_and_vibrate"
          android:id="@+id/ring_and_vibrate01"
          android:layout_width="fill_parent"
          android:textSize="24sp"
          android:paddingLeft="50sp"/>
         <RadioButton
          android:text="@string/ring"
          android:id="@+id/ring01"
          android:layout_width="fill_parent"
          android:textSize="24sp"
          android:paddingLeft="50sp"
          android:paddingRight="50sp"/>
         <RadioButton
          android:text="@string/vibrate"
          android:id="@+id/vibrate01"
          android:layout_width="fill_parent"
          android:textSize="24sp"
          android:paddingLeft="50sp"
          android:paddingRight="50sp"/>
         <RadioButton
          android:text="@string/silent"
          android:id="@+id/silent01"
          android:layout_width="fill_parent"
          android:textSize="24sp"
          android:paddingLeft="50sp"
          android:paddingRight="50sp"/>
        </RadioGroup>
        
        <RelativeLayout
         xmlns:android="http://schemas.android.com/apk/res/android"
         android:id="@+id/RelativeLayout01"
         android:orientation="vertical"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
         android:padding="12sp">
         <TextView
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="@string/help"
          android:textSize="20px"
          android:textStyle="bold"
          android:id="@+id/help">
         </TextView>
         <TimePicker
          android:id="@+id/timePkr"
          android:layout_below="@id/help"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content">
         </TimePicker>
         <RadioGroup
          android:orientation="vertical"
          android:id="@+id/RadioGroup02"
          android:layout_below="@id/timePkr"
          android:layout_height="wrap_content"
          android:layout_width="wrap_content"
          android:layout_centerInParent="true">
          <RadioButton
           android:text="@string/ring_and_vibrate"
           android:id="@+id/ring_and_vibrate02"
           android:layout_width="fill_parent"
           android:textSize="24sp"
           android:paddingLeft="50sp"/>
          <RadioButton
           android:text="@string/ring"
           android:id="@+id/ring02"
           android:layout_width="fill_parent"
           android:textSize="24sp"
           android:paddingLeft="50sp"
           android:paddingRight="50sp"/>
          <RadioButton
           android:text="@string/vibrate"
           android:id="@+id/vibrate02"
           android:layout_width="fill_parent"
           android:textSize="24sp"
           android:paddingLeft="50sp"
           android:paddingRight="50sp"/>
          <RadioButton
           android:text="@string/silent"
           android:id="@+id/silent02"
           android:layout_width="fill_parent"
           android:textSize="24sp"
           android:paddingLeft="50sp"
           android:paddingRight="50sp"/>
         </RadioGroup>
        </RelativeLayout>

        <AbsoluteLayout
         xmlns:android="http://schemas.android.com/apk/res/android"
         android:id="@+id/AbsoluteLayout03"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent"
         >
         <TextView
          android:id="@+id/myText1"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="情景模式:"
          android:textSize="16sp"
          android:layout_x="20px"
          android:layout_y="42px"
          >
         </TextView>
         <ImageView
          android:id="@+id/myImage"
          android:layout_width="48px"
          android:layout_height="48px"
          android:layout_x="110px"
          android:layout_y="32px"
          >
         </ImageView>
         <TextView
          android:id="@+id/myText2"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="声音音量:"
          android:textSize="16sp"
          android:layout_x="20px"
          android:layout_y="102px"
          >
         </TextView>
         <ProgressBar
          android:id="@+id/myProgress"
          style="?android:attr/progressBarStyleHorizontal"
          android:layout_width="160dip"
          android:layout_height="wrap_content"
          android:max="7"
          android:progress="5"
          android:layout_x="110px"
          android:layout_y="102px"
          >
         </ProgressBar>
         <ImageButton
          android:id="@+id/downButton"
          android:layout_width="100px"
          android:layout_height="100px"
          android:layout_x="50px"
          android:layout_y="162px"
          android:src="@drawable/down"
          >
         </ImageButton>
         <ImageButton
          android:id="@+id/upButton"
          android:layout_width="100px"
          android:layout_height="100px"
          android:layout_x="150px"
          android:layout_y="162px"
          android:src="@drawable/up"
          >
         </ImageButton>
         <ImageButton
          android:id="@+id/normalButton"
          android:layout_width="60px"
          android:layout_height="60px"
          android:layout_x="50px"
          android:layout_y="272px"
          android:src="@drawable/icon"
          >
         </ImageButton>
         <ImageButton
          android:id="@+id/muteButton"
          android:layout_width="60px"
          android:layout_height="60px"
          android:layout_x="120px"
          android:layout_y="272px"
          android:src="@drawable/mute"
          >
         </ImageButton>
         <ImageButton
          android:id="@+id/vibrateButton"
          android:layout_width="60px"
          android:layout_height="60px"
          android:layout_x="190px"
          android:layout_y="272px"
          android:src="@drawable/vibrate"
          >
         </ImageButton>
        </AbsoluteLayout>
       </FrameLayout>
     </LinearLayout>
    </TabHost>
   音频管理器(AudioManager)
    既然是情景模式,肯定需要调节声音的大小、静音、振动等。可用AudioManager来控制和访问铃声。
     Context.getSystemService(Context.AUDIO_SERVICE);//获得AudioManager实例
    AudioManager常量:
     ADJUST_LOWER   减少铃声音量
     ADJUST_RAISE   增加铃声音量
     ADJUST_SAME    保持原来的铃声音量
     EXTRA_RINGER_MODE  新的铃声模式
     EXTRA_VIBRATE_SETTING 新的特殊的振动设置
     EXTRA_VIBRATE_TYPE  振动类型
     FLAG_PLAY_SOUND   当调节音量时,是否播放(预览效果)
     FLAG_VIBRATE   是否振动
     MODE_CURRENT   当前音频模式
     MODE_INVALID   无效音频模式
     MODE_IN_CALL   在调用的音频模式
     MODE_NORMAL    普通音频模式
     MODE_RINGTONE   响铃模式
    AudioManager方法:
     adjustVolume   调整音量大小
     getMode     得到当前音频模式
     getRingerMode   得到当前铃声模式
     getStreamMaxVolume  得到最大的音频指数
     getStreamVolume   得到当前音频指数
     isSpeakerphoneOn  扬声器是否打开
     loadSoundEffects  加载声音效果
     playSoundEffect   播放声音效果
     setMicrophoneMute  设置麦克风静音和关闭
     setMode     设置音频模式
     setRingerMode   设置铃声模式
     setSpeakerphoneOn  设置扬声器的打开和关闭
     setVibrateSetting  当铃声模式改变时,设置振动类型
     如下代码设置了铃声和振动模式:
      audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
      audio.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON);
      audio.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON);
     如下代码设置了静音模式:
      audio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
      audio.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF);
      audio.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF);
   定时器(AlarmManager)
    需要使用AlarmManager来控制定时器。可以使用set(int type,long triggerAtTime,PendingIntent operation)来注册定时器。参数PendingIntent负责传递定时信息,即要将信息
    发出去,也要对发送后的状态进行处理。可以使用getActivity(Content ,int , Intent, int) , getBroadcast(Context, int, Intent, int), getService(Context ,int ,Intent,int)
    函数来得到一个PendingIntent实例。通过调用 getBroadcast 来获得PendingIntent实现广播的功能,就像调用Context.sendBroadcast()函数一样。当系统通过PendingIntent发送
    一个Intent是要采用广播的形式,并且在该Intent中会包含响应的Intent接收的对象,当然可以在创建PendingIntent时指定这个对象,也可以通过ACTION和CATEGORY等描述让系统自动
    找到该行为处理对象。
     如下为处理一个定时器的方法:
      protected void ring(){
       Intent intent = new Intent(RingBroadcastReceiver.RING_CHANGED);
       intent.putExtra("checkedId", R.id.ring02);
       PendingIntent alarmIntent = PendingIntent.getBroadcast(this, RingBroadcastReceiver.REQUEST_CODE, intent ,0);
       mAlarmManager.set(AlarmManager.RTC_WAKEUP, getTime(),alarmIntent);
      }
   广播接收器(BroadcastReceiver)
    当应用程序所设置的时间到了后,系统中的AlarmManagerService就会从系统底层获取一个闹钟事件,并从自己维护的队列中取出与其匹配的信息,然后通过其应用注册的
    PendingIntent把该闹了事件发回给应用。当应用收到该Intent后就会对事件作出相应的处理,比如,改变情景模式为振动、铃声等。因此需要在应用程序中创建一个接收广播的
    类RingBroadcastReceiver来处理这些事件。
 
   public class RingBroadcastReceiver extends BroadcastReceiver{
    private static final String TAG  = "RingBroadcastReceiver";
    public static final String VIBRATE_CHANGED = "com.yarin.android.RingProfile.VIBRATE_CHANGED";
    public static final String SILENT_CHANGED = "com.yarin.android.RingProfile.SILENT_CHANGED";
    public static final String RV_CHANGED  = "com.yarin.android.RingProfile.RV_CHANGED";
    public static final String RING_CHANGED = "com.yarin.android.RingProfile.RING_CHANGED";
    public static final int REQUEST_CODE = 0;
    public void onReceive(Context context, Intent intent){
     AudioManager audio = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);
     int checkedId = intent.getIntExtra("checkedId", 0);
     Log.e(TAG, checkedId + intent.getAction());  
     switch (checkedId){// 切换情景模式
      case R.id.ring_and_vibrate01:
      case R.id.ring_and_vibrate02:
       ringAndVibrate(audio);
       break;
      case R.id.vibrate01:
      case R.id.vibrate02:
       vibrate(audio);
       break;
      case R.id.silent01:
      case R.id.silent02:
       silent(audio);
       break;
      default:
       ring(audio);
       break;
     }
    } 
    protected void ringAndVibrate(AudioManager audio){// 铃声和震动
     audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
     audio.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON);
     audio.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON);
    } 
    protected void ring(AudioManager audio){// 铃声
     audio.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
     audio.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF);
     audio.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF);
    } 
    protected void vibrate(AudioManager audio){// 震动
     audio.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
     audio.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_ON);
     audio.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_ON); 
    } 
    protected void silent(AudioManager audio){// 静音
     audio.setRingerMode(AudioManager.RINGER_MODE_SILENT);
     audio.setVibrateSetting(AudioManager.VIBRATE_TYPE_RINGER, AudioManager.VIBRATE_SETTING_OFF);
     audio.setVibrateSetting(AudioManager.VIBRATE_TYPE_NOTIFICATION, AudioManager.VIBRATE_SETTING_OFF);
    }
   }

   public class RingProfile extends TabActivity{//处理UI界面中定义的按钮、选项的事件
    private static final String TAG="RingToggle"; 
    private TabHost mTabHost;//声明TabHost对象
    protected boolean isChange; 
    private AlarmManager mAlarmManager; 
    private TimePicker mTimePicker ; 
    private int mTab;
 
    private ImageView   myImage;
    private ImageButton   downButton;
    private ImageButton   upButton;
    private ImageButton   normalButton;
    private ImageButton   muteButton;
    private ImageButton   vibrateButton;
    private ProgressBar   myProgress;
    private AudioManager  audioMa;
    private int     volume = 0;
  
    public void onCreate(Bundle savedInstanceState){
     super.onCreate(savedInstanceState);
     setContentView(R.layout.main);
   
     mTabHost = getTabHost();//取得TabHost对象    
     //为TabHost添加标签 .新建一个newTabSpec(newTabSpec),设置其标签和图标(setIndicator),设置内容(setContent)
     mTabHost.addTab(mTabHost.newTabSpec("tab_test1")
       .setIndicator("普通情景模式",getResources().getDrawable(R.drawable.icon))
       .setContent(R.id.RadioGroup01));
     mTabHost.addTab(mTabHost.newTabSpec("tab_test2")
       .setIndicator("定时情景模式",getResources().getDrawable(R.drawable.timeprofile))
       .setContent(R.id.RelativeLayout01));
     mTabHost.addTab(mTabHost.newTabSpec("tab_test3")
       .setIndicator("自定义情景模式",getResources().getDrawable(R.drawable.addprofile))
       .setContent(R.id.AbsoluteLayout03));
           
     mTabHost.setBackgroundResource(R.drawable.bg); //设置TabHost的背景图片资源  
     mTabHost.setCurrentTab(0); //设置当前显示哪一个标签
     mTab = 0;
     updateRadioGroup();
         
     audioMa = (AudioManager)getSystemService(Context.AUDIO_SERVICE);//初始化,取得AudioManager
     myImage = (ImageView)findViewById(R.id.myImage);
     myProgress = (ProgressBar)findViewById(R.id.myProgress);
     downButton = (ImageButton)findViewById(R.id.downButton);
     upButton = (ImageButton)findViewById(R.id.upButton);
     normalButton = (ImageButton)findViewById(R.id.normalButton);
     muteButton = (ImageButton)findViewById(R.id.muteButton);
     vibrateButton = (ImageButton)findViewById(R.id.vibrateButton);
    
     mTabHost.setOnTabChangedListener(new OnTabChangeListener(){ //标签切换事件处理,setOnTabChangedListener
      public void onTabChanged(String tabId) {
       if ( tabId.equals("tab_test1") ){
        mTab = 0;            
        mAlarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        mTimePicker = (TimePicker)findViewById(R.id.timePkr);
        mTimePicker.setIs24HourView(true);
        updateRadioGroup();
       }else if ( tabId.equals("tab_test2") ){
        mTab = 1;
        mAlarmManager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
        mTimePicker = (TimePicker)findViewById(R.id.timePkr);
        mTimePicker.setIs24HourView(true);
        updateRadioGroup();
       }
      }           
     });
       
     RadioGroup group1 = (RadioGroup) findViewById(R.id.RadioGroup01);
     group1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
      public void onCheckedChanged(RadioGroup group, int checkedId) {
       if (isChange){
        return;
       }        
       switch (checkedId){              
        case R.id.ring_and_vibrate01:
         ringAndVibrate();
         break;              
        case R.id.ring01:
         ring();
         break;                  
        case R.id.vibrate01:
         vibrate();
         break;                             
        case R.id.silent01:
         silent();
         break;              
       }             
       RadioButton radio = (RadioButton) findViewById(checkedId);              
       if (radio != null)           
        radio.setTextSize(30);             
      } 
     });     
     for (int i = 0, l = group1.getChildCount(); i < l; i++){  //RadioButton添加监听器 
      RadioButton radio = (RadioButton) group1.getChildAt(i);
      radio.setOnTouchListener(new OnTouchListener() {              
       public boolean onTouch(View v, MotionEvent event){            
        RadioButton radio = (RadioButton) v;                
        if (!radio.isChecked())                    
         return false;               
         radio.setTextSize(30);                                                                               
         return false;                                         
       }              
      });
     }      
     RadioGroup group2 = (RadioGroup) findViewById(R.id.RadioGroup02);//添加onChangeListener
     group2.setOnCheckedChangeListener(new OnCheckedChangeListener() {
      public void onCheckedChanged(RadioGroup group, int checkedId){
       if (isChange)
        return;            
       switch (checkedId){              
        case R.id.ring_and_vibrate02:
         ringAndVibrate();
         break;              
        case R.id.ring02:
         ring();
         break;                  
        case R.id.vibrate02:
         vibrate();
         break;                             
        case R.id.silent02:
         silent();
         break;              
       }             
       RadioButton radio = (RadioButton) findViewById(checkedId);              
        if (radio != null)             
        radio.setTextSize(30);             
      } 
     });     
     for (int i = 0, l = group2.getChildCount(); i < l; i++){   //RadioButton添加监听器
      RadioButton radio = (RadioButton) group2.getChildAt(i);
      radio.setOnTouchListener(new OnTouchListener() {              
       public boolean onTouch(View v, MotionEvent event){            
        RadioButton radio = (RadioButton) v;                
        if (!radio.isChecked())                    
         return false;               
         radio.setTextSize(30);                                                                               
         return false;                                         
       }              
      });
     }      
     volume=audioMa.getStreamVolume(AudioManager.STREAM_RING); //取得手机的初始音量,并初始化进度条
     myProgress.setProgress(volume);     
     int mode=audioMa.getRingerMode(); //取得初始模式,并分别设置图标
     if(mode==AudioManager.RINGER_MODE_NORMAL){
      myImage.setImageDrawable(getResources().getDrawable(R.drawable.icon));
     }else if(mode==AudioManager.RINGER_MODE_SILENT){
      myImage.setImageDrawable(getResources().getDrawable(R.drawable.mute));
     }else if(mode==AudioManager.RINGER_MODE_VIBRATE){
      myImage.setImageDrawable(getResources().getDrawable(R.drawable.vibrate));
     }       
     downButton.setOnClickListener(new Button.OnClickListener(){ //降低音量按键
      public void onClick(View arg0) {
       audioMa.adjustVolume(AudioManager.ADJUST_LOWER, 0); //adjustVolume可以增加和降低音量
       volume=audioMa.getStreamVolume(AudioManager.STREAM_RING);
       myProgress.setProgress(volume);//设置进度条
       int mode=audioMa.getRingerMode();//设置图标
       if(mode==AudioManager.RINGER_MODE_NORMAL){
        myImage.setImageDrawable(getResources().getDrawable(R.drawable.icon));
       }else if(mode==AudioManager.RINGER_MODE_SILENT){
        myImage.setImageDrawable(getResources().getDrawable(R.drawable.mute));
       }else if(mode==AudioManager.RINGER_MODE_VIBRATE){
        myImage.setImageDrawable(getResources().getDrawable(R.drawable.vibrate));
       }
      }
     });    
     upButton.setOnClickListener(new Button.OnClickListener() {   //提高音量
      public void onClick(View arg0) {
       audioMa.adjustVolume(AudioManager.ADJUST_RAISE, 0); //AudioManager.ADJUST_RAISE提高音量
       volume=audioMa.getStreamVolume(AudioManager.STREAM_RING);
       myProgress.setProgress(volume);
       int mode=audioMa.getRingerMode();
       if(mode==AudioManager.RINGER_MODE_NORMAL){
        myImage.setImageDrawable(getResources().getDrawable(R.drawable.icon));
       }else if(mode==AudioManager.RINGER_MODE_SILENT){
        myImage.setImageDrawable(getResources().getDrawable(R.drawable.mute));
       }else if(mode==AudioManager.RINGER_MODE_VIBRATE){
        myImage.setImageDrawable(getResources().getDrawable(R.drawable.vibrate));
       }
      }
     });
     normalButton.setOnClickListener(new Button.OnClickListener() { //正常状态
      public void onClick(View arg0) {
       audioMa.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
       volume=audioMa.getStreamVolume(AudioManager.STREAM_RING);
       myProgress.setProgress(volume);
       myImage.setImageDrawable(getResources().getDrawable(R.drawable.icon));
      }
     });
     muteButton.setOnClickListener(new Button.OnClickListener() {  //静音状态
      public void onClick(View arg0) {
       audioMa.setRingerMode(AudioManager.RINGER_MODE_SILENT);
       volume=audioMa.getStreamVolume(AudioManager.STREAM_RING);
       myProgress.setProgress(volume);
       myImage.setImageDrawable(getResources().getDrawable(R.drawable.mute));
      }
     });
     vibrateButton.setOnClickListener(new Button.OnClickListener() {   //振动状态
      public void onClick(View arg0) {
       audioMa.setRingerMode(AudioManager.RINGER_MODE_VIBRATE);
       volume=audioMa.getStreamVolume(AudioManager.STREAM_RING);
       myProgress.setProgress(volume);
       myImage.setImageDrawable(getResources().getDrawable(R.drawable.vibrate));
      }
     });
    } 
    protected void updateRadioGroup(){// 更新情景模式
     int checkedId = currentMode();
     RadioButton checked = (RadioButton) findViewById(checkedId);
     isChange = true;
     checked.setChecked(true);
     isChange = false;
    } 
    protected int currentMode(){// 取得当前情景模式
     AudioManager audio = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
     switch (audio.getRingerMode()){
      case AudioManager.RINGER_MODE_SILENT:
       if ( mTab == 0 ){
        return R.id.silent01;
       }else{
        return R.id.silent02;
       }
      case AudioManager.RINGER_MODE_VIBRATE:
       if ( mTab == 0 ){
        return R.id.vibrate01;
       }else{
        return R.id.vibrate02;
       }
     }
     if (audio.shouldVibrate(AudioManager.VIBRATE_TYPE_RINGER)){
      if ( mTab == 0 ){
       return R.id.ring_and_vibrate01;
      }else{
       return R.id.ring_and_vibrate02;
      }
     }
     if ( mTab == 0 ){
      return R.id.ring01;
     }else{
      return R.id.ring02;
     }
    }
    protected void ringAndVibrate(){// 铃声和震动
     Intent intent = new Intent(RingBroadcastReceiver.RV_CHANGED);
     if ( mTab == 0 ){
      intent.putExtra("checkedId", R.id.ring_and_vibrate01);
     }else{
      intent.putExtra("checkedId", R.id.ring_and_vibrate02);
     }
     PendingIntent alarmIntent = PendingIntent.getBroadcast(this, RingBroadcastReceiver.REQUEST_CODE, intent, 0);
     Log.e(TAG, "" + intent);
     mAlarmManager.set(AlarmManager.RTC_WAKEUP, getTime(), alarmIntent);
    } 
    protected void ring(){// 铃声
     Intent intent = new Intent(RingBroadcastReceiver.RING_CHANGED);
     if ( mTab == 0 ){
      intent.putExtra("checkedId", R.id.ring01);
     }else{
      intent.putExtra("checkedId", R.id.ring02);
     }
     PendingIntent alarmIntent = PendingIntent.getBroadcast(this, RingBroadcastReceiver.REQUEST_CODE, intent, 0);
     Log.e(TAG, "" + intent);
     mAlarmManager.set(AlarmManager.RTC_WAKEUP, getTime(), alarmIntent);
    }
    protected void vibrate(){// 震动
     Intent intent = new Intent(RingBroadcastReceiver.VIBRATE_CHANGED);
     if ( mTab == 0 ){
      intent.putExtra("checkedId", R.id.vibrate01);
     }else{
      intent.putExtra("checkedId", R.id.vibrate02);
     }
     PendingIntent alarmIntent = PendingIntent.getBroadcast(this, RingBroadcastReceiver.REQUEST_CODE, intent, 0);
     Log.e(TAG, "" + intent);
     mAlarmManager.set(AlarmManager.RTC_WAKEUP, getTime(), alarmIntent);
    } 
    protected void silent(){// 静音
     Intent intent = new Intent(RingBroadcastReceiver.SILENT_CHANGED);
     if ( mTab == 0 ){
      intent.putExtra("checkedId", R.id.silent01);
     }else{
      intent.putExtra("checkedId", R.id.silent02);
     }
     PendingIntent alarmIntent = PendingIntent.getBroadcast(this, RingBroadcastReceiver.REQUEST_CODE, intent, 0);
     Log.e(TAG, "" + intent);
     mAlarmManager.set(AlarmManager.RTC_WAKEUP, getTime(), alarmIntent);
    } 
    private long getTime(){// 计算切换时间
     Date dateNow = new Date();
     long hour = mTimePicker.getCurrentHour() - dateNow.getHours();
     long min = mTimePicker.getCurrentMinute() - dateNow.getMinutes();
     long second = dateNow.getSeconds();
     return dateNow.getTime() + (hour * 60 + min) * 60 * 1000 - second * 1000;
    }
   }
   
   AndroidManifest.xml
    <receiver //注册声明权限
     android:name="RingBroadcastReceiver">
     <intent-filter>
      <action android:name="com.yarin.android.RingProfile.RV_CHANGED" />
      <action android:name="com.yarin.android.RingProfile.RING_CHANGED" />
      <action android:name="com.yarin.android.RingProfile.VIBRATE_CHANGED" />
      <action android:name="com.yarin.android.RingProfile.SILENT_CHANGED" />
     </intent-filter>
    </receiver>

第二部分 文件管理器
   文件管理器就是能够浏览和管理我们手机中的文件、文件夹和存储卡的工具,可以用来查看手机中所有资源,文件机构以便清楚直观的查看和操作手机文件和文件夹。如:重命名、
   删除、新建、复制、粘贴等。
   下例中实现了首先需要浏览文件(文件夹)、显示路径以及一些常用操作(比如新建、删除、粘贴等)。当选中一个文件时,需要提示用户有关文件操作的菜单,比如打开、复制、剪切、
   重命名、删除等。在操作文件,比如重命名、粘贴等,遇到该目录中有相同的文件名时,提升用户是否需要覆盖。当用户删除一个文件时,提示用户是否确定删除该文件等。当在删除
   时需要判断删除的是文件还是整个目录,然后进行相应的操作。

   public class IconifiedText implements Comparable<IconifiedText>{//UI设计 由于需要浏览大量的文件(文件夹),所以需要使用一个ListView来显示这些文件(文件夹)的列表。
                   在这里我们设置了不同的文件类型在前面设置了不同的图标,因此Android中自带的ListView并不能满足需要,
                   所以需要自己来定义一个用于显示文件(文件夹)的列表视图。
                   这里我们不用xml布局文件来设计界面,使用的是在程序中定义布局文件。那么在布局之前需要设计一个实例来
                   显示每个列表,这个列表必须包括一个图标和一个字符串,因此定义了IconifiedText类来显示每一行数据信息。
                   该类中包含两个对象,一个是使用Drawable来显示图标,使用String来显示文件名。另外附加一个boolean来表示
                   该行是否被选中。为了能够操作每一类数据,我们完成了一些该类的成员方法,如:设置文件名,设置图标、
                   获得文件名、获得图标等。看下面代码:
    private String  mText  = "";//文件名
    private Drawable mIcon  = null;//文件的图标ICNO
    private boolean mSelectable = true;//能否选中
    public IconifiedText(String text, Drawable bullet){
     mIcon = bullet;
     mText = text;
    } 
    public boolean isSelectable(){//是否可以选中
     return mSelectable;
    } 
    public void setSelectable(boolean selectable){//设置是否可用选中
     mSelectable = selectable;
    } 
    public String getText(){//得到文件名
     return mText;
    } 
    public void setText(String text){//设置文件名
     mText = text;
    } 
    public void setIcon(Drawable icon){//设置图标
     mIcon = icon;
    } 
    public Drawable getIcon(){//得到图标
     return mIcon;
    } 
    public int compareTo(IconifiedText other){//比较文件名是否相同
     if (this.mText != null)
      return this.mText.compareTo(other.getText());
     else
     throw new IllegalArgumentException();
    }
   }

   public class IconifiedTextView extends LinearLayout{//通过上步我们得到每一行的数据信息,要将该数据显示在界面之上,就需要实现一个界面布局的类IconifiedTextView
                在该类中使用TextView来显示文件名,使用ImageView来显示图标。由于我们的布局是图标和文件名在同一行上面,可以使用线性布局
                来设置这个界面,所以这里的继承了一个线性布局LinearLayout
    private TextView mText = null;//一个文件包括文件名和图表
    private ImageView mIcon = null;
    public IconifiedTextView(Context context, IconifiedText aIconifiedText){
     super(context); 
  
     this.setOrientation(HORIZONTAL);//设置布局方式,采用一个水平线性布局
     mIcon = new ImageView(context);  
     mIcon.setImageDrawable(aIconifiedText.getIcon());//设置ImageView为文件的图标  
     mIcon.setPadding(8, 12, 6, 12); //设置图标在该布局中的填充位置  
     addView(mIcon,  new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));//将ImageView即图表添加到该布局中
  
     mText = new TextView(context);
     mText.setText(aIconifiedText.getText());//设置文件名、填充方式、字体大小
     mText.setPadding(8, 6, 6, 10);
     mText.setTextSize(26);  
     addView(mText, new LinearLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));//将文件名添加到布局中
    }
    public void setText(String words){//设置文件名
     mText.setText(words);
    }
    public void setIcon(Drawable bullet){//设置图标
     mIcon.setImageDrawable(bullet);
    }
   }

   public class IconifiedTextListAdapter extends BaseAdapter{//使用BaseAdapter(数据存储器)来存储取得的文件。
                  因为是使用了列表视图,所以需要使用BaseAdapter来存储这些列表数据。
                  这里定义一个类继承BaseAdapter的类用来显示列表中的数据,其中List的内容是我们定义的InonifiedText类
    private Context    mContext = null; 
    private List<IconifiedText> mItems  = new ArrayList<IconifiedText>();// 用于显示文件的列表
    public IconifiedTextListAdapter(Context context){
     mContext = context;
    } 
    public void addItem(IconifiedText it) {//添加一项(一个文件)
     mItems.add(it);
    } 
    public void setListItems(List<IconifiedText> lit) { //设置文件列表
     mItems = lit;
    } 
    public int getCount() { //得到文件的数目,列表的个数
     return mItems.size();
    } 
    public Object getItem(int position) { //得到一个文件
     return mItems.get(position);
    } 
    public boolean areAllItemsSelectable() {//能否全部选中
     return false;
    } 
    public boolean isSelectable(int position) { //判断指定文件是否被选中
     return mItems.get(position).isSelectable();
    } 
    public long getItemId(int position) { //得到一个文件的ID
     return position;
    } 
    public View getView(int position, View convertView, ViewGroup parent) {//重写getView方法来返回一个IconifiedTextView(我们自定义的文件布局)对象
     IconifiedTextView btv;
     if (convertView == null) {
      btv = new IconifiedTextView(mContext, mItems.get(position));
     } else {
      btv = (IconifiedTextView) convertView;
      btv.setText(mItems.get(position).getText());
      btv.setIcon(mItems.get(position).getIcon());
     }
     return btv;
    }
   }

   public class FileManager extends ListActivity{// 事件处理。 下面实现了获取手机中的目录以及其中的文件(文件夹),然后显示到ListView中展现给用户。
                  下面实现的是以浮动的方式显示菜单和对话框。
    private List<IconifiedText> directoryEntries = new ArrayList<IconifiedText>();
    private File    currentDirectory = new File("/");
    private File     myTmpFile    = null;
    private int     myTmpOpt   = -1;

    public void onCreate(Bundle icicle){
     super.onCreate(icicle);
     browseToRoot();
     this.setSelection(0);
    } 
    private void browseToRoot() {//浏览文件系统的根目录
     browseTo(new File("/"));
    } 
    private void upOneLevel(){//返回上一级目录
     if(this.currentDirectory.getParent() != null)
      this.browseTo(this.currentDirectory.getParentFile());
    } 
    private void browseTo(final File file){//浏览指定的目录,如果是文件则进行打开操作
     this.setTitle(file.getAbsolutePath());
     if (file.isDirectory()){
      this.currentDirectory = file;
      fill(file.listFiles());
     }else{
      fileOptMenu(file);
     }
    }
    protected void openFile(File aFile){//打开指定文件.当我们点击打开菜单之后,要求能够根据不同的文件类型来启动相应的Activity,控制文件的操作等。
             此方法通过 File 来确定一个URI,然后通过 Intent 来设置URI的属性,最后通过 startActivity 来开启一个Activity
     Intent intent = new Intent();
     intent.setAction(android.content.Intent.ACTION_VIEW);
     File file = new File(aFile.getAbsolutePath());  
     String fileName = file.getName();// 取得文件名
     // 根据不同的文件类型来打开文件
     if (checkEndsWithInStringArray(fileName, getResources().getStringArray(R.array.fileEndingImage))){
      intent.setDataAndType(Uri.fromFile(file), "image/*");
     }else if (checkEndsWithInStringArray(fileName, getResources().getStringArray(R.array.fileEndingAudio))){
      intent.setDataAndType(Uri.fromFile(file), "audio/*");
     }else if (checkEndsWithInStringArray(fileName, getResources().getStringArray(R.array.fileEndingVideo))){
      intent.setDataAndType(Uri.fromFile(file), "video/*");
     }
     startActivity(intent);
    } 
    private void fill(File[] files){//这里可以理解为设置ListActivity的源  
     this.directoryEntries.clear();//清空列表  
     this.directoryEntries.add(new IconifiedText(getString(R.string.current_dir), getResources().getDrawable(R.drawable.folder)));//添加一个当前目录的选项  
     if (this.currentDirectory.getParent() != null) //如果不是根目录则添加上一级目录项
      this.directoryEntries.add(new IconifiedText(getString(R.string.up_one_level), getResources().getDrawable(R.drawable.uponelevel)));
      Drawable currentIcon = null;
      for (File currentFile : files){   
       if (currentFile.isDirectory()){//判断是一个文件夹还是一个文件
        currentIcon = getResources().getDrawable(R.drawable.folder);
       }else{   
        String fileName = currentFile.getName();//取得文件名
        //根据文件名来判断文件类型,设置不同的图标
        if (checkEndsWithInStringArray(fileName, getResources().getStringArray(R.array.fileEndingImage))){
         currentIcon = getResources().getDrawable(R.drawable.image);
        }else if (checkEndsWithInStringArray(fileName, getResources().getStringArray(R.array.fileEndingWebText))){
         currentIcon = getResources().getDrawable(R.drawable.webtext);
        }else if (checkEndsWithInStringArray(fileName, getResources().getStringArray(R.array.fileEndingPackage))){
         currentIcon = getResources().getDrawable(R.drawable.packed);
        }else if (checkEndsWithInStringArray(fileName, getResources().getStringArray(R.array.fileEndingAudio))){
         currentIcon = getResources().getDrawable(R.drawable.audio);
        }else if (checkEndsWithInStringArray(fileName, getResources().getStringArray(R.array.fileEndingVideo))){
         currentIcon = getResources().getDrawable(R.drawable.video);
        }else{
         currentIcon = getResources().getDrawable(R.drawable.text);
        }
       }  
       int currentPathStringLenght = this.currentDirectory.getAbsolutePath().length();//确保只显示文件名、不显示路径如:/sdcard/111.txt就只是显示111.txt
       this.directoryEntries.add(new IconifiedText(currentFile.getAbsolutePath().substring(currentPathStringLenght), currentIcon));
      }
      Collections.sort(this.directoryEntries);
      IconifiedTextListAdapter itla = new IconifiedTextListAdapter(this);  
      itla.setListItems(this.directoryEntries);//将表设置到ListAdapter中  
      this.setListAdapter(itla);//为ListActivity添加一个ListAdapter
    } 
    protected void onListItemClick(ListView l, View v, int position, long id){
     super.onListItemClick(l, v, position, id); 
     String selectedFileString = this.directoryEntries.get(position).getText();// 取得选中的一项的文件名  
     if (selectedFileString.equals(getString(R.string.current_dir))){   
      this.browseTo(this.currentDirectory);//如果选中的是刷新
     }else if (selectedFileString.equals(getString(R.string.up_one_level))){  
      this.upOneLevel();//返回上一级目录
     }else{    
      File clickedFile = null;
      clickedFile = new File(this.currentDirectory.getAbsolutePath()+ this.directoryEntries.get(position).getText());
      if(clickedFile != null)
       this.browseTo(clickedFile);
     }
    } 
    private boolean checkEndsWithInStringArray(String checkItsEnd, String[] fileEndings){//通过文件名判断是什么类型的文件
     for(String aEnd : fileEndings){
      if(checkItsEnd.endsWith(aEnd))
       return true;
     }
     return false;
    } 
    public boolean onCreateOptionsMenu(Menu menu){
     super.onCreateOptionsMenu(menu);
     menu.add(0, 0, 0, "新建目录").setIcon(R.drawable.addfolderr);
     menu.add(0, 1, 0, "删除目录").setIcon(R.drawable.delete);
     menu.add(0, 2, 0, "粘贴文件").setIcon(R.drawable.paste);
     menu.add(0, 3, 0, "根目录").setIcon(R.drawable.goroot);
     menu.add(0, 4, 0, "上一级").setIcon(R.drawable.uponelevel);
     return true;
    }
    public boolean onOptionsItemSelected(MenuItem item){
     super.onOptionsItemSelected(item);
     switch (item.getItemId()){
      case 0:
       Mynew();
       break;
      case 1:    
       MyDelete();//注意:删除目录,谨慎操作,该例子提供了deleteFile(删除文件)和deleteFolder(删除整个目录)
       break;
      case 2:
       MyPaste();
       break;
      case 3:
       this.browseToRoot();
       break;
      case 4:
       this.upOneLevel();
       break;
     }
     return false;
    }
    public boolean onPrepareOptionsMenu(Menu menu){
     return super.onPrepareOptionsMenu(menu);
    } 
    public void MyPaste(){//粘贴操作
     if ( myTmpFile == null ){
      Builder builder = new Builder(FileManager.this);
      builder.setTitle("提示");
      builder.setMessage("没有复制或剪切操作");
      builder.setPositiveButton(android.R.string.ok,new AlertDialog.OnClickListener() {
       public void onClick(DialogInterface dialog, int which) {
        dialog.cancel(); 
       }
      });
      builder.setCancelable(false);
      builder.create();
      builder.show();
     }else{
      if ( myTmpOpt == 0 ){//复制操作
       if(new File(GetCurDirectory()+"/"+myTmpFile.getName()).exists()){
        Builder builder = new Builder(FileManager.this);
        builder.setTitle("粘贴提示");
        builder.setMessage("该目录有相同的文件,是否需要覆盖?");
        builder.setPositiveButton(android.R.string.ok,new AlertDialog.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {
          copyFile(myTmpFile,new File(GetCurDirectory()+"/"+myTmpFile.getName()));
          browseTo(new File(GetCurDirectory()));
         }
        });
        builder.setNegativeButton(android.R.string.cancel,new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {
          dialog.cancel();
         }
        });
        builder.setCancelable(false);
        builder.create();
        builder.show();
       }else{
        copyFile(myTmpFile,new File(GetCurDirectory()+"/"+myTmpFile.getName()));
        browseTo(new File(GetCurDirectory()));
       }
      }else if(myTmpOpt == 1){//粘贴操作
       if(new File(GetCurDirectory()+"/"+myTmpFile.getName()).exists()){
        Builder builder = new Builder(FileManager.this);
        builder.setTitle("粘贴提示");
        builder.setMessage("该目录有相同的文件,是否需要覆盖?");
        builder.setPositiveButton(android.R.string.ok,new AlertDialog.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {
          moveFile(myTmpFile.getAbsolutePath(),GetCurDirectory()+"/"+myTmpFile.getName());
          browseTo(new File(GetCurDirectory()));
         }
        });
        builder.setNegativeButton(android.R.string.cancel,new DialogInterface.OnClickListener(){
         public void onClick(DialogInterface dialog, int which) {
          dialog.cancel();
         }
        });
        builder.setCancelable(false);
        builder.create();
        builder.show();
       }else{
        moveFile(myTmpFile.getAbsolutePath(),GetCurDirectory()+"/"+myTmpFile.getName());
        browseTo(new File(GetCurDirectory())); 
       }
      }
     }
    }
    public void MyDelete(){//删除整个文件夹 
     File tmp=new File(this.currentDirectory.getAbsolutePath());//取得当前目录  
     this.upOneLevel();//跳到上一级目录  
     if ( deleteFolder(tmp) ){//删除取得的目录
      Builder builder = new Builder(FileManager.this);
      builder.setTitle("提示");
      builder.setMessage("删除成功");
      builder.setPositiveButton(android.R.string.ok,new AlertDialog.OnClickListener() {
       public void onClick(DialogInterface dialog, int which) {
        dialog.cancel(); 
       }
      });
      builder.setCancelable(false);
      builder.create();
      builder.show();
     }else{
      Builder builder = new Builder(FileManager.this);
      builder.setTitle("提示");
      builder.setMessage("删除失败");
      builder.setPositiveButton(android.R.string.ok,new AlertDialog.OnClickListener(){
       public void onClick(DialogInterface dialog, int which) {
        dialog.cancel();
       }
      });
      builder.setCancelable(false);
      builder.create();
      builder.show();
     }
     this.browseTo(this.currentDirectory); 
    } 
    public void Mynew(){//新建文件夹
     final LayoutInflater factory = LayoutInflater.from(FileManager.this);
     final View dialogview = factory.inflate(R.layout.dialog, null);  
     ((TextView) dialogview.findViewById(R.id.TextView_PROM)).setText("请输入新建文件夹的名称!");//设置TextView  
     ((EditText) dialogview.findViewById(R.id.EditText_PROM)).setText("文件夹名称...");//设置EditText
  
     Builder builder = new Builder(FileManager.this);
     builder.setTitle("新建文件夹");
     builder.setView(dialogview);
     builder.setPositiveButton(android.R.string.ok,new AlertDialog.OnClickListener(){
      public void onClick(DialogInterface dialog, int which){
       String value = ((EditText) dialogview.findViewById(R.id.EditText_PROM)).getText().toString();
       if ( newFolder(value) ){
        Builder builder = new Builder(FileManager.this);
        builder.setTitle("提示");
        builder.setMessage("新建文件夹成功");
        builder.setPositiveButton(android.R.string.ok,new AlertDialog.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {           
          dialog.cancel();//点击确定按钮之后,继续执行网页中的操作
         }
        });
        builder.setCancelable(false);
        builder.create();
        builder.show();
       }else{
        Builder builder = new Builder(FileManager.this);
        builder.setTitle("提示");
        builder.setMessage("新建文件夹失败");
        builder.setPositiveButton(android.R.string.ok,new AlertDialog.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {           
          dialog.cancel();//点击确定按钮之后,继续执行网页中的操作
         }
        });
        builder.setCancelable(false);
        builder.create();
        builder.show(); 
       }
      }
     });
     builder.setNegativeButton(android.R.string.cancel,new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which) {
       dialog.cancel();
      }
     });
     builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
      public void onCancel(DialogInterface dialog) {
       dialog.cancel();
      }
     });
     builder.show();
    } 
    public boolean newFolder(String file){//新建文件夹
     File dirFile = new File(this.currentDirectory.getAbsolutePath()+"/"+file);
     try{
      if (!(dirFile.exists()) && !(dirFile.isDirectory())){
       boolean creadok = dirFile.mkdirs();
       if (creadok){
        this.browseTo(this.currentDirectory);
        return true;
       }else{
        return false;
       }
      }
     }catch (Exception e){
      e.printStackTrace();
      System.out.println(e);
      return false;
     }
     return true;
    } 
    public boolean deleteFile(File file){//删除文件
     boolean result = false;
     if (file != null){
      try{
       File file2 = file;
       file2.delete();
       result = true;
      }catch (Exception e){
       e.printStackTrace();
       result = false;
      }
     }
     return result;
    }  
    public boolean deleteFolder(File folder){ //删除文件夹
     boolean result = false;
     try{
      String childs[] = folder.list();
      if (childs == null || childs.length <= 0){
       if (folder.delete()){
        result = true;
       }
      }else{
       for (int i = 0; i < childs.length; i++){
        String childName = childs[i];
        String childPath = folder.getPath() + File.separator + childName;
        File filePath = new File(childPath);
        if (filePath.exists() && filePath.isFile()){
         if (filePath.delete()){
          result = true;
         }else{
          result = false;
          break;
         }
        }else if (filePath.exists() && filePath.isDirectory()){
         if (deleteFolder(filePath)){
          result = true;
         }else{
          result = false;
          break;
         }
        }
       }
       folder.delete();
      }
     }catch (Exception e){
      e.printStackTrace();
      result = false;
     }
     return result;
    }   
    public void fileOptMenu(final File file){//处理文件,包括打开,重命名等操作
     OnClickListener listener = new DialogInterface.OnClickListener() {
      public void onClick(DialogInterface dialog, int which){
       if (which == 0){
        openFile(file);
       }else if (which == 1){    
        final LayoutInflater factory = LayoutInflater.from(FileManager.this);//自定义一个带输入的对话框由TextView和EditText构成
        final View dialogview = factory.inflate(R.layout.rename, null);
     
        ((TextView) dialogview.findViewById(R.id.TextView01)).setText("重命名");//设置TextView的提示信息    
        ((EditText) dialogview.findViewById(R.id.EditText01)).setText(file.getName());//设置EditText输入框初始值     
        Builder builder = new Builder(FileManager.this);
        builder.setTitle("重命名");
        builder.setView(dialogview);
        builder.setPositiveButton(android.R.string.ok,new AlertDialog.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {
          String value = GetCurDirectory()+"/"+((EditText) dialogview.findViewById(R.id.EditText01)).getText().toString();//点击确定之后
          if(new File(value).exists()){
           Builder builder = new Builder(FileManager.this);
           builder.setTitle("重命名");
           builder.setMessage("文件名重复,是否需要覆盖?");
           builder.setPositiveButton(android.R.string.ok,new AlertDialog.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
             String str2 = GetCurDirectory()+"/"+((EditText) dialogview.findViewById(R.id.EditText01)).getText().toString();
             file.renameTo(new File(str2));
             browseTo(new File(GetCurDirectory()));
            }
           });
           builder.setNegativeButton(android.R.string.cancel,new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
             dialog.cancel();
            }
           });
           builder.setCancelable(false);
           builder.create();
           builder.show();
          }else {          
           file.renameTo(new File(value));//重命名
           browseTo(new File(GetCurDirectory()));
          }
         }
        });
        builder.setNegativeButton(android.R.string.cancel,new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {
          dialog.cancel();
         }
        });
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
         public void onCancel(DialogInterface dialog) {
          dialog.cancel();
         }
        });
        builder.show();
       }else if ( which == 2 ){
        Builder builder = new Builder(FileManager.this);
        builder.setTitle("删除文件");
        builder.setMessage("确定删除"+file.getName()+"?");
        builder.setPositiveButton(android.R.string.ok,new AlertDialog.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {
          if ( deleteFile(file) ){
           Builder builder = new Builder(FileManager.this);
           builder.setTitle("提示对话框");
           builder.setMessage("删除成功");
           builder.setPositiveButton(android.R.string.ok,new AlertDialog.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {             
             dialog.cancel();//点击确定按钮之后
             browseTo(new File(GetCurDirectory()));
            }
           });
           builder.setCancelable(false);
           builder.create();
           builder.show();
          }else{
           Builder builder = new Builder(FileManager.this);
           builder.setTitle("提示对话框");
           builder.setMessage("删除失败");
           builder.setPositiveButton(android.R.string.ok,new AlertDialog.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {            
             dialog.cancel();//点击确定按钮之后
            }
           });
           builder.setCancelable(false);
           builder.create();
           builder.show(); 
          }
         }
        });
        builder.setNegativeButton(android.R.string.cancel,new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int which) {
          dialog.cancel();
         }
        });
        builder.setCancelable(false);
        builder.create();
        builder.show();
       }else if ( which == 3 ){//复制     
        myTmpFile = file;//保存我们复制的文件目录     
        myTmpOpt = 0;//这里我们用0表示复制操作
       }else if ( which == 4 )//剪切{     
        myTmpFile = file;//保存我们复制的文件目录     
        myTmpOpt = 1; //这里我们用0表示剪切操作
       }
      }
     };  
     String[] menu={"打开","重命名","删除","复制","剪切"};//显示操作菜单
     new AlertDialog.Builder(FileManager.this)
         .setTitle("请选择你要进行的操作")
         .setItems(menu,listener)
         .show();
    } 
    public String GetCurDirectory(){//得到当前目录的绝对路径
     return this.currentDirectory.getAbsolutePath();
    } 
    public void moveFile(String source, String destination){//移动文件
     new File(source).renameTo(new File(destination));  
    } 
    public void copyFile(File src, File target){//复制文件
     InputStream in = null;
     OutputStream out = null;
     BufferedInputStream bin = null;
     BufferedOutputStream bout = null;
     try{
      in = new FileInputStream(src);
      out = new FileOutputStream(target);
      bin = new BufferedInputStream(in);
      bout = new BufferedOutputStream(out);
      byte[] b = new byte[8192];
      int len = bin.read(b);
      while (len != -1){
       bout.write(b, 0, len);
       len = bin.read(b);
      }
     }catch (FileNotFoundException e){
      e.printStackTrace();
     }catch (IOException e){
      e.printStackTrace();
     }finally{
      try{
       if (bin != null){
        bin.close();
       }
       if (bout != null){
        bout.close();
       }
      }catch (IOException e){
       e.printStackTrace();
      }
     }
    }
   }
     
   res.layout.rename.xml
   <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:gravity="center_horizontal"
     android:orientation="vertical"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     >
     <TextView
      android:id="@+id/TextView01"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"/>
     <EditText
      android:id="@+id/EditText01"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:selectAllOnFocus="true"
      android:scrollHorizontally="true"/>
    </LinearLayout>

   res.layout.dialog.xml
   <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:gravity="center_horizontal"
     android:orientation="vertical"
     android:layout_width="fill_parent"
     android:layout_height="wrap_content"
     >
     <TextView
      android:id="@+id/TextView_PROM"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"/>
     <EditText
      android:id="@+id/EditText_PROM"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:selectAllOnFocus="true"
      android:scrollHorizontally="true"/>
    </LinearLayout>
   
   AndroidManifest.xml
   <?xml version="1.0" encoding="utf-8"?>
    <manifest
     xmlns:android="http://schemas.android.com/apk/res/android"
     package="com.yarin.android.FileManager"
     android:versionCode="1"
     android:versionName="1.0">
     <application
      android:icon="@drawable/icon"
      android:label="@string/app_name">
      <activity
       android:name=".FileManager"
       android:label="@string/app_name">
       <intent-filter>
        <action android:name="android.intent.action.MAIN" />
        <category android:name="android.intent.category.LAUNCHER" />
       </intent-filter>
      </activity>
     </application>
     <uses-permission android:name="android.permission.INTERNET"/>
     <uses-permission android:name="android.permission.MOUNT_UNMOUNT_FILESYSTEMS"/>//程序中使用了文件操作所以需声明权限
     <uses-sdk android:minSdkVersion="5" />
    </manifest>

你可能感兴趣的:(android,File,layout,dialog,RadioButton,文件管理器)