Android 常用代码片小结

简介: 1. dp px 相互转换---------------public class DensityUtil { /** * 根据手机的分辨率从 dip 的单位 转成为 px(像素) */ public static int dip...
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("3")); 
        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("3")); 
        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 > -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"/>    
2private 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\images\
5、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);
}

  

目录
相关文章
|
Android开发
Android——常用代码段积累(一)
     1,Toast              // 登录成功之后跳转到home Toast.makeText(getApplicationContext(), "登陆成功!", Toast.
813 0
|
5天前
|
Linux 编译器 Android开发
FFmpeg开发笔记(九)Linux交叉编译Android的x265库
在Linux环境下,本文指导如何交叉编译x265的so库以适应Android。首先,需安装cmake和下载android-ndk-r21e。接着,下载x265源码,修改crosscompile.cmake的编译器设置。配置x265源码,使用指定的NDK路径,并在配置界面修改相关选项。随后,修改编译规则,编译并安装x265,调整pc描述文件并更新PKG_CONFIG_PATH。最后,修改FFmpeg配置脚本启用x265支持,编译安装FFmpeg,将生成的so文件导入Android工程,调整gradle配置以确保顺利运行。
24 1
FFmpeg开发笔记(九)Linux交叉编译Android的x265库
|
28天前
|
Java Android开发
Android 开发获取通知栏权限时会出现两个应用图标
Android 开发获取通知栏权限时会出现两个应用图标
14 0
|
1月前
|
XML 缓存 Android开发
Android开发,使用kotlin学习多媒体功能(详细)
Android开发,使用kotlin学习多媒体功能(详细)
103 0
|
1月前
|
设计模式 人工智能 开发工具
安卓应用开发:构建未来移动体验
【2月更文挑战第17天】 随着智能手机的普及和移动互联网技术的不断进步,安卓应用开发已成为一个热门领域。本文将深入探讨安卓平台的应用开发流程、关键技术以及未来发展趋势。通过分析安卓系统的架构、开发工具和框架,本文旨在为开发者提供全面的技术指导,帮助他们构建高效、创新的移动应用,以满足不断变化的市场需求。
18 1
|
2天前
|
数据库 Android开发 开发者
安卓应用开发:构建高效用户界面的策略
【4月更文挑战第24天】 在竞争激烈的移动应用市场中,一个流畅且响应迅速的用户界面(UI)是吸引和保留用户的关键。针对安卓平台,开发者面临着多样化的设备和系统版本,这增加了构建高效UI的复杂性。本文将深入分析安卓平台上构建高效用户界面的最佳实践,包括布局优化、资源管理和绘制性能的考量,旨在为开发者提供实用的技术指南,帮助他们创建更流畅的用户体验。
|
19天前
|
XML 开发工具 Android开发
构建高效的安卓应用:使用Jetpack Compose优化UI开发
【4月更文挑战第7天】 随着Android开发不断进化,开发者面临着提高应用性能与简化UI构建流程的双重挑战。本文将探讨如何使用Jetpack Compose这一现代UI工具包来优化安卓应用的开发流程,并提升用户界面的流畅性与一致性。通过介绍Jetpack Compose的核心概念、与传统方法的区别以及实际集成步骤,我们旨在提供一种高效且可靠的解决方案,以帮助开发者构建响应迅速且用户体验优良的安卓应用。
|
21天前
|
监控 算法 Android开发
安卓应用开发:打造高效启动流程
【4月更文挑战第5天】 在移动应用的世界中,用户的第一印象至关重要。特别是对于安卓应用而言,启动时间是用户体验的关键指标之一。本文将深入探讨如何优化安卓应用的启动流程,从而减少启动时间,提升用户满意度。我们将从分析应用启动流程的各个阶段入手,提出一系列实用的技术策略,包括代码层面的优化、资源加载的管理以及异步初始化等,帮助开发者构建快速响应的安卓应用。