【Android源码 栏目提醒】:网学会员为需要Android源码 的朋友们搜集整理了项目中用到的Android代码整理 - 培训资料相关资料,希望对各位网友有所帮助!
f7f1、全屏窗口requestWindowFeatureWindow.FEATURE_NO_TITLEgetWindow.setFlagsWindowManager.LayoutParams.FLAG_FULLSCREENWindowManager.LayoutParams.FLAG_FULLSCREEN Preference ActivityLayoutcrc.xmlltxml versionquot1.0quot encodingquotutf-8quot gt ltPreferenceScreen xmlns:androidquothttp://schemas.
android.com/apk/res/androidquotgt ltPreferenceCategory
android:titlequotCRC Testquotgt ltPreferenceScreen
android:titlequot1. BIN CRCquot
android:summaryquotCode Area CRCquot
android:keyquotbin_crcquotgt lt/PreferenceScreengt ltPreferenceScreen
android:titlequot2. EFS CRC Detailquot
android:summaryquotEFS CRC Detailquot
android:keyquotefs_crcquotgt ltintent
android:actionquotandroid.intent.action.MAINquot
android:targetPackagequotcom.dhz.testappquot
android:targetClassquotcom.dhz.testapp.efscrcquot/gt lt/PreferenceScreengt lt/PreferenceCategorygtlt/PreferenceScreengt 2、Preference 单单单单添加理PreferenceScreen BINCRC PreferenceScreengetPreferenceScreen.findPreferencequotbin_crcquotBINCRC.setOnPreferenceClickListenernew Preference.OnPreferenceClickListener public boolean onPreferenceClickPreference preference BINCRC.setSummaryquotDetect a clickquot return true 3单单单单、运行一个命令或程序取果/单单单单单单单单正表达式找匹配/分隔字符串Process process1 new ProcessBuilderquotcatquot quot/opl/etc/system.propquot.start BufferedReader br1 new BufferedReadernew InputStreamReaderprocess1.getInputStream Pattern pattern Pattern.compilequotapps.setting.platformversionquot String line while line br1.readLine null Matcher matcher pattern.matcherline ifmatcher.find String temp line.splitquot quot iftemp.length gt 1 mRver.setSummarytemp1 else mRver.setSummaryquot/opl/etc/system.prop not configed well.quot ifprocess1 null process1.destroy ifbr1 null br1.close 4单单单单单单单、算一个文件的CRC32单import java.util.zip.CRC32FileInputStream inStream null BufferedInputStream in null CRC32 crc32 new CRC32 inStream new FileInputStreamfilePath in new BufferedInputStreaminStreamsize_8k forint iiin.read-1 crc32.updatei Log.dTAG filePath quot CRC32: quotLong.toHexStringcrc32.getValue ifinStream null inStream.close ifin null in.close 5单单单单单单单单单单单、示一个模框yes/no单按new AlertDialog.Builderefscrc.this .setMessagequotWork Done Show resultsquot .setCancelablefalse .setPositiveButtonquotYesquot new Dialog public void onClickDialogInterface dialogint whichButton showResult .setNegativeButtonquotNoquot new DialogInterface.OnClickListener public void onClickDialogInterface dialogint whichButton dialog.dismiss .show 6、判断是否有SDCard if Environment.getExternalStorageState.equalsEnvironment.MEDIA_MOUNTED copyToSDCardlogFilePath else Toast.makeTextFPRITest.thisquotNo SDCard Please insert SDCard. quotToast.LENGTH_SHORT.show 7单单单单单、果集排序/List单遍ListltStringgt resultList new ArrayListltStringgtresultList.addstr1......resultList.addstrnCollections.sortresultListFileOutputStream outStream new FileOutputStreamefsCRCResultFileIterator itr resultList.iteratorwhile itr.hasNext outStream.writeStringitr103f.next.getBytes 8单单单单单单单单单单单单单单单单单单单、非方法枚目下所有文件含子目private void getFileListString dirPath LinkedListltFilegt mDirList new LinkedListltFilegt File dir new FiledirPath mDirList.adddirFile files null int count 0 String filePath null File tmp null while mDirList.isEmpty tmp mDirList.removeFirst //handle files in one directory. files tmp.listFiles if files null continue for int i 0 i lt files.length i if filesi.isDirectory mDirList.addfilesi else Log.dTAGfilesi.getAbsolutePath quot quot count count Log.dTAGquotgetFileList finishfile count: quot count 9单单单单单、添加秘密程序通号启AndroidManifest.xmlltreceiver
android:namequot.secretquotgt ltintent-filtergt ltaction
android:namequotandroid.provider.Telephony.SECRET_CODEquot /gt ltdata
android:schemequotandroid_secret_codequot
android:hostquot1234quot/gt lt/intent-filtergtlt/receivergtsecret.javapublic class secret extends BroadcastReceiver Override public void onReceiveContext context Intent intent String action intent.getAction String host intent.getData null intent.getData.getHost : null if Intents.SECRET_CODE_ACTION.equalsaction ampamp quot1234quot.equalshost //start an acitivity SECRET_CODE_ACTIONpublic static final String SECRET_CODE_ACTION Broadcast Action: A quotsecret codequot has been entered in the dialer. Secret codes are of the form . The intent will have the data URI:
android_secret_code://ltcodegt 10、格式化SD卡/private IMountService mMountServicemMountService getMountServiceprivate synchronized IMountService getMountService if mMountService null IBinder service ServiceManager.getServicequotmountquot if service null mMountService IMountService.Stub.asInterfaceservice else Log.eTAG quotCant get mount servicequot return mMountService //format sdcardmMountService.formatMediaEnvironment.getExternalStorageDirectory.toString//unmount sdcardmMountService.unmountMediaEnvironment.getExternalStorageDirectory.toString 11、保持屏幕常亮PowerManager.WakeLock wakeLock12、启用屏幕常亮功能wakeLock PowerManagergetSystemServicePOWER_SERVICE.newWakeLockPowerManager.SCREEN_BRIGHT_WAKE_LOCK PowerManager.ON_AFTER_RELEASE quotMyActivityquotwakeLock.acquire//PowerManager.SCREEN_DIM_WAKE_LOCK 单单单单单单单单单单单单单单单单单单单单个可持在低明状有其他的志可参考Andoid文档13单单单单单单单单、屏幕常亮功能if wakeLock null wakeLock.release15单单、需要限ltuses-permission
android:namequotandroid.permission.WAKE_LOCKquot /gt单单单单单单单单单单单单单单单单单单单单单单单单单单单单 了不其他程序造成影响启用和屏幕常亮的代一般被放在Activity 的onResume 和onPause 事件中。
单用setting的校准屏幕功能Intent intent new Intentintent.setActionquotandroid.intent.action.MAINquotintent.setComponentnew ComponentNamequotcom.
android.settingsquotquotcom.
android.settings.CalibrationquotstartActivityintent16、DOM解析XML文档DOM单XML 单单单单单单单单单单单单单单单单单单单单单单单单单文档的解析定了一接口。
解析器入整个文档然后构建一个留单单单单单单单单单单单单单 内存的构然后代就可以使用DOM 单单单单单单接口来操作个构。
单单单单单单单单单单单单单单单单单单单单单单单单单单单单单单点整个文档在内存中便于操作支持除、修改、重新排列等多功能单单单单单单单单单单单单单单单单单单单单单单缺点将整个文档入内存包括无用的点浪和空单单单单单单单单单单单单单单单单单单单单单单单单单单单单单单单使用合一旦解析了文档需多次些数据硬件源充足内存、CPU。
public void parserXmlString fileName try DocumentBuilderFactory dbf DocumentBuilderFactory.newInstance DocumentBuilder db dbf.newDocumentBuilder Document document db.parsefileName NodeList employees document.getChildNodes for int i 0 i lt employees.getLength i 103f NodeList paramList document.getElementsByTagNamequotyourTagquot forint i0 iltparamList.getLength i Node paramNode paramList.itemi NamedNodeMap attrs paramNode.getAttributes forint j0 jltattrs.getLengthj String itemName attrs.itemj.getNodeName String itemVal attrs.itemj.getNodeValue catch Exception e e.printStackTrace //////////////////////////androin 单单单有用的代片段1单单单单单单单单单单看是否有存卡插入String statusEnvironment.getExternalStorageStateifstatus.equalsEnviroment.MEDIA_MOUNTED 单明有SD卡插入2单单单某个Activity透明OnCreate单中不Layout this.setThemeR.style.Theme_Transparent以下是Theme_Transparent单单单单 的定注意transparent_bg单单单是一副透明的片3单单单单在屏幕元素中置句柄使用Activity.findViewById来取得屏幕上的元素的句柄. 单单单单单单单单单单单单单使用句柄您可以置或取任何单单单象外露的.TextView msgTextView TextViewfindViewByIdR.id.msg msgTextView.setTextR.string.push_me 4单单单单送短信 String body”this is mms demo” Intent mmsintent new IntentIntent.ACTION_SENDTO Uri.fromParts”smsto” number null mmsintent.putExtraMessaging.KEY_ACTION_SENDTO_MESSAGE_BODY body mmsintent.putExtraMessaging.KEY_ACTION_SENDTO_COMPOSE_MODE true mmsintent.putExtraMessaging.KEY_ACTION_SENDTO_EXIT_ON_SENT true startActivitymmsintent5单单单单送彩信 StringBuilder sb new StringBuilder sb.append”file://” sb.appendfd.getAbsoluteFile Intent intent new IntentIntent.ACTION_SENDTO Uri.fromParts”mmsto” number null // Below extra datas are all optional. intent.putExtraMessaging.KEY_ACTION_SENDTO_MESSAGE_SUBJECT subject intent.putExtraMessaging.KEY_ACTION_SENDTO_MESSAGE_BODY body intent.putExtraMessaging.KEY_ACTION_SENDTO_CONTENT_URI sb.toString intent.putExtraMessaging.KEY_ACTION_SENDTO_COMPOSE_MODE composeMode intent.putExtraMessaging.KEY_ACTION_SENDTO_EXIT_ON_SENT exitOnSent startActivityintent6单单送Mail mime “img/jpg” shareIntent.setDataAndTypeUri.fromFilefd mime shareIntent.putExtraIntent.EXTRA_STREAM Uri.fromFilefd shareIntent.putExtraIntent.EXTRA_SUBJECT subject shareIntent.putExtraIntent.EXTRA_TEXT body7注册一个BroadcastReceiverregisterReceivermMasterResetReciever new IntentFilter”oms.action.MASTERRESET”private BroadcastReceiver mMasterResetReciever new BroadcastReceiver public void onReceiveContext context Intent intent String action intent.getAction if”oms.action.MASTERRESET”.equalsaction RecoverDefaultConfig 8 单定ContentObserver单单单单单单单听某个数据表private ContentObserver mDownloadsObserver new DownloadsChangeObserverDownloads.CONTENT_URIprivate class DownloadsChangeObserver extends ContentObserver public DownloadsChangeOb supernew Handler Override public void onChangeboolean selfChange 9单 得手机UApublic String getUserAgent String user_agent ProductProperties.getProductProperties.USER_AGENT_KEY null return user_agent 10清空手机上CookieCookieSyncManager.createInstancegetApplicationContext CookieManager.getInstance.removeAllCookie11建立GPRS单接 //Dial the GPRS link. private boolean openDataConnection // Set up data connection. DataConnection conn DataConnection.getInstance if connectMode 0 ret conn.openConnectionmContext “cmwap” “cmwap” “cmwap” 103f else ret conn.openConnectionmContext “cmnet” “” “” 12PreferenceActivity 用法public class Setting extends PreferenceActivity public void onCreateBundle savedInstanceState super.onCreatesavedInstanceState addPreferencesFromResourceR.xml.settings Setting.xml:
android:key”seting2〃
android:title”string/seting2〃
android:summary”string/seting2〃/gt
android:key”seting1〃
android:title”string/seting1〃
android:summaryOff”string/seting1summaryOff”
android:summaryOn”stringseting1summaryOff”/gt13单通HttpClient从指定server单取数据 DefaultHttpClient httpClient new DefaultHttpClient HttpGet method new HttpGet“http://www.baidu.com/1.html” HttpResponse resp Reader reader null try // AllClientPNames.TIMEOUT HttpParams params new BasicHttpParams params.setIntParameterAllClientPNames.CONNECTION_TIMEOUT 10000 httpClient.setParamsparams resp httpClient.executemethod 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 14单单示toastToast.makeText ///////////////////////////
android 单单单常用代示例///////////////////////////1、Intent用法2010-04-27 12:09Intent it new IntentActivity.Main.this Activity2.class startActivityit 2. 向下一个Activity单单数据使用Bundle和Intent.putExtras Intent it new IntentActivity.Main.this Activity2.class Bundle bundlenew Bundle bundle.putStringquotnamequot quotThis is from MainActivityquot it.putExtrasbundle // it.putExtra“test” quotshuju” startActivityit // startActivityForResultitREQUEST_CODE 单 单单单单单单单 于数据的取可以采用Bundle bundlegetIntent.getExtras String namebundle.getStringquotnamequot 3. 向上一个Activity单单单单单返回果使用setResult单单startActivityForResultitREQUEST_CODE单 启的Activity Intent intentgetIntent Bundle bundle2new Bundle bundle2.putStringquotnamequot quotThis is from ShowMsgquot intent.putExtrasbundle2 setResultRESULT_OK intent 4. 单单单单回上一个Activity单单单单单单单的果理函数onActivityResult Override protected void onActivityResultint requestCode int resultCode Intent data // TODO Auto-generated method stub super.onActivityResultrequestCode resultCode data if requestCodeREQUEST_CODE ifresultCodeRESULT_CANCELED setTitlequotcanclequot else if resultCodeRESULT_OK String tempnull Bundle bundledata.getExtras ifbundlenull tempbundle.getStringquotnamequot setTitletemp 5、单单 示网Uri uri Uri.parsequothttp://google.comquot Intent it new IntentIntent.ACTION_VIEW uri startActivityit 6、单单 示地Uri uri Uri.parsequotgeo:38.899533-77.036476quot Intent it new IntentIntent.ACTION_VIEW uri startActivityit 其他geo URI 范例geo:latitudelongitude geo:latitudelongitudezzoom geo:00qmystreetaddress geo:00qbusinessnearcity google.streetview:cblllatlngampcbp1yawpitchzoomampmzmapZoom 7、单单 路径划Uri uri Uri.parsequothttp://maps.google.com/efcmapsfdampsaddrstartLat20startLngampdaddrendLat20endLngamphlenquot Intent it new IntentIntent.ACTION_VIEW uri startActivityit //where startLat startLng endLat endLng are a long with 6 decimals like: 50.123456 单单 打1. //单单单单 叫出号程序2. Uri uri Uri.parsequottel:0800000123quot 3. Intent it new IntentIntent.ACTION_DIAL uri 4. startActivityit 1. //单单单单 直接打出去2. Uri uri Uri.parsequottel:0800000123quot 3. Intent it new IntentIntent.ACTION_CALL uri 4. startActivityit 5. // 用这个要在AndroidManifest.xml 中加上6. //ltuses-permission idquotandroid.
上一篇:
android应用框架分析
下一篇:
7*30m公路预应力混凝土连续梁桥上部结构设计