2012年8月17日 星期五

URL (Internet)

Internet 打開網頁

Manifest.xml:


<uses-permission android:name="android.permission.INTERNET"/>


*******************************************
main.java


public class URLActivity extends Activity {
    /** Called when the activity is first created. */
TextView mTextView = null;
ScrollView mScrollView = null;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setContentView(R.layout.main);
        
        mTextView = new TextView (this);  //初始化textView
        mScrollView = new ScrollView(this);
        URLConnection conn = null;
        BufferedInputStream bis = null;
        ByteArrayBuffer baf = null;
        
        try{
        URL myURL = new URL ("http://www.google.com.tw/"); //初始化URL
        conn = myURL.openConnection(); //打開連接
        bis = new BufferedInputStream(conn.getInputStream()); //透過連接得到輸入串流
        int current = 0;
        baf = new ByteArrayBuffer(1000);
        while ((current = bis.read()) != -1) {
        baf.append((char) current); //將收到的資訊新增到ByteArrayBuffer中
       
        }catch (Exception e) {
    e.printStackTrace();
    } finally {
    try {
    if (bis != null) {
    bis.close(); 
    }
    } catch (Exception e) {
    e.printStackTrace();
    }
    }
        
        mTextView.setText(EncodingUtils.getString(baf.toByteArray(), "UTF-8"));
        mScrollView.addView(mTextView);//將textView新增到scrollView中
        this.setContentView(mScrollView);//設定當前顯示的使用者介面為scrollView
    }// end of onCreate()
}

Marquee 跑馬燈







<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/textView01"
        android:layout_width="300px"  //一定得設成某個值,否則不動
        android:layout_height="wrap_content"
        android:text="This is a test of marquee on the textView in android"
        android:ellipsize="marquee"
        android:scrollHorizontally="true"
        android:singleLine="true"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:marqueeRepeatLimit="marquee_forever" 
        android:textColor="#00FF00"
        android:textSize="25dip"/>

    <Button
        android:id="@+id/button1"
        android:scrollHorizontally="true"
        android:focusable="true"
        android:focusableInTouchMode="true"
        android:layout_marginTop="20dip"
        android:layout_width="250px"
        android:layout_height="wrap_content"
        android:ellipsize="marquee"
        android:singleLine="true"
        android:marqueeRepeatLimit="marquee_forever"
        android:textColor="#FF00FF"
        android:text="@string/hello" />


</LinearLayout>

******************
按下按鈕時,按鈕上的馬跑燈將啟動,但TextView的跑馬燈將停止

程式裡的 tv.setMarqueeRepeatLimit(-1); 循環


SharedPreferences

SharedPreferences: 主要用於儲存單一資料類別的資料,以供下次進來程式時使用。


public class G_4_5_PreferenceActivity extends Activity {
    /** Called when the activity is first created. */

EditText ed;
SharedPreferences sp;
public final String EDIT_TEXT_KEY = "EDIT_TEXT"; //定義Preferences檔中的key

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        ed = (EditText) findViewById(R.id.ed);
        sp = getPreferences(MODE_PRIVATE);//獲得SharedPreferences物件
        String result = sp.getString(EDIT_TEXT_KEY, null);
        if (result != null) {     //判斷獲取的值是否為空
        ed.setText(result);   //EditText物件顯示的內容設定為讀取的資料
        }
     
    }// end of onCreate()

@Override
protected void onDestroy() {
// TODO Auto-generated method stub
SharedPreferences.Editor editor = sp.edit();  //獲得SharedPreferences的Editor物件
//editor.putString(EDIT_TEXT_KEY, String.valueOf(ed.getText())); 與下述的結果一樣
editor.putString(EDIT_TEXT_KEY, ed.getText().toString());
editor.commit();
super.onDestroy();
}//end of onDestroy()
 
 
 
}


IO --(5)讀出的檔案內容,套用TTS,將內容以機器合成聲音讀出


IO --(5)讀出的檔案內容,套用TTS,將內容以機器合成聲音讀出
                  設計讓練習英聽的學生使用


Manifest.xml:
加上:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>




***********************
main.java: 主程式



public class IO_TTSActivity extends Activity implements OnInitListener{
    /** Called when the activity is first created. */
private final String SDCARD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
private final String FILE_PATH = "/fileio";
// private final String FILE_NAME = "test03.txt";
private final String ENCODING = "UTF-8";
private File mDataPath;
private FileInputStream fis = null;
TextView tv;
ListView lv;
String [] strings;
 
private TextToSpeech mTTS;
private Button listenBtn;
String result = "";
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        tv= (TextView) findViewById(R.id.textView01);
        tv.setMovementMethod(ScrollingMovementMethod.getInstance());
        
        mDataPath = new File (SDCARD_PATH + FILE_PATH);
        File [] filesArray = mDataPath.listFiles();
        
        String fileNames = ""; // to receive every single file name
        for (int i = 0; i < filesArray.length; i++) {
        if (filesArray[i].isFile()) { //get rid of directories
        String tempStr = ""; //會多出入境的字串
        tempStr = filesArray[i].toString();
        String strSub = ""; //to subtract the uneccessary part: /mnt/sdcard/fileio/ (19 個字元)
        strSub = tempStr.substring(19, tempStr.length()).toString();
        fileNames += strSub + "--";
        }
        }
        
