Skip to main content
 Web开发网 » 操作系统 » linux系统

常用的Android编程代码总结

2021年10月14日7150百度已收录

1. android dp与px相互转换

public class DensityUtil{

public static int dip2px(Contextcontext,floatdpValue){

final float scale=context.getResources().getDisplayMetrics().density;

return(int)(dpValue*scale+0.5f);

public static int px2dip(Contextcontext,floatpxValue){

final float scale=context.getResources().getDisplayMetrics().density;

return(int)(pxValue/scale+0.5f);

2.android 对话框

<stylename="MyDialog"parent="@android:Theme.Dialog">

<itemname="android:windowNoTitle">true</item>

<itemname="android:windowBackground">@color/ha</item>

</style>

3.android 依据uri获取路径

Uri uri=data.getData();

String[] proj={MediaStore.Images.Media.DATA};

Cursor actualimagecursor=managedQuery(uri,proj,null,null,null);

intactual_image_column_index=actualimagecursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);

actualimagecursor.moveToFirst();

String img_path=actualimagecursor.getString(actual_image_column_index);

File file=new File(img_path);

4.android 依据uri获取真正路径

public static String getRealFilePath(finalContextcontext,finalUriuri){

if(null==uri)return null;

final String scheme=uri.getScheme();

String data=null;

if(scheme==null)

data=uri.getPath();

else if(ContentResolver.SCHEME_FILE.equals(scheme)){

data=uri.getPath();

}else if(ContentResolver.SCHEME_CONTENT.equals(scheme)){

Cursorcursor=context.getContentResolver().query(uri,newString[]{ImageColumns.DATA},null,null,null);

if(null!=cursor){

if(cursor.moveToFirst()){

int index=cursor.getColumnIndex(ImageColumns.DATA);

if(index>-1){

data=cursor.getString(index);

cursor.close();

return data;

5.android 恢复短信代码

ContentValues values=new ContentValues();

values.put("address","123456789");

values.put("body","haha");

values.put("date","135123000000");

getContentResolver().insert(Uri.parse("content://sms/sent"),values);

6.android 横竖屏切换代码

<activity android:name="MyActivity"

android:configChanges="orientation|keyboardHidden">

public void onConfigurationChanged(ConfigurationnewConfig){

super.onConfigurationChanged(newConfig);

if(this.getResources().getConfiguration().orientation==Configuration.ORIENTATION_LANDSCAPE){

//加入横屏要处理的代码

}else if(this.getResources().getConfiguration().orientation==Configuration.ORIENTATION_PORTRAIT){

//加入竖屏要处理的代码

7.android 获得mac地址

1、<uses-permissionandroid:name="android.permission.ACCESS_WIFI_STATE"/>

2、private String getLocalMacAddress(){

WifiManager wifi=(WifiManager)getSystemService(Context.WIFI_SERVICE);

WifiInfo info=wifi.getConnectionInfo();

return info.getMacAddress();

8.android 获得sd卡状态

File sdcardDir=Environment.getExternalStorageDirectory();

StatFs statFs=new StatFs(sdcardDir.getPath());

/**Block的size*/

Long blockSize=statFs.getBlockSize();

/**总Block数量*/

Long totalBlocks=statFs.getBlockCount();

/**已使用的Block数量*/

Long availableBlocks=statFs.getAvailableBlocks();

9. Android获取状态栏与标题栏的高度

1.Android获取状态栏高度:

Rect frame=new Rect();

getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);

int statusBarHeight=frame.top;

2.获取标题栏高度:

int contentTop=getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();

//statusBarHeight是上面所求的状态栏的高度

int titleBarHeight=contentTop-statusBarHeight

获取状态栏高度

Rect frame=new Rect();

getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);

int statusBarHeight=frame.top;

获取标题栏高度

int contentTop=getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();

//statusBarHeight是上面所求的状态栏的高度

int titleBarHeight=contentTop-statusBarHeight

10.android 禁用home键盘

public boolean onKeyDown(int keyCode,KeyEvent event){

if(KeyEvent.KEYCODE_HOME==keyCode)

android.os.Process.killProcess(android.os.Process.myPid());

returnsuper.onKeyDown(keyCode,event);

public void onAttachedToWindow(){

//TODOAuto-generatedmethodstub

this.getWindow().setType(WindowManager.LayoutParams.TYPE_KEYGUARD);

super.onAttachedToWindow();

加权限禁止Home键

<uses-permissionandroid:name="android.permission.DISABLE_KEYGUARD"></uses-permission>

12.android 控制对话框位置

window=dialog.getWindow();//   得到对话框的窗口.

WindowManager.LayoutParamswl=window.getAttributes();

wl.x=x;//这两句设置了对话框的位置.0为中间

wl.y=y;

wl.width=w;

wl.height=h;

wl.alpha=0.6f;//这句设置了对话框的透明度

13.android 挪动dialog的位置

Window mWindow=dialog.getWindow();

WindowManager.LayoutParamslp=mWindow.getAttributes();

lp.x=10;//新位置X坐标

lp.y=-100;//新位置Y坐标

dialog.onWindowAttributesChanged(lp);

14.android 判断网络状态

<uses-permission

android:name="android.permission.ACCESS_NETWORK_STATE"/>

private boolean getNetWorkStatus(){

boolean netSataus=false;

ConnectivityManager cwjManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_SERVICE);

cwjManager.getActiveNetworkInfo();

if(cwjManager.getActiveNetworkInfo()!=null){

netSataus=cwjManager.getActiveNetworkInfo().isAvailable();

if(!netSataus){

Builder b=new AlertDialog.Builder(this).setTitle("没有可用的网络")

.setMessage("是否对网络进行设置?");

b.setPositiveButton("是",newDialogInterface.OnClickListener(){

public void onClick(DialogInterfacedialog,intwhichButton){

Intent mIntent=new Intent("/");

ComponentName comp=new ComponentName(

"com.android.settings",

"com.android.settings.WirelessSettings");

mIntent.setComponent(comp);

mIntent.setAction("android.intent.action.VIEW");

startActivityForResult(mIntent,0);

}).setNeutralButton("否",newDialogInterface.OnClickListener(){

public void onClick(DialogInterface dialog,int whichButton){

dialog.cancel();

}).show();

return netSataus;

15. android 设置apn

ContentValues values=new ContentValues();

values.put(NAME,"CMCCcmwap");

values.put(APN,"cmwap");

values.put(PROXY,"10.0.0.172");

values.put(PORT,"80");

values.put(MMSPROXY,"");

values.put(MMSPORT,"");

values.put(USER,"");

values.put(SERVER,"");

values.put(PASSWORD,"");

values.put(MMSC,"");

values.put(TYPE,"");

values.put(MCC,"460");

values.put(MNC,"00");

values.put(NUMERIC,"46000");

reURI=getContentResolver().insert(Uri.parse("content://telephony/carriers"),values);

//首选接入点"content://telephony/carriers/preferapn"

16.android 调节屏幕亮度

public void setBrightness(intlevel){

ContentResolver cr=getContentResolver();

Settings.System.putInt(cr,"screen_brightness",level);

Windowwindow=getWindow();

LayoutParams attributes=window.getAttributes();

float flevel=level;

attributes.screenBrightness=flevel/255;

getWindow().setAttributes(attributes);

17.android 重启

第一,root权限,这是必须的

第二,Runtime.getRuntime().exec("su-creboot");

第三,模拟器上运行不出来,必须真机

第四,运行时会提示你是否加入列表,同意就好

18.android隐藏软键盘

setContentView(R.layout.activity_main);

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE|

WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

19.android隐藏以及显示软键盘以及不自动弹出键盘的方法

1、//隐藏软键盘

((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(WidgetSearchActivity.this.getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS);

2、//显示软键盘,控件ID可以是EditText,TextView

((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE)).showSoftInput(控件ID,0);

22.BitMap、Drawable、inputStream及byte[] 互转

(1)BitMaptoinputStream:

ByteArrayOutputStreambaos=newByteArrayOutputStream();

bm.compress(Bitmap.CompressFormat.PNG,100,baos);

InputStreamisBm=newByteArrayInputStream(baos.toByteArray());

(2)BitMaptobyte[]:

BitmapdefaultIcon=BitmapFactory.decodeStream(in);

ByteArrayOutputStreamstream=newByteArrayOutputStream();

defaultIcon.compress(Bitmap.CompressFormat.JPEG,100,stream);

byte[]bitmapdata=stream.toByteArray();

(3)Drawabletobyte[]:

Drawabled;//thedrawable(CaptainObvious,totherescue!!!)

Bitmapbitmap=((BitmapDrawable)d).getBitmap();

ByteArrayOutputStreamstream=newByteArrayOutputStream();

defaultIcon.compress(Bitmap.CompressFormat.JPEG,100,bitmap);

byte[]bitmapdata=stream.toByteArray();

(4)byte[]toBitmap:

Bitmapbitmap=BitmapFactory.decodeByteArray(byte[],0,byte[].length);

23.发送指令

out=process.getOutputStream();

out.write(("amstart-aandroid.intent.action.VIEW-ncom.android.browser/com.android.browser.BrowserActivityn").getBytes());

out.flush();

InputStream in=process.getInputStream();

BufferedReader re=new BufferedReader(new InputStreamReader(in));

String line=null;

while((line=re.readLine())!=null){

Log.d("conio","[result]"+line);

评论列表暂无评论
发表评论
微信