Android 常用代码片小结

1. dp  px  相互转换---------------public class DensityUtil {  

    /**
     * 根据手机的分辨率从 dip 的单位 转成为 px(像素)
     */
    public static int dip2px(Context context, float dpValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }  

    /**
     * 根据手机的分辨率从 px(像素) 的单位 转成为 dp
     */
    public static int px2dip(Context context, float pxValue) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (int) (pxValue / scale + 0.5f);
    }
}  
root 下禁用组件

pm disable com.htc.htclocationservice/com.htc.htclocationservice.AutoSettingReceiver
根据url获取真实路径

    public static String getRealFilePath( final Context context, final Uri uri ) {

        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 ) ) {
            Cursor cursor = context.getContentResolver().query( uri, new String[] { 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;
    }
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);
横竖屏切换

< activity android:name="MyActivity"
android:configChanges="orientation|keyboardHidden"> 

public void onConfigurationChanged(Configuration newConfig) {  

   super.onConfigurationChanged(newConfig);  

if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
           //加入横屏要处理的代码  

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

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

}  

}  
获取mac地址

1、<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
2、private String getLocalMacAddress() {
    WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
    WifiInfo info = wifi.getConnectionInfo();
    return info.getMacAddress();
  }  
获取sd卡状态

/** 获取存储卡路径 */
File sdcardDir=Environment.getExternalStorageDirectory();
/** StatFs 看文件系统空间使用情况 */
StatFs statFs=new StatFs(sdcardDir.getPath());
/** Block 的 size*/
Long blockSize=statFs.getBlockSize();
/** 总 Block 数量 */
Long totalBlocks=statFs.getBlockCount();
/** 已使用的 Block 数量 */
Long availableBlocks=statFs.getAvailableBlocks(); 
Android获取状态栏和标题栏的高度

1.Android获取状态栏高度:

decorView是window中的最顶层view,可以从window中获取到decorView,然后decorView有个getWindowVisibleDisplayFrame方法可以获取到程序显示的区域,包括标题栏,但不包括状态栏。

于是,我们就可以算出状态栏的高度了。

Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;

2.获取标题栏高度:

getWindow().findViewById(Window.ID_ANDROID_CONTENT)这个方法获取到的view就是程序不包括标题栏的部分,然后就可以知道标题栏的高度了。

int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
//statusBarHeight是上面所求的状态栏的高度
int titleBarHeight = contentTop - statusBarHeight

例子代码:

package com.cn.lhq;
import android.app.Activity;
import android.graphics.Rect;
import android.os.Bundle;
import android.util.Log;
import android.view.Window;
import android.widget.ImageView;
public class Main extends Activity {
 ImageView iv;
 @Override
 public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  setContentView(R.layout.main);
  iv = (ImageView) this.findViewById(R.id.ImageView01);
  iv.post(new Runnable() {
   public void run() {
    viewInited();
   }
  });
  Log.v("test", "== ok ==");
 }
 private void viewInited() {
  Rect rect = new Rect();
  Window window = getWindow();
  iv.getWindowVisibleDisplayFrame(rect);
  int statusBarHeight = rect.top;
  int contentViewTop = window.findViewById(Window.ID_ANDROID_CONTENT)
    .getTop();
  int titleBarHeight = contentViewTop - statusBarHeight;
  // 测试结果:ok之后 100多 ms 才运行了
  Log.v("test", "=-init-= statusBarHeight=" + statusBarHeight
    + " contentViewTop=" + contentViewTop + " titleBarHeight="
    + titleBarHeight);
 }
}

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
 <ImageView
  android:id="@+id/ImageView01"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"/>
</LinearLayout>
  //取得窗口属性
        getWindowManager().getDefaultDisplay().getMetrics(dm);

        //窗口的宽度
        int screenWidth = dm.widthPixels;
        //窗口高度
        int screenHeight = dm.heightPixels;
        textView = (TextView)findViewById(R.id.textView01);
        textView.setText("屏幕宽度: " + screenWidth + "\n屏幕高度: " + screenHeight);

二、获取状态栏高度
decorView是window中的最顶层view,可以从window中获取到decorView,然后decorView有个getWindowVisibleDisplayFrame方法可以获取到程序显示的区域,包括标题栏,但不包括状态栏。
于是,我们就可以算出状态栏的高度了。
view plain

Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top;

三、获取标题栏高度
getWindow().findViewById(Window.ID_ANDROID_CONTENT)这个方法获取到的view就是程序不包括标题栏的部分,然后就可以知道标题栏的高度了。
view plain