        //Handle to subtraction of the final "--" in fileNames string
        String result = "";
        result = fileNames.substring(0, fileNames.length()-2);
        strings = TextUtils.split(result, "--");
        
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strings);
        lv = (ListView) findViewById(R.id.listView1);
        lv.setAdapter(adapter);
        lv.setOnItemClickListener(listener);
        
        mTTS = new TextToSpeech(getApplicationContext(), this);//初始化
        listenBtn = (Button) findViewById(R.id.button1);
        listenBtn.setOnClickListener(btnListener);
        
    }// end of onCreate
    
    
    //選擇要唸出的檔案
    private OnItemClickListener listener = new OnItemClickListener() {

@Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
tv.setText(""); // clean tv in case of left-over
String aFileName = strings[position].toString();
readFile(aFileName);//Method: read the content of a file
//讀出所選檔案的內容;用QUEUE_ADD可以再接其他的字串;QUEUE_FLUSH將無法做到
mTTS.speak(result, TextToSpeech.QUEUE_ADD, null);
mTTS.playSilence(5000, TextToSpeech.QUEUE_ADD, null); //休息五秒
mTTS.speak(result, TextToSpeech.QUEUE_ADD, null); //又重複將內容朗誦一遍
}
};// end of listener
    
//看答案的按鈕
private OnClickListener btnListener = new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
tv.setText(result);

}
};
//讀出檔案的內容
private void readFile(String aFileName) {
try {
String mFileName = mDataPath + "/" + aFileName;
File fileContent = new File (mFileName);
fis = new FileInputStream(fileContent);
int length = fis.available();
byte [] buffer = new byte [length];
fis.read(buffer);
result = EncodingUtils.getString(buffer, ENCODING);
fis.close();
//tv.setText(result);
}catch (Exception e) {
e.printStackTrace();
}
} //end of readFile()


@Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status == TextToSpeech.SUCCESS) {
mTTS.speak("I'm ready", TextToSpeech.QUEUE_FLUSH, null);
}else {
System.out.println("Oops!");
}
}


@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
mTTS.shutdown();
}


@Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if (mTTS != null) {
mTTS.stop();
}
}
}

****************************************
res/layout/main.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >

    <TextView
        
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:textColor="#FF0000"
        android:textSize="20dp"
        android:text="選擇下列檔案練習英聽:" />

    <TextView
        android:id="@+id/textView01"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp"
        android:maxLines="15"
        android:scrollbarStyle="outsideInset"
        android:scrollbars="vertical"
        android:singleLine="false"
        android:text=""
        android:textColor="#00FF00"
        android:textSize="20dp" />
     <Button
        android:id="@+id/button1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="看答案!" />
    

    <ListView
        android:id="@+id/listView1"
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:layout_weight="0.85" >
    </ListView>

   
</LinearLayout>

2012年7月17日 星期二

IO: (2) SDCARD


IO: (2) 僅列出SDCARD裡檔案的名稱(不包括資料夾)


public class OnlyFileNamesInSDCardActivity extends Activity {
    /** Called when the activity is first created. */

private final String SD_PATH = Environment.getExternalStorageDirectory().getAbsolutePath();
private final String FILE_PATH = "/fileio";
private final String FILE_NAME = "test02.txt";
private final String ENCODING = "UTF-8";

FileInputStream fis = null;

TextView tv;
ListView lv;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
     
     
     
        //列出Sdcard 裡的夾子和檔案,放上LISTVIEW
        try {
                //找出SD的入徑
        File sdcardPATH = Environment.getExternalStorageDirectory();
               //用list(),將SD裡的資料夾和檔案以字串的方式收集在array
//         String [] fileNamesArrayStr = sdcardPATH.list(); 

        //listFiles()則會加上完整入徑,列出入徑及資料夾+檔名的集合,存在File格是的陣列
        File [] fileArray = sdcardPATH.listFiles();
         /*** 如果要制訂特別的入徑 ***/
        // File myDataPath = new File (sdcardPATH.getAbsolutePath() + "/fileio");
        // File [] fileArray = myDataPath.listFiles(); //不要忘了要計算、減掉入徑的字元數


        String  tempStr = ""; //初始化
       
        for (int i=0; i < fileArray.length; i++) {//只收集檔案,不要資料夾,但每筆資料會產生入徑(但無法用 fileNamesArrayStr來做,因為它是字串,無法判定是否為檔案還是資料夾
        if (fileArray[i].isFile()) {
                               //用來接收每一筆的檔案名字串,但是會包含前面的入徑:/mnt/sdcard/
        String str = "";
        str = fileArray[i].toString();
                               // 用來去除多餘的入徑字串:/mnt/sdcard/
        String strSub = "";
                                 //利用substring 去掉每筆最前面的12個字元:/mnt/sdcard/
        strSub = str.substring(12, str.length()).toString();
                                // 以 "--"為記號,分隔每筆處理好的資料,存成一筆字串
        tempStr += "--" + strSub;
       
        }
        }

         //設一變數來處理最後的"--"兩個字元,讓它不會在ListView上多產生一個空的cell
          String result = "";
          Result = tempStr.substring(0, tempStr.length()-2);
        //以"--"為分節點將整筆字串切割成數個字串儲存成字串陣列,以顯示在螢幕上
        String[] strings = TextUtils.split(reselt, "--");
       
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, strings);
        lv = (ListView) findViewById(R.id.listView1);
        lv.setAdapter(adapter);
       
        } catch (Exception e) {
        e.printStackTrace();
        }
 

     
    }// end of onCreate
 
 
}