2010年10月28日星期四

通過Java程序碼, 運行時設置屏幕方向 - setRequestedOrientation()

上文"通過XML設置屏幕方向(android:screenOrientation)"中, 在AndroidManifest.xml文件設定屏幕方向. 這種方法有一個缺點:不能在程序運行時改變屏幕方向. 這篇文章用另一種方法 - 使用setRequestedOrientation()方法, 在程序運行時設置屏幕方向.

通過Java程序碼, 運行時設置屏幕方向 - setRequestedOrientation()

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<Button
android:id="@+id/setrequestedorientation"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Set Requested Orientation"
/>
</LinearLayout>


SetRequestedOrientationActivity.java 負責選擇屏幕方向.
package com.AndroidRequestedOrientation;

import android.app.ListActivity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class SetRequestedOrientationActivity extends ListActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);

setListAdapter(new ArrayAdapter<String>(this,
android.R.layout.simple_list_item_1, OrientationString));
getListView().setTextFilterEnabled(true);
}

static final String[] OrientationString = new String[] {
"SCREEN_ORIENTATION_UNSPECIFIED",
"SCREEN_ORIENTATION_LANDSCAPE",
"SCREEN_ORIENTATION_PORTRAIT",
"SCREEN_ORIENTATION_USER",
"SCREEN_ORIENTATION_BEHIND",
"SCREEN_ORIENTATION_SENSOR",
"SCREEN_ORIENTATION_NOSENSOR"
};

static final int[] OrientationSetting = new int[] {
ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED,
ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE,
ActivityInfo.SCREEN_ORIENTATION_PORTRAIT,
ActivityInfo.SCREEN_ORIENTATION_USER,
ActivityInfo.SCREEN_ORIENTATION_BEHIND,
ActivityInfo.SCREEN_ORIENTATION_SENSOR,
ActivityInfo.SCREEN_ORIENTATION_NOSENSOR
};

@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);

Intent intent = new Intent();
Bundle bundle = new Bundle();

bundle.putInt("setting", OrientationSetting[position]);
intent.putExtras(bundle);
setResult(RESULT_OK, intent);
finish();
}

}


主代碼 - AndroidRequestedOrientation.java
在onActivityResult()方法, 從SetRequestedOrientationActivity返回值, 使用setRequestedOrientation()方法, 設置屏幕方向.
package com.AndroidRequestedOrientation;

import android.app.Activity;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class AndroidRequestedOrientation extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonSetRequestedOrientation = (Button)findViewById(R.id.setrequestedorientation);
buttonSetRequestedOrientation.setOnClickListener(new Button.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent();
intent.setClass(AndroidRequestedOrientation.this,
SetRequestedOrientationActivity.class);

startActivityForResult(intent, 0);
}});
}

@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);

if (requestCode==0)
{
if(resultCode == RESULT_OK){
int OrientationSetting = data.getIntExtra("setting",
ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED);
setRequestedOrientation(OrientationSetting);
}
}
}
}


記得在AndroidManifest.xml文件加入SetRequestedOrientationActivity活動.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.AndroidRequestedOrientation"
android:versionCode="1"
android:versionName="1.0">
<application android:icon="@drawable/icon" android:label="@string/app_name">
<activity android:name=".AndroidRequestedOrientation"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".SetRequestedOrientationActivity"></activity>
</application>
<uses-sdk android:minSdkVersion="4" />

</manifest>

2010年10月27日星期三

通過XML設置屏幕方向(android:screenOrientation)

在某些情況下, 程序員要設定屏幕在一定的方向, 這可以通過AndroidManifest.xml設定. 例如:


<activity android:name=".MyActivity"
android:label="@string/app_name"
android:screenOrientation="portrait">


android:screenOrientation設定該活動的方向, 該值可以是任何一個下面的字符串:

"unspecified"
- 默認值. 由系統選擇顯示方向. 在不同的設備可能會有所不同.

"landscape"
- 橫向

"portrait"
- 縱向

"user"
- 用戶當前的首選方向

"behind"
- 與在活動堆棧下的活動相同方向

"sensor"
- 根據物理方向傳感器確定方向. 取決於用戶手持的方向, 當用戶轉動設備, 它跟隨改變.

"nosensor"
- 不經物理方向傳感器確定方向. 該傳感器被忽略, 所以當用戶轉動設備, 顯示不會跟隨改變. 除了這個區別,系統選擇使用相同的政策取向對於“未指定”設置. 系統根據“未指定”("unspecified")設定選擇相同顯示方向.


相關文章: 通過Java程序碼, 運行時設置屏幕方向 - setRequestedOrientation()



2010年10月24日星期日

用戶界面/應用程序訓練猴(Monkey)

猴子(Monkey)是運行在Android模擬器或設備上的一個程序, 它產生偽隨機(pseudo-random)的用戶事件, 例如點擊(clicks), 觸摸(touches), 或手勢(gestures), 以及一些系統級的事件. 可以使用猴子以隨機重複的方式對應用程序進行壓力測試.

下面的指令是使用猴子最簡單的方式, 這將啟動應用程序並發送500個偽隨機事件給它.

$ adb shell monkey -v -p your.package.name 500

如需有關猴子指令的更多選項資料, 可以參閱完整的用戶界面/應用程序訓練猴文檔(UI/Application Exerciser Monkey)頁面.

2010年10月23日星期六

投票: 誰是最好的移動操作系統?

華爾街日報網站的Question of the Day正進行誰是最好的移動操作系統投票, 候選的移動操作系統包括: Apple, Google, Microsoft, Palm, RIM/Blackberry及其他.

包括我的一票, Google現正以49.2%領先.



更新: 目前Microsoft以42.7%領先!


更更新: Microsoft曾一度"不合理地"(純筆者個人意見)領先, 經網上一番熱烈流傳, Google"更不合理地"(純筆者個人意見)以97.4%再度領先.




2010年10月22日星期五

Google I/O 2010 - The world of ListView

ListView是一個最廣泛使用的Android Widget, 也是最複雜的之一.

觀看Youtube視頻"Google I/O 2010 - The world of ListView", 學習如何掌握ListView和了解所有關於它的功能,優化,怪癖和局限性.





2010年10月20日星期三

使用內部存儲(Internal Storage)

可以直接在設備上的內部存儲(Internal Storage)保存文件. 默認情況下, 文件保存到內部存儲是應用程式私有的, 其他應用程序(用戶)無法訪問. 當用戶卸載應用程序, 這些文件也會被刪除.

範例:

使用內部存儲(Internal Storage)

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<EditText
android:id="@+id/input"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/write"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Write"
/>
<Button
android:id="@+id/read"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Read"
/>
<TextView
android:id="@+id/output"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>


主代碼, AndroidInternalStorage.java
package com.AndroidInternalStorage;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class AndroidInternalStorage extends Activity {

String FILENAME = "MyFile";

EditText edittextInput;
TextView textviewOutput;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
edittextInput = (EditText)findViewById(R.id.input);
Button buttonWrite = (Button)findViewById(R.id.write);
Button buttonRead = (Button)findViewById(R.id.read);
textviewOutput = (TextView)findViewById(R.id.output);

buttonWrite.setOnClickListener(buttonWriteOnClickListener);
buttonRead.setOnClickListener(buttonReadOnClickListener);
}

private Button.OnClickListener buttonWriteOnClickListener
= new Button.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

String string = edittextInput.getText().toString();

FileOutputStream fos;
try {
fos = openFileOutput(FILENAME, Context.MODE_PRIVATE);
fos.write(string.getBytes());
fos.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}


}};

private Button.OnClickListener buttonReadOnClickListener
= new Button.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

FileInputStream fis;
try {
fis = openFileInput(FILENAME);
byte[] input = new byte[fis.available()];
while (fis.read(input) != -1) {}
textviewOutput.setText(new String(input));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}



}};
}

2010年10月19日星期二

使用SharedPreferences

SharedPreferences類提供一個保存和檢索持久的鍵值對原始數據類型的框架.

可以使用SharedPreferences保存任何原始數據:布爾型(booleans),浮點(floats),整數(ints),長整數(ongs)和字符串(strings). 這些數據將保持不變(即使應用程序被終止).

使用SharedPreferences

要獲得 SharedPreferences對象, 可以使用兩種方法之一:

- getSharedPreferences() : 如果你需要使用多個Preferences文件, 使用第一個參數指定Preferences文件的名稱.
- getPreferences() : 如果只需要一個Preferences文件.

要寫入:
1。呼叫edit()來獲得SharedPreferences.Editor.
2。呼叫如putBoolean()和putString()添加值.
3。呼叫commit()提交新的值.

讀取, 使用使用SharedPreferences的方法,如getBoolean()和getString().

範例:

main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
<EditText
android:id="@+id/preferencestring"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<Button
android:id="@+id/savepreference"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Save Preference"
/>
<Button
android:id="@+id/restorepreference"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Restore Preference"
/>
<Button
android:id="@+id/exit"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Exit"
/>
</LinearLayout>


主代碼, AndroidPreferences.java
package com.AndroidPreferences;

import android.app.Activity;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;

public class AndroidPreferences extends Activity {

EditText myText;

/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

myText = (EditText)findViewById(R.id.preferencestring);
Button buttonSave = (Button)findViewById(R.id.savepreference);
Button buttonRestore = (Button)findViewById(R.id.restorepreference);
Button buttonExit = (Button)findViewById(R.id.exit);

buttonSave.setOnClickListener(buttonSaveOnClickListener);
buttonRestore.setOnClickListener(buttonRestoreOnClickListener);
buttonExit.setOnClickListener(buttonExitOnClickListener);

SharedPreferences myPreferences = getPreferences(0);
String myPreferencesString = myPreferences.getString("key", "default value");

myText.setText(myPreferencesString);

}

private Button.OnClickListener buttonSaveOnClickListener
= new Button.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub

SharedPreferences settings = getPreferences(0);
SharedPreferences.Editor editor = settings.edit();
editor.putString("key", myText.getText().toString());
editor.commit();

}};

private Button.OnClickListener buttonRestoreOnClickListener
= new Button.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
SharedPreferences myPreferences = getPreferences(0);
String myPreferencesString = myPreferences.getString("key", "default value");

myText.setText(myPreferencesString);
}};

private Button.OnClickListener buttonExitOnClickListener
= new Button.OnClickListener(){

@Override
public void onClick(View v) {
// TODO Auto-generated method stub
finish();
}};

}