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>