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);
}
}
private void turnGPSOn(){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); if(!provider.contains("gps")){ //if gps is disabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse(""));
sendBroadcast(poke);
}
} private void turnGPSOff(){
String provider = Settings.Secure.getString(getContentResolver(), Settings.Secure.LOCATION_PROVIDERS_ALLOWED); if(provider.contains("gps")){ //if gps is enabled
final Intent poke = new Intent();
poke.setClassName("com.android.settings", "com.android.settings.widget.SettingsAppWidgetProvider");
poke.addCategory(Intent.CATEGORY_ALTERNATIVE);
poke.setData(Uri.parse(""));
sendBroadcast(poke);
}
}
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 > - ) {
data = cursor.getString( index );
}
}
cursor.close();
}
}
return data;
}

Android 还原短信
ContentValues values = new ContentValues(); values.put("address", ""); values.put("body", "haha"); values.put("date", ""); 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地址

、<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
、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获取状态栏和标题栏的高度

.Android获取状态栏高度:

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

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

Rect frame = new Rect();
getWindow().getDecorView().getWindowVisibleDisplayFrame(frame);
int statusBarHeight = frame.top; .获取标题栏高度: 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);
} }
)<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\images\
5、OK,模拟器正常运行

  

挪动dialog的位置

Window mWindow = dialog.getWindow();
WindowManager.LayoutParams lp = mWindow.getAttributes();
lp.x = ; //新位置X坐标
lp.y = -; //新位置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,);
}
}).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 / ;
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);
}

  

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

  1. Android 常用代码大集合 [转]

    [Android]调用字符串资源的几种方法   字符串资源的定义 文件路径:res/values/strings.xml 字符串资源定义示例: <?xml version="1.0&q ...

  2. Android常用代码集合

    这篇文章主要记录一些常用的一些代码段,方便以后查阅,不断更新中. 1:调用浏览器,载入某网址 1 2 3 Uri uri = Uri.parse("http://www.android-st ...

  3. Android常用代码

    1.图片旋转 Bitmap bitmapOrg = BitmapFactory.decodeResource(this.getContext().getResources(), R.drawable. ...

  4. Android 常用代码

    1.单元测试 然而可以直接建立单元测试 <uses-library android:name="android.test.runner"/> 放在application ...

  5. 转--Android实用的代码片段 常用代码总结

    这篇文章主要介绍了Android实用的代码片段 常用代码总结,需要的朋友可以参考下     1:查看是否有存储卡插入 复制代码 代码如下: String status=Environment.getE ...

  6. 36个Android开发常用代码片段

    //36个Android开发常用代码片段 //拨打电话 public static void call(Context context, String phoneNumber) { context.s ...

  7. 【风马一族_Android】第4章Android常用基本控件

    第4章Android常用基本控件 控件是Android用户界面中的一个个组成元素,在介绍它们之前,读者必须了解所有控件的父类View(视图),它好比一个盛放控件的容器. 4.1View类概述 对于一个 ...

  8. Android 常用开发工具以及Mac常用软件

    Android 常用的开发工具记录.其中包括AndroidStudio(IDEA)插件.Mac 上好用的软件以及国内知名Android开发者博客等. Android Studio 插件 codota ...

  9. android 常用URI

    关于联系人的一些URI: 管理联系人的Uri: ContactsContract.Contacts.CONTENT_URI 管理联系人的电话的Uri: ContactsContract.CommonD ...

随机推荐

  1. 实现winfrom进度条及进度信息提示,winfrom程序假死处理

    1.方法一:使用线程 功能描述:在用c#做WinFrom开发的过程中.我们经常需要用到进度条(ProgressBar)用于显示进度信息.这时候我们可能就需要用到多线程,如果不采用多线程控制进度条,窗口 ...

  2. Time Out 访问数据库超时处理 .NET

    using System.Reflection; using System.Data.SqlClient; TransactionSelectTableAdapter adapter = new Tr ...

  3. 浅谈:配置本地yum源(centos)

    删除YUM的所有配置信息[root@server yum.repos.d]#rm -rf * 现在手动配置:1.在根目录下创建文件夹centos-yum: [root@server /]#mkdir ...

  4. 使用 Oracle Sql plus的一点经验

    1    当你输入的语句有错误的时候,不用重新输入语句,直接输入ed就会出现一个文本文档显示之前输入的语句,这样你可以在文本文档里面修改语句,最后点保存. 2 三个set:设置每行显示的记录长度:SE ...

  5. 使用 Struts 2 实现国际化

    struts2国际化(I18N) 国际化也叫I18N,是Internationalization的简称.Struts2国际化是建立在Java国际化基础上,只是Struts2框架对Java国际化进行了进 ...

  6. 由chkconfig 引发的联想——怎么查看程序是否已经安装/成功安装

    由chkconfig 引发的联想--怎么查看程序是否已经安装/成功安装 某天需要运行chkconfig,root登录依然找不到该命令. [root@localhost ~]# chkconfig ba ...

  7. dependency injection via inversion of control

    依赖注入DI是一个程序设计模式和架构模型, 一些时候也称作控制反转,尽管在技术上来讲, 依赖注入是一个IOC的特殊实现, 依赖注入是指一个对象应用另外一个对象来提供一个特殊的能力, 例如:把一个数据库 ...

  8. jquery中的on事件

    on()函数用于为指定元素的一个或多个事件绑定事件处理函数. 从jQuery 1.7开始,on()函数提供了绑定事件处理程序所需的所有功能,用于统一取代以前的bind(). delegate(). l ...

  9. php 生成唯一的订单

    /** * 生成唯一的订单号 20110809111259232312 * 2011-年日期 * 08-月份 * 09-日期 * 11-小时 * 12-分 * 59-秒 * 2323-微秒 * 12- ...

  10. ip,子网掩码,网关,DNS

    要配置一个局域网通信的计算机(也就是同一个网络): IP地址 子网掩码 要配置一个跨网段通信的计算机: IP地址 子网掩码 网关(路由使用) 要配置一个可上网的计算机: IP地址 子网掩码 网关 DN ...