int contentTop = getWindow().findViewById(Window.ID_ANDROID_CONTENT).getTop();
//statusBarHeight是上面所求的状态栏的高度
int titleBarHeight = contentTop - statusBarHeight
        问题的提出
         Android Home键系统负责监听,捕获后系统自动处理。有时候,系统的处理往往不随我们意,想自己处理点击Home后的事件,那怎么办?

        问题的解决
         先禁止Home键,再在onKeyDown里处理按键值,点击Home键的时候就把程序关闭,或者随你XXOO。

@Override

 public boolean onKeyDown(int keyCode, KeyEvent event)

{ // TODO Auto-generated method stub

  if(KeyEvent.KEYCODE_HOME==keyCode)

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

     return super.onKeyDown(keyCode, event);

  }

@Override

 public void onAttachedToWindow()

 { // TODO Auto-generated method stub

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

    super.onAttachedToWindow();

 }

加权限禁止Home键

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

  

public class StartupReceiver extends BroadcastReceiver {  

  @Override
  public void onReceive(Context context, Intent intent) {
    Intent startupintent = new Intent(context,StrongTracks.class);
    startupintent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    context.startActivity(startupintent);
  }  

}
2)<receiver
android:name=".StartupReceiver">
<intent-filter>
    <!-- 系统启动完成后会调用 -->
    <action
        android:name="android.intent.action.BOOT_COMPLETED">
    </action>
</intent-filter>
</receiver> 
 window =dialog.getWindow();//    得到对话框的窗口.
      WindowManager.LayoutParams wl = window.getAttributes();
       wl.x = x;//这两句设置了对话框的位置.0为中间
       wl.y =y;
       wl.width =w;
       wl.height =h;
       wl.alpha =0.6f;// 这句设置了对话框的透明度   
1、找到android模拟器安装目录:C:\Documents and Settings\Administrator\.android\avd\AVD23.avd
2、编辑config.ini文件,就是这块配置错误导致错误产生。
3、如果硬盘空间比较紧张,可以把模拟器文件放到其它盘符上:你可以在命令行下用mkcard创建一个SDCARD文件,如: mksdcard 50M D:\sdcard.img
4、下面代码可以整个覆盖原来的config文件 hw.sdCard=yes hw.lcd.density=240 skin.path=800×480 skin.name=800×480 vm.heapSize=24 sdcard.path=D:\sdcard.img hw.ramSize=512 image.sysdir.1=platforms\android-8\images5、OK,模拟器正常运行

  

挪动dialog的位置

Window mWindow = dialog.getWindow();
WindowManager.LayoutParams lp = mWindow.getAttributes();
lp.x = 10;   //新位置X坐标
lp.y = -100; //新位置Y坐标
dialog.onWindowAttributesChanged(lp);
判断网络状态

<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("是", new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int whichButton) {
   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("否", new DialogInterface.OnClickListener() {
   public void onClick(DialogInterface dialog, int whichButton) {
   dialog.cancel();
   }
   }).show();
   }  

   return netSataus;
   }  
设置 apn

ContentValues values = new ContentValues();
values.put(NAME, "CMCC cmwap");
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"

  

调节屏幕的亮度
、
、
public void setBrightness(int level) {
ContentResolver cr = getContentResolver();
Settings.System.putInt(cr, "screen_brightness", level);
Window window = getWindow();
LayoutParams attributes = window.getAttributes();
float flevel = level;
attributes.screenBrightness = flevel / 255;
getWindow().setAttributes(attributes);
} 
第一,root权限,这是必须的
第二,Runtime.getRuntime().exec("su -c reboot");
第三,模拟器上运行不出来,必须真机
第四,运行时会提示你是否加入列表 , 同意就好
隐藏软键盘

setContentView(R.layout.activity_main);
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_RESIZE |
                WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
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);

  

Bitmap 工具类

(1) BitMap  to   inputStream:
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
    InputStream isBm = new ByteArrayInputStream(baos .toByteArray());

 (2)BitMap  to   byte[]:
  Bitmap defaultIcon = BitmapFactory.decodeStream(in);
  ByteArrayOutputStream stream = new ByteArrayOutputStream();
  defaultIcon.compress(Bitmap.CompressFormat.JPEG, 100, stream);
  byte[] bitmapdata = stream.toByteArray();
 (3)Drawable  to   byte[]:
  Drawable d; // the drawable (Captain Obvious, to the rescue!!!)
  Bitmap bitmap = ((BitmapDrawable)d).getBitmap();
  ByteArrayOutputStream stream = new ByteArrayOutputStream();
  defaultIcon.compress(Bitmap.CompressFormat.JPEG, 100, bitmap);
  byte[] bitmapdata = stream.toByteArray();

