Android开发常用经典代码段集锦
本文实例总结了Android开发常用经典代码段。分享给大家供大家参考,具体如下:
1、图片旋转
BitmapbitmapOrg=BitmapFactory.decodeResource(this.getContext().getResources(),R.drawable.moon); Matrixmatrix=newMatrix(); matrix.postRotate(-90);//旋转的角度 BitmapresizedBitmap=Bitmap.createBitmap(bitmapOrg,0,0, bitmapOrg.getWidth(),bitmapOrg.getHeight(),matrix,true); BitmapDrawablebmd=newBitmapDrawable(resizedBitmap);
2、获取手机号码
//创建电话管理 TelephonyManagertm=(TelephonyManager) //与手机建立连接 activity.getSystemService(Context.TELEPHONY_SERVICE); //获取手机号码 StringphoneId=tm.getLine1Number(); //记得在manifestfile中添加 <uses-permission android:name="android.permission.READ_PHONE_STATE"/> //程序在模拟器上无法实现,必须连接手机
3.格式化string.xml中的字符串
//instrings.xml.. <stringname="my_text">Thanksforvisiting%s.Youageis%d!</string> //andinthejavacode: String.format(getString(R.string.my_text),"oschina",33);
4、android设置全屏的方法
A.在java代码中设置
/**全屏设置,隐藏窗口所有装饰*/ requestWindowFeature(Window.FEATURE_NO_TITLE); getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
B、在AndroidManifest.xml中配置
<activityandroid:name=".Login.NetEdit"android:label="@string/label_net_Edit" android:screenOrientation="portrait"android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen"> <intent-filter> <actionandroid:name="android.intent.Net_Edit"/> <categoryandroid:name="android.intent.category.DEFAULT"/> </intent-filter> </activity>
5、设置Activity为Dialog的形式
在AndroidManifest.xml中配置Activity节点是配置theme如下:
android:theme="@android:style/Theme.Dialog"
6、检查当前网络是否连上
ConnectivityManagercon=(ConnectivityManager)getSystemService(Activity.CONNECTIVITY_SERVICE); booleanwifi=con.getNetworkInfo(ConnectivityManager.TYPE_WIFI).isConnectedOrConnecting(); booleaninternet=con.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).isConnectedOrConnecting();
在AndroidManifest.xml增加权限:
<uses-permissionandroid:name="android.permission.ACCESS_NETWORK_STATE"/>
7、检测某个Intent是否有效
publicstaticbooleanisIntentAvailable(Contextcontext,Stringaction){ finalPackageManagerpackageManager=context.getPackageManager(); finalIntentintent=newIntent(action); List<ResolveInfo>list= packageManager.queryIntentActivities(intent, PackageManager.MATCH_DEFAULT_ONLY); returnlist.size()>0; }
8、android拨打电话
try{ Intentintent=newIntent(Intent.ACTION_CALL); intent.setData(Uri.parse("tel:+110")); startActivity(intent); }catch(Exceptione){ Log.e("SampleApp","Failedtoinvokecall",e); }
9、android中发送Email
Intenti=newIntent(Intent.ACTION_SEND); //i.setType("text/plain");//模拟器请使用这行 i.setType("message/rfc822");//真机上使用这行 i.putExtra(Intent.EXTRA_EMAIL,newString[]{"test@gmail.com","test@163.com}); i.putExtra(Intent.EXTRA_SUBJECT,"subjectgoeshere"); i.putExtra(Intent.EXTRA_TEXT,"bodygoeshere"); startActivity(Intent.createChooser(i,"Selectemailapplication."));
10、android中打开浏览器
IntentviewIntent=new Intent("android.intent.action.VIEW",Uri.parse("http://vaiyanzi.cnblogs.com")); startActivity(viewIntent);
11、android获取设备唯一标识码
Stringandroid_id=Secure.getString(getContext().getContentResolver(),Secure.ANDROID_ID);
12、android中获取IP地址
publicStringgetLocalIpAddress(){ try{ for(Enumeration<NetworkInterface>en=NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();){ NetworkInterfaceintf=en.nextElement(); for(Enumeration<InetAddress>enumIpAddr=intf.getInetAddresses(); enumIpAddr.hasMoreElements();){ InetAddressinetAddress=enumIpAddr.nextElement(); if(!inetAddress.isLoopbackAddress()){ returninetAddress.getHostAddress().toString(); } } } }catch(SocketExceptionex){ Log.e(LOG_TAG,ex.toString()); } returnnull; }
13、android获取存储卡路径以及使用情况
/**获取存储卡路径*/ FilesdcardDir=Environment.getExternalStorageDirectory(); /**StatFs看文件系统空间使用情况*/ StatFsstatFs=newStatFs(sdcardDir.getPath()); /**Block的size*/ LongblockSize=statFs.getBlockSize(); /**总Block数量*/ LongtotalBlocks=statFs.getBlockCount(); /**已使用的Block数量*/ LongavailableBlocks=statFs.getAvailableBlocks();
14android中添加新的联系人
privateUriinsertContact(Contextcontext,Stringname,Stringphone){ ContentValuesvalues=newContentValues(); values.put(People.NAME,name); Uriuri=getContentResolver().insert(People.CONTENT_URI,values); UrinumberUri=Uri.withAppendedPath(uri,People.Phones.CONTENT_DIRECTORY); values.clear(); values.put(Contacts.Phones.TYPE,People.Phones.TYPE_MOBILE); values.put(People.NUMBER,phone); getContentResolver().insert(numberUri,values); returnuri; }
15、查看电池使用情况
IntentintentBatteryUsage=newIntent(Intent.ACTION_POWER_USAGE_SUMMARY); startActivity(intentBatteryUsage);
16、获取进程号
ActivityManagermActivityManager=(ActivityManager)this.getSystemService(ACTIVITY_SERVICE); List<ActivityManager.RunningAppProcessInfo>mRunningProcess=mActivityManager.getRunningAppProcesses(); inti=1; for(ActivityManager.RunningAppProcessInfoamProcess:mRunningProcess){ Log.e("homerApplication",(i++)+"PID="+amProcess.pid+";processName="+amProcess.processName); }
更多关于Android相关内容感兴趣的读者可查看本站专题:《Android开发入门与进阶教程》、《Android控件用法总结》、《Android短信与电话操作技巧汇总》及《Android多媒体操作技巧汇总(音频,视频,录音等)》
希望本文所述对大家Android程序设计有所帮助。