【Android源码 栏目提醒】:以下是网学会员为您推荐的Android源码 -Android代码片段 - 培训资料,希望本篇文章对您学习有所帮助。
1查看是否有存储卡插入 String statusEnvironment.getExternalStorageState ifstatus.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 startActivitymmsintent 5发送彩信 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 startActivityintent 6发送Mail mime “img/jpg” shareIntent.setDataAndTypeUri.fromFilefd mime shareIntent.putExtraIntent.EXTRA_STREAM Uri.fromFilefd shareIntent.putExtraIntent.EXTRA_SUBJECT subject shareIntent.putExtraIntent.EXTRA_TEXT body 7注册一个BroadcastReceiver registerReceivermMasterResetReciever 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_URI private class DownloadsChangeObserver extends ContentObserver public DownloadsChangeObserverUri uri supernew Handler Override public void onChangeboolean selfChange 9获得 手机UA public String getUserAgent String user_agent ProductProperties.getProductProperties.USER_AGENT_KEY null return user_agent 10清空手机上Cookie CookieSyncManager.createInstancegetApplicationContext CookieManager.getInstance.removeAllCookie 11建立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” 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”/gt 13通过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显示toast Toast.makeTextthis._getApplicationContext R.string._item Toast.LENGTH_SHORT.show 15屏幕显示 程序中默的显示是带有标题栏和系统信息栏的有的时候这很影响程序界面的美观。
手机默认的是竖屏或与感应器状态相关为了某种效果我们的程序需要限制使用横屏或竖屏。
以下的代码就解决了上述问题。
//设置为无标题栏 requestWindowFeatureWindow.FEATURE_NO_TITLE //设置为全屏模式 getWindow.setFlagsWindowManager.LayoutParams.FLAG_FULLSCREEN WindowManager.LayoutParams.FLAG_FULLSCREEN //设置为横屏 setRequestedOrientationActivityInfo.SCREEN_ORIENTATION_LANDSCAPE 16Intent传参 当Activity与Activity/Service或其它情况有时与要进行参数传递最常用也是最简单的方式就是通过Intent来处理。
看如下代码 Intent intent new Intent... Bundle bundle new Bundle bundle.putStringquotNAMEquot quotzixuanquot intent.putExtrasbundle context.startActivityintent 或 context.startServiceintent 当然有传送就有接收接收也很简单如 Bundle bunde intent.getExtras String name bunde.getIntquotNAMEquot 当然参数KEY要与传送时的参数一致。
17获取手机号 在j2me中根本没有办法获取用户的手机号码就连获取手机串号IMEI都基本上无法实现然后在
android手机上一切都是如此的简单看代码 TelephonyManager tm TelephonyManagercontext.getSystemServiceContext.TELEPHONY_SERVICE String imei tm.getDeviceId String tel tm.getLine1Number 看来
android的确加速了j2me的消亡。
18振动器 总感觉手机上的振动器没有多大用处当然静音模式下的振铃很有用但还是顺带着说一下吧只有两行代码 1、获取振动服务的实例 Vibrator vibrator Vibrator getSystemServiceContext.VIBRATOR_SERVICE 2、设置振动时长单位当然也是ms vibrator.vibrate1000 如果你觉得这样过去单调的话可以设个节奏 vibrator.vibratenew long10 100 20 200 -1 两个参数习惯告诉我第一个是节奏第二个是重复次数可事实并没有这么简单我翻译不好大家还是看原文吧 public void vibrate long pattern int repeat pattern: an array of longs of times to turn the vibrator on or off. repeat: the index into pattern at which to repeat or -1 if you dont want to repeat. google喜欢弄些技巧我却觉得这里有点弄巧成拙了。
19闹钟管理 最近看了一下
Android的闹钟管理类AlarmManager真不错误强大又简单代码如下 1、建立一个AlarmReceiver继承入BroadcastReceiver并在AndroidManifest.xml声明 public static class AlarmReceiver extends BroadcastReceiver Override public void onReceiveContext context Intent intent Toast.makeTextcontext quot闹钟提示时间到quot Toast.LENGTH_LONG.show 2、建立Intent和PendingIntent来调用目标组件。
Intent intent new Intentthis AlarmReceiver.class PendingIntent pendingIntent PendingIntent.getBroadcastthis 0 intent 0 3、设置闹钟 获取闹钟管理的实例 AlarmManager alarmManager AlarmManager getSystemServiceContext.ALARM_SERVICE 设置单次闹钟 alarmManager.setAlarmManager.RTC_WAKEUP System.currentTimeMillis 51000 pendingIntent 设置周期闹钟 alarmManager.setRepeatingAlarmManager.RTC_WAKEUP System.currentTimeMillis 101000 2460601000 pendingIntent 20开机自启动 1.定义一个BroadcastReceiver public class BootReceiver extends BroadcastReceiver public void onReceiveContext ctx Intent intent Log.dquotBootReceiverquot quotsystem boot completedquot//start activityString actionquotandroid.intent.action.MAINquotString categoryquotandroid.intent.category.LAUNCHERquotIntent myinew IntentctxCustomDialog.classmyi.setActionactionmyi.addCategorycategorymyi.addFlagsIntent.FLAG_ACTIVITY_NEW_TASKctx.startActivitymyi//start serviceIntent snew IntentctxMyService.classctx.startServices 2.配置Receiver的许可允许接收系统启动消息在AndroidManifest.xml中 ltuses-permission
android:namequotandroid.permission.RECEIVE_BOOT_COMPLETEDquot/gt 3.配置Receiver可以接收系统启动消息在AndroidManifest.xml中 ltreceiver
android:namequot.app.BootReceiverquotgt ltintent-filtergt ltaction
android:namequotandroid.intent.action.BOOT_COMPLETEDquot/gt ltcategory
android:namequotandroid.intent.category.HOMEquot /gt lt/intent-filtergt lt/receivergt 4.启动模拟器可以看到系统启动后弹出一个对话框。
1、设置窗口格式为半透明 getWindow.setFormatPixelFormat.TRANSLUCENT 2、
Android中在非UI线程里更新View的不同方法 Activity.runOnUiThread Runnable View.post Runnable View.postDelayed Runnable long Hanlder 3、全屏显示窗口 requestWindowFeatureWindow.FEATURE_NO_TITLE getWindow.setFlagsWindowManager.LayoutParams.FLAG_FULLSCREEN WindowManager.LayoutParams.FLAG_FULLSCREEN 4、取得屏幕大小 方法A WindowManager windowManager getWindowManager Display display windowManager.getDefaultDisplay hAndW0 display.getWidth hAndW1 display.getHeight 方法B DisplayMetrics dm new DisplayMetrics getWindowManager.getDefaultDisplay.getMetricsdm hAndW0 dm.widthPixels hAndW1 dm.heightPixels 5、调浏览器 载入网址 Uri uri Uri.parsequothttp://www.google.comquot Intent it new IntentIntent.ACTION_VIEW uri startActivityit 6、取得内存大小 ActivityManager.MemoryInfo outInfo new ActivityManager.MemoryInfo activityManager.getMemoryInfooutInfo //可用内存 outInfo.availMem //是否在低内存状态 outInfo.lowMemory 取得ScrollView的实际高度 scrollview.getHeight scrollview.getMeasuredHeight scrollview.compute scrollview.getLayoutParams.height 7、监听App安装/卸载事件 A.Define a class derived from class BroadcastReceiver B.Register broadcast receiver MyBroadcastReceiver myReceiver new MyBroadcastReceiver IntentFilter filter new IntentFilterIntent.ACTION_PACKAGE_INSTALL filter.addActionIntent.ACTION_PACKAGE_REMOVED filter.addActionIntent.ACTION_PACKAGE_ADDED filter.addActionIntent.ACTION_PACKAGE_CHANGED filter.addActionIntent.ACTION_PACKAGE_RESTARTED ... filter.addDataSchemequotpackagequot //This line is very important. Otherwise broadcast cant be received. registerReceivermyReceiver filter Notes: The package name is Intent.mData. Intent.mData is not available in SDK 1.0 but it can be retrieved by calling Intent.getDataString 8、取得IP地址 A. //Connect via WIFI 通过wifi WifiManager wifiManager WifiManager getSystemServiceWIFI_SERVICE WifiInfo wifiInfo wifiManager.getConnectionInfo int ipAddress wifiInfo.getIpAddress B. //Connect via GPRS通过gprs public String getLocalIpAddress try forEnumerationltNetworkInterfacegt en NetworkInterface.getNetworkInterfaces en.hasMoreElements NetworkInterface intf en.nextElement for EnumerationltInetAddressgt enumIpAddr intf.getInetAddresses enumIpAddr.hasMoreElements InetAddress inetAddress enumIpAddr.nextElement if inetAddress.isLoopbackAddress return inetAddress.getHostAddress.toString catch SocketException ex Log.eS.TAG ex.toString return null 9、ListView 后面adapter数据已更改但是ListView没有收到Notification 首先必须将 更新adapter数据的代码放在Handler.postRunnable方法中执行 然后如果Adapter数据的来源如果是cursorCursorAdapter的话 可以cursor.requery一下如果是别的可以强制调用一下notifyChange notifyChange 会调用 invalidate 进行重绘 10、模拟HOME键 Intent inew IntentIntent.ACTION_MAIN i.addCategoryIntent.CATEGORY_HOME i.addFlagsIntent.FLAG_ACTIVITY_NEW_TASK context.startActivityi 11、设置焦点 editText.setFocusabletrue editText.requestFocus editText.setFocusableInTouchModetrue TextView跑马灯效果:
android:layout_width quot100pxquot
android:layout_height quotwrap_contentquot
android:textColor quotandroid:color/whitequot
android:ellipsize quotmarqueequot
android:focusable quottruequot
android:marqueeRepeatLimit quotmarquee_foreverquot
android:focusableInTouchMode quottruequot
android:scrollHorizontally quottruequot
android:text quot这才是真正的文字跑马灯效果quotgt 发送邮件: Intent intent new Intentandroid.content.Intent.ACTION_SEND File file new FileEnvironment.getExternalStorageDirectory .getPath File.separator quotfirst.txtquot intent.putExtraandroid.content.Intent.EXTRA_EMAIL new String quotmadgoatqq.comquot intent.putExtraandroid.content.Intent.EXTRA_SUBJECT quotHello Madgoatquot intent.putExtraandroid.content.Intent.EXTRA_TEXT quotDear Madgoat:ntThis a test mail from
android client.nThanks for you visit http://madgoat.cn quot intent.setTypequotapplication/octet-streamquot //当无法确认发送类型的时候使用如下语句 //intent.setTypequot/quot //当没有附件纯文本发送时使用如下语句 //intent.setTypequotplain/textquot intent.putExtraIntent.EXTRA_STREAM Uri.fromFilefile startActivityIntent.createChooserintent quotMail Testquot
android中执行Shell命令或者脚本 public String execCommandString command throws IOException // start the ls command running Runtime runtime Runtime.getRuntime Process proc runtime.execcommand // 这句话就是shell与高级语言间的调用 // 如果有参数的话可以用另外一个被重载的exec方法 // 实际上这样执行时启动了一个子进程它没有父进程的控制台 // 也就看不到输出所以我们需要用输出流来得到shell执行后的输出 InputStream inputstream proc.getInputStream InputStreamReader inputstreamreader new InputStreamReaderinputstream BufferedReader bufferedreader new BufferedReaderinputstreamreader // read the ls output String line quotquot StringBuilder sb new StringBuilderline while line bufferedreader.readLine null // System.out.printlnline sb.appendline sb.appendn // 使用exec执行不会等执行成功以后才返回它会立即返回 // 所以在某些情况下是很要命的比如复制文件的时候 // 使用wairFor可以等待命令执行完成以后才返回 try if proc.waitFor 0 System.err.printlnquotexit value quot proc.exitValue catch InterruptedException e System.err.printlne return sb.toString 另一段执行Shell的代码 Process process Runtime.getRuntime.execquotsuquot DataOutputStream os new DataOutputStreamprocess.getOutputStream DataInputStream osRes new DataInputStreamprocess.getInputStream for String single : commands os.writeBytessingle quotnquot os.flush res.addosRes.readLine os.writeBytesquotexitnquot os.flush process.waitFor 禁止横屏重建Activity在AndroidManifest.xml的Activity属性中添加如下值
android:configChangesquotkeyboardHiddenorientationquot
android:configChangesquotkeyboardHiddenorientationquot
Android 获取MIEI ISMI Sim卡串号等等信息 TelephonyManager telephonemanage TelephonyManager getWindow .getContext.getSystemServiceContext.TELEPHONY_SERVICE try .
上一篇:
04_Android的底层库和程序
下一篇:
谈谈初学者怎样突破英语音标