(4)byte[]  to  Bitmap :
  Bitmap bitmap =BitmapFactory.decodeByteArray(byte[], 0,byte[].length);

  

发送指令:

out = process.getOutputStream();
out.write(("am start -a android.intent.action.VIEW -n com.android.browser/com.android.browser.BrowserActivity\n").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);
}

  

时间: 2024-08-01 19:15:00

Android 常用代码片小结的相关文章

Android常用代码

1.图片旋转 Bitmap bitmapOrg = BitmapFactory.decodeResource(this.getContext().getResources(), R.drawable.moon); Matrix matrix = new Matrix(); matrix.postRotate(-90);//旋转的角度 Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0, bitmapOrg.getWidth(),

android 实用代码片段整理

android 常用代码片段,前1-10条是从网上摘录,向原作者致谢.后面为自己整理. 1.设置窗口格式为半透明 getWindow().setFormat(PixelFormat.TRANSLUCENT); 2.Android中在非UI线程里更新View的不同方法: * Activity.runOnUiThread( Runnable ) * View.post( Runnable ) * View.postDelayed( Runnable, long ) * Hanlder 3.全屏显示窗

Android常用功能代码块

1.设置activity无标题,全屏 // 设置为无标题栏 requestWindowFeature(Window.FEATURE_NO_TITLE); // 设置为全屏模式 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN); 2.获得屏幕高度和宽度 //获取屏幕的高度和宽度用到WindowManager这个类 WindowMan

Android 常用的URI

一.关于联系人的一些URI: 管理联系人的Uri: ContactsContract.Contacts.CONTENT_URI 管理联系人的电话的Uri: ContactsContract.CommonDataKinds.Phone.CONTENT_URI 管理联系人的Email的Uri: ContactsContract.CommonDataKinds.Email.CONTENT_URI (注:Contacts有两个表,分别是rawContact和Data, rawContact记录了用户的i

【Android 应用开发】 Android 相关代码规范 更新中 ...

. 简介 : Android 常用的代码结构, 包括包的规范, 测试用例规范, 数据库模块常用编写规范; 参考 : 之前写的一篇博客 [Android 应用开发] Application 使用分析 ; -- Application 分析 : Application 概念, 声明周期, 组件间传递数据作用, 数据缓存作用; -- 源码分析 : 分析 Application 结构接口源码; -- 使用示例 : 自定义 Application 注册, 保存崩溃日志到文件, 监听Activity声明周期

[Android阅读代码]android-async-http源码学习一

android-async-http 下载地址 一个比较常用的Http请求库,基于org.apache.http对http操作进行封装. 特点: 1.每一个HTTP请求发生在UI线程之外,Client通过回调处理HTTP请求的结果,使得Client代码逻辑清晰 2.每一个请求使用线程池管理执行 3.支持gzip , cookie等功能 4.支持自动重试连接功能 [Android阅读代码]android-async-http源码学习一,布布扣,bubuko.com

【转】 Android常用实例—Alert Dialog的使用

Android常用实例-Alert Dialog的使用 AlertDialog的使用很普遍,在应用中当你想要用户做出"是"或"否"或者其它各式各样的选择时,为了保持在同样的Activity和不改变用户屏幕,就可以使用AlertDialog. 代码地址 https://github.com/JueYingCoder/AndroidUsefulExample_AlertDialog 这篇文章主要讲解如何实现各种AlertDialog,文章比较长,如果能认真读完,Aler

Android常用开源项目

Android常用开源项目 Android   2014-05-23 16:39:43 发布 您的评价:       4.3   收藏     24收藏 Android开源项目第一篇--个性化控件(View)篇  包括ListView.ActionBar.Menu.ViewPager.Gallery.GridView.ImageView.ProgressBar.TextView.其他Android开源项目第二篇--工具库篇  包括依赖注入.图片缓存.网络相关.数据库ORM工具包.Android公

Android常用的工具类

主要介绍总结的Android开发中常用的工具类,大部分同样适用于Java.目前包括HttpUtils.DownloadManagerPro.ShellUtils.PackageUtils.PreferencesUtils.JSONUtils.FileUtils.ResourceUtils.StringUtils.ParcelUtils.RandomUtils.ArrayUtils.ImageUtils.ListUtils.MapUtils.ObjectUtils.SerializeUtils.S