Android開發:14個解決實際問題的程式碼片段
在Android編程開發中都會遇到哪些問題呢?在這裡為初學者介紹了十四段簡單實用的代碼,儲存下來需要時輕鬆一鍵獲得。其中包括檢查是否有SD卡,讓某個Activity透明,在螢幕元素中設定控制代碼等等在實際應用經常用到的簡短代碼。
1、查看是否有儲存卡插入
String status=Environment.getExternalStorageState();
if ( status.equals ( Enviroment.MEDIA_MOUNTED ) )
{
說明有SD卡插入
}
2、讓某個Activity透明
OnCreate中不設Layout
this.setTheme(R.style.Theme_Transparent);
以下是Theme_Transparent的定義(注意transparent_bg是一副透明的圖片)
3、在螢幕元素中設定控制代碼
使用Activity.findViewById來取得螢幕上的元素的控制代碼,使用該控制代碼您可以設定或擷取任何該對象外露的值。
TextView msgTextView = (TextView)findViewById(R.id.msg);
msgTextView.setText(R.string.push_me);
4、傳送簡訊
String body=”this is mms demo”;
Intent mmsintent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(”smsto”, number, null));
mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY, body);
mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE, true);
mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT, true);
startActivity(mmsintent);
5、發送多媒體訊息
StringBuilder sb = new StringBuilder();
sb.append(”file://”);
sb.append(fd.getAbsoluteFile());
Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(”mmsto”, number, null));
// Below extra datas are all optional.
intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_SUBJECT, subject);
intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY, body);
intent.putExtra(Messaging.KEY_ACTION_SENDTO_CONTENT_URI, sb.toString());
intent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE, composeMode);
intent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT, exitOnSent);
startActivity(intent);
6、顯示toast
view plaincopy
Toast.makeText(this._getApplicationContext(), R.string._item, Toast.LENGTH_SHORT).show();
7、發送Mail
mime = “img/jpg”;
shareIntent.setDataAndType(Uri.fromFile(fd), mime);
shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(fd));
shareIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
shareIntent.putExtra(Intent.EXTRA_TEXT, body);
8、註冊一個BroadcastReceiver
registerReceiver(mMasterResetReciever, new IntentFilter(”OMS.action.MASTERRESET”));
private BroadcastReceiver mMasterResetReciever = new BroadcastReceiver()
{
public void onReceive(Context context, Intent intent)
{
String action = intent.getAction();
if (”oms.action.MASTERRESET”.equals(action) )
{
RecoverDefaultConfig();
}
}
};
9、定義ContentObserver,監聽某個資料表
private ContentObserver mDownloadsObserver = new DownloadsChangeObserver(Downloads.CONTENT_URI);
private class DownloadsChangeObserver extends ContentObserver
{
public DownloadsChangeObserver(Uri uri)
{
super(new Handler());
}
@Override
public void onChange(boolean selfChange) {}
}
10、獲得手機UA
public String getUserAgent()
{
String user_agent = ProductProperties.get(ProductProperties.USER_AGENT_KEY, null);
return user_agent;
}
11、清空手機上cookie
CookieSyncManager.createInstance (getApplicationContext() );
CookieManager.getInstance().removeAllCookie();
12、建立GPRS串連
//Dial the GPRS link.
private boolean openDataConnection()
{
// Set up data connection.
DataConnection conn = DataConnection.getInstance();
if ( connectMode == 0 )
{
ret = conn.openConnection ( mContext, “cmwap”, "cmwap”, "cmwap” );
}
else
{
ret = conn.openConnection(mContext, “cmnet”, "", "");
}
}
13、PreferenceActivity 用法
public class Setting extends PreferenceActivity
{
public void onCreate ( Bundle savedInstanceState )
{
super.onCreate ( savedInstanceState );
addPreferencesFromResource ( R.xml.settings );
}
}
Setting.xml:
[java]
Android:key=”seting2″
android:title=”@string/seting2″
android:summary=”@string/seting2″/>
android:key=”seting1″
android:title=”@string/seting1″
android:summaryOff=”@string/seting1summaryOff”
android:summaryOn=”@stringseting1summaryOff”/>
14、通過HttpClient從指定server擷取資料
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet method = new HttpGet(“/templets/default/index.html”);
HttpResponse resp;
Reader reader = null;
try {
// AllClientPNames.TIMEOUT
HttpParams params = new BasicHttpParams();
params.setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, 10000);
httpClient.setParams(params);
resp = httpClient.execute(method);
int status = resp.getStatusLine().getStatusCode();
if (status != HttpStatus.SC_OK)
{
return false;
}
// HttpStatus.SC_OK;
return true;
}
catch (ClientProtocolException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally
{
if (reader != null)
try
{
reader.close();
}
catch (IOException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
}