android开发常用问题总结

 

android 学习笔记一 全屏显示以及获取屏幕大小

//不显示标题
requestWindowFeature(Window.FEATURE_NO_TITLE);

//设置窗口全屏显示
getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,WindowManager.LayoutParams.FLAG_FULLSCREEN);

 

判断国家

String locale = context.getResources().getConfiguration().locale.getCountry();  

String locale = context.getResources().getConfiguration().locale.getDisplayCountry(); 

TelephonyManager tm = (TelephonyManager)getSystemService(Context.TELEPHONY_SERVICE); 
String countryCode = tm.getSimCountryIso(); 

 

关闭输入法

InputMethodManager inputMethodManager = (InputMethodManager)getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(etEditText.getWindowToken(), 0);

 

设置输入格式过滤器

EditText::setInputType(InputType.TYPE_NULL); // 表示不显示输入法

 

//取得屏幕信息
DisplayMetrics dm = new DisplayMetrics();
dm = this.getResources().getDisplayMetrics();
//获得屏幕宽度
int screenWidth = dm.widthPixels;
//获得屏幕高度
int screenHeight = dm.heightPixels;

 

获取状态栏高度:

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;

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

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

int titleBarHeight = contentTop - statusBarHeight;

 

屏幕方向更改

屏幕方向是横排(PORTRAIT)刚将屏幕方向更改为竖排(LANDSCAPE), 运用了getRequestedOrientation(),和setRequestedorientation()两个方法. 但是要利用这两个方法必须先在AndroidManiefst.xml设置一下屏幕方属性,不然程序将不能正常的工作.

//如果是竖排,则改为横排

if(getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {

  setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

}

 

//如果是横排,则改为竖排

else if(getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_PORTRAIT) {

  setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);

}

 

在AndroidManifest.xml文件里设置默认方向

< activity android:name=".XXXActivity"

  android:label="@string/app_name"

  android:screenOrientation="portrait" >

 

 

android 特殊符号的显示
在android values 的String中,如果想让特殊符号正常的显示,需要转义,通常一般字符都可以用 / 来转义例如 ' /'  "  /"
现在简单说说最常用的几个字符的其他转义
单引号 '   &apos;
双引号 "   &quot;
       >   &gt;
       <   &lt;
       &   &amp; 

 

Context Menu和Options Menu菜单的区别

1.  Context Menu – 显示一个Activity中特定View的信息。在Android中,通过按下并Hold一段时间来激活上下文菜单。   

2.  Options Menu – 显示当前Activity的信息。在Android中,通过按下MENU键来激活选项菜单。   

3.  Options Menu需要重写两个方法——onCreateOptionsMenu()和onOptionsItemSelected()。onCreateOptionsMenu()方法在MENU按钮被按下时调用。当一个菜单项被选中时,onOptionsItemSelected()方法会被调用。Context Menu需要重写onCreateContextMenu()和onContextItemSelected()方法。在创建ContextMenu是调用onCreateContextMenu(),当选项被选中时调用onContextItemSelected()。

 

Android平台显示单位px和dip以及sp的区别

px (pixels)像素 -- 屏幕上的点, 一般我们HVGA代表320x480像素,这个用的比较多

dip或dp (device independent pixels)设备独立像素 -- 这个和设备硬件有关(与密度无关的像素),一般我们为了支持WVGA、HVGA和QVGA cwj推荐使用这个,不依赖像素, 一种基于屏幕密度的抽象单位。在每英寸160点的显示器上,1dp = 1px。 在大于160点的显示器上可能增大

sp (scaled pixels — best for text size)放大像素-- 主要处理字体的大小, (与刻度无关的像素), 与dp类似,但是可以根据用户的字体大小首选项进行缩放

下面的几个是不常用的:

in(英寸):长度单位。

mm(毫米):长度单位

pt(磅):1/72英寸

 

 

如何通过handler来更新线程

最常见的例子就是我们在更新UI时,由于Android UI操作并不是线程安全的并且这些操作必须在UI线程中执行。所以我们需要使用利用Handler来实现UI线程的更新的。(当然Handler的用处也不仅限于此)。下面是代码片段

  1. //处理消息   
  2. Handler myHandler = new Handler() {      
  3.     public void handleMessage(Message msg) {       
  4.          switch (msg.what) {       
  5.              case 100:       
  6.                    //更新线程   
  7.                    break;       
  8.           }       
  9.           super.handleMessage(msg);       
  10.      }       
  11. };   
  12. //发送消息   
  13. Message message = new Message();       
  14. message.what = 100;       
  15. myHandler.sendMessage(message);   

 

以下源自:http://blog.csdn.net/mingxunzh/archive/2009/10/29/4745634.aspx

显示网页

Uri uri = Uri.parse("http://google.com");       

Intent it = new Intent(Intent.ACTION_VIEW, uri);       

startActivity(it);     

 

显示地图
Uri uri = Uri.parse("geo:38.899533,-77.036476");       
Intent it = new Intent(Intent.ACTION_VIEW, uri);        
startActivity(it);        
//其他 geo URI 範例       
//geo:latitude,longitude       
//geo:latitude,longitude?z=zoom       
//geo:0,0?q=my+street+address       
//geo:0,0?q=business+near+city       
//google.streetview:cbll=lat,lng&cbp=1,yaw,,pitch,zoom&mz=mapZoom     

 

 

拨打电话

//叫出撥號程式       
Uri uri = Uri.parse("tel:0800000123");       
Intent it = new Intent(Intent.ACTION_DIAL, uri);       
startActivity(it);      
//直接打電話出去       
Uri uri = Uri.parse("tel:0800000123");       
Intent it = new Intent(Intent.ACTION_CALL, uri);       
startActivity(it);       
//用這個,要在 AndroidManifest.xml 中,加上       
//<uses-permission id="android.permission.CALL_PHONE" />

 

发送SMS/MMS
//需写号码SMS      
Intent it = new Intent(Intent.ACTION_VIEW);       
it.putExtra("sms_body", "The SMS text");        
it.setType("vnd.android-dir/mms-sms");       
startActivity(it);      
//发送SMS       
Uri uri = Uri.parse("smsto:0800000123");       
Intent it = new Intent(Intent.ACTION_SENDTO, uri);       
it.putExtra("sms_body", "The SMS text");       
startActivity(it);      
//发送MMS       
Uri uri = Uri.parse("content://media/external/images/media/23");       
Intent it = new Intent(Intent.ACTION_SEND);        
it.putExtra("sms_body", "some text");        
it.putExtra(Intent.EXTRA_STREAM, uri);       
it.setType("image/png");        
startActivity(it);    

 

发送EMAIL
Uri uri = Uri.parse("mailto:xxx@abc.com");       
Intent it = new Intent(Intent.ACTION_SENDTO, uri);       
startActivity(it);      
Intent it = new Intent(Intent.ACTION_SEND);       
it.putExtra(Intent.EXTRA_EMAIL, "me@abc.com");       
it.putExtra(Intent.EXTRA_TEXT, "The email body text");       
it.setType("text/plain");       
startActivity(Intent.createChooser(it, "Choose Email Client"));      
Intent it=new Intent(Intent.ACTION_SEND);         
String[] tos={"me@abc.com"};         
String[] ccs={"you@abc.com"};         
it.putExtra(Intent.EXTRA_EMAIL, tos);         
it.putExtra(Intent.EXTRA_CC, ccs);         
it.putExtra(Intent.EXTRA_TEXT, "The email body text");         
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");         
it.setType("message/rfc822");         
startActivity(Intent.createChooser(it, "Choose Email Client"));       
//传送附件       
Intent it = new Intent(Intent.ACTION_SEND);       
it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");       
it.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/mysong.mp3");       
sendIntent.setType("audio/mp3");       
startActivity(Intent.createChooser(it, "Choose Email Client"));    

 

播放多媒体 
Intent it = new Intent(Intent.ACTION_VIEW);       
Uri uri = Uri.parse("file:///sdcard/song.mp3");       
it.setDataAndType(uri, "audio/mp3");       
startActivity(it);      
Uri uri = Uri.withAppendedPath(MediaStore.Audio.Media.INTERNAL_CONTENT_URI, "1");       
Intent it = new Intent(Intent.ACTION_VIEW, uri);       
startActivity(it);  

 

Android Market
//寻找应用      
Uri uri = Uri.parse("market://search?q=pname:pkg_name");       
Intent it = new Intent(Intent.ACTION_VIEW, uri);       
startActivity(it);       
//where pkg_name is the full package path for an application      
//显示应用详细列表     
Uri uri = Uri.parse("market://details?id=app_id");       
Intent it = new Intent(Intent.ACTION_VIEW, uri);       
startActivity(it);       
//where app_id is the application ID, find the ID        
//by clicking on your application on Market home        
//page, and notice the ID from the address bar

 

卸载应用

Uri uri = Uri.fromParts("package", strPackageName, null);        

Intent it = new Intent(Intent.ACTION_DELETE, uri);        

startActivity(it);

 

安装应用 
Uri uri = Uri.parse("url_of_apk_file");       
Intent it = new Intent(Intent.ACTION_VIEW, uri);       
it.setData(uri);       
it.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);       
it.setClassName("com.android.packageinstaller",       
                "com.android.packageinstaller.PackageInstallerActivity");       
startActivity(it);        
//make sure the url_of_apk_file is readable for all users     

 

 

 

检测到现在在电源状态:

IntentFilter   mIntentFilter = new IntentFilter();

mIntentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);  
registerReceiver(mIntentReceiver, mIntentFilter);

 

 //声明消息处理过程  
   private BroadcastReceiver mIntentReceiver = new BroadcastReceiver() {  
       @Override  
       public void onReceive(Context context, Intent intent) {  
           String action = intent.getAction();  
           //要看看是不是我们要处理的消息  
           if (action.equals(Intent.ACTION_BATTERY_CHANGED)) {            
               //电池电量,数字  
               Log.d("Battery", "" + intent.getIntExtra("level", 0));                 
               //电池最大容量  
               Log.d("Battery", "" + intent.getIntExtra("scale", 0));                 
               //电池伏数  
               Log.d("Battery", "" + intent.getIntExtra("voltage", 0));                 
               //电池温度  
               Log.d("Battery", "" + intent.getIntExtra("temperature", 0));  
                 
               //电池状态,返回是一个数字  
               // BatteryManager.BATTERY_STATUS_CHARGING 表示是充电状态  
               // BatteryManager.BATTERY_STATUS_DISCHARGING 放电中  
               // BatteryManager.BATTERY_STATUS_NOT_CHARGING 未充电  
               // BatteryManager.BATTERY_STATUS_FULL 电池满  
               Log.d("Battery", "" + intent.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN));  
               
               //充电类型 BatteryManager.BATTERY_PLUGGED_AC 表示是充电器,不是这个值,表示是 USB  
               Log.d("Battery", "" + intent.getIntExtra("plugged", 0));  
               
               //电池健康情况,返回也是一个数字  
               //BatteryManager.BATTERY_HEALTH_GOOD 良好  
               //BatteryManager.BATTERY_HEALTH_OVERHEAT 过热  
               //BatteryManager.BATTERY_HEALTH_DEAD 没电  
               //BatteryManager.BATTERY_HEALTH_OVER_VOLTAGE 过电压  
               //BatteryManager.BATTERY_HEALTH_UNSPECIFIED_FAILURE 未知错误  
               Log.d("Battery", "" + intent.getIntExtra("health", BatteryManager.BATTERY_HEALTH_UNKNOWN));  
           }  
       }  
   };

 

 

USB充电插拔与USB Debugging connect提示

在 packages/apps/Settings/src/com/android/settings/DevelopmentSettings.java 找到关于 USB Debug Enable 的代码: 
Settings.Secure.putInt(getContentResolver(), Settings.Secure.ADB_ENABLED,  0 );  
别处将根据其值动态变化做出相应动作如状态栏消息提示。
void usbListener() {
        ContentResolver resolver = mContext.getContentResolver();
        resolver.registerContentObserver(Settings.Secure.getUriFor(
                    Settings.Secure.ADB_ENABLED), false, this);
        updateUsbStatus();
}

@Override
public void onChange(boolean selfChange) {
        updateUsbStatus();
}

public void updateUsbStatus() {
        ContentResolver resolver = mContext.getContentResolver();
        mAdbEnabled = Settings.Secure.getInt(resolver, Settings.Secure.ADB_ENABLED, 0) != 0;
}

 

通过HttpClient从指定server获取数据

DefaultHttpClient httpClient = new DefaultHttpClient();
HttpGet method = new HttpGet(“http://www.baidu.com/1.html”);
HttpResponse resp;
Reader reader = null;
try {
    // AllClientPNames.TIMEOUT
    HttpParams params = new BasicHttpParams();
    params.setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, 10000);
    httpClient.setParams(params);
    resp = httpClient.execute(method);
    int status = resp.getStatusLine().getStatusCode();
    if (status != HttpStatus.SC_OK) return false;

    // HttpStatus.SC_OK;
    return true;

} catch (ClientProtocolException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
} catch (IOException e) {
     // TODO Auto-generated catch block
     e.printStackTrace();
} finally {
     if (reader != null) try {
           reader.close();
     } catch (IOException e) {
           // TODO Auto-generated catch block
           e.printStackTrace();
     }
}

 

 

application/SLA    stl
application/STEP    step
application/STEP    stp
application/acad    dwg
application/andrew-inset    ez
application/clariscad    ccad
application/drafting    drw
application/dsptype    tsp
application/dxf    dxf
application/excel    xls
application/i-deas    unv
application/java-archive    jar
application/mac-binhex40    hqx
application/mac-compactpro    cpt
application/vnd.ms-powerpoint    pot
application/vnd.ms-powerpoint    pps
application/vnd.ms-powerpoint    ppt
application/vnd.ms-powerpoint    ppz
application/msword    doc
application/octet-stream    bin
application/octet-stream    class
application/octet-stream    dms
application/octet-stream    exe
application/octet-stream    lha
application/octet-stream    lzh
application/oda    oda
application/ogg    ogg
application/ogg    ogm
application/pdf    pdf
application/pgp    pgp
application/postscript    ai
application/postscript    eps
application/postscript    ps
application/pro_eng    prt
application/rtf    rtf
application/set    set
application/smil    smi
application/smil    smil
application/solids    sol
application/vda    vda
application/vnd.mif    mif
application/vnd.ms-excel    xlc
application/vnd.ms-excel    xll
application/vnd.ms-excel    xlm
application/vnd.ms-excel    xls
application/vnd.ms-excel    xlw
application/vnd.rim.cod    cod
application/x-arj-compressed    arj
application/x-bcpio    bcpio
application/x-cdlink    vcd
application/x-chess-pgn    pgn
application/x-cpio    cpio
application/x-csh    csh
application/x-debian-package    deb
application/x-director    dcr
application/x-director    dir
application/x-director    dxr
application/x-dvi    dvi
application/x-freelance    pre
application/x-futuresplash    spl
application/x-gtar    gtar
application/x-gunzip    gz
application/x-gzip    gz
application/x-hdf    hdf
application/x-ipix    ipx
application/x-ipscript    ips
application/x-javascript    js
application/x-koan    skd
application/x-koan    skm
application/x-koan    skp
application/x-koan    skt
application/x-latex    latex
application/x-lisp    lsp
application/x-lotusscreencam    scm
application/x-mif    mif
application/x-msdos-program    bat
application/x-msdos-program    com
application/x-msdos-program    exe
application/x-netcdf    cdf
application/x-netcdf    nc
application/x-perl    pl
application/x-perl    pm
application/x-rar-compressed    rar
application/x-sh    sh
application/x-shar    shar
application/x-shockwave-flash    swf
application/x-stuffit    sit
application/x-sv4cpio    sv4cpio
application/x-sv4crc    sv4crc
application/x-tar-gz    tar.gz
application/x-tar-gz    tgz
application/x-tar    tar
application/x-tcl    tcl
application/x-tex    tex
application/x-texinfo    texi
application/x-texinfo    texinfo
application/x-troff-man    man
application/x-troff-me    me
application/x-troff-ms    ms
application/x-troff    roff
application/x-troff    t
application/x-troff    tr
application/x-ustar    ustar
application/x-wais-source    src
application/x-zip-compressed    zip
application/zip    zip
audio/TSP-audio    tsi
audio/basic    au
audio/basic    snd
audio/midi    kar
audio/midi    mid
audio/midi    midi
audio/mpeg    mp2
audio/mpeg    mp3
audio/mpeg    mpga
audio/ulaw    au
audio/x-aiff    aif
audio/x-aiff    aifc
audio/x-aiff    aiff
audio/x-mpegurl    m3u
audio/x-ms-wax    wax
audio/x-ms-wma    wma
audio/x-pn-realaudio-plugin    rpm
audio/x-pn-realaudio    ram
audio/x-pn-realaudio    rm
audio/x-realaudio    ra
audio/x-wav    wav
chemical/x-pdb    pdb
chemical/x-pdb    xyz
image/cmu-raster    ras
image/gif    gif
image/ief    ief
image/jpeg    jpe
image/jpeg    jpeg
image/jpeg    jpg
image/png    png
image/tiff    tif tiff
image/tiff    tif
image/tiff    tiff
image/x-cmu-raster    ras
image/x-portable-anymap    pnm
image/x-portable-bitmap    pbm
image/x-portable-graymap    pgm
image/x-portable-pixmap    ppm
image/x-rgb    rgb
image/x-xbitmap    xbm
image/x-xpixmap    xpm
image/x-xwindowdump    xwd
model/iges    iges
model/iges    igs
model/mesh    mesh
model/mesh    msh
model/mesh    silo
model/vrml    vrml
model/vrml    wrl
text/css    css
text/html    htm
text/html    html htm
text/html    html
text/plain    asc txt
text/plain    asc
text/plain    c
text/plain    cc
text/plain    f90
text/plain    f
text/plain    h
text/plain    hh
text/plain    m
text/plain    txt
text/richtext    rtx
text/rtf    rtf
text/sgml    sgm
text/sgml    sgml
text/tab-separated-values    tsv
text/vnd.sun.j2me.app-descriptor    jad
text/x-setext    etx
text/xml    xml
video/dl    dl
video/fli    fli
video/flv    flv
video/gl    gl
video/mpeg    mp2
video/mp4    mp4
video/mpeg    mpe
video/mpeg    mpeg
video/mpeg    mpg
video/quicktime    mov
video/quicktime    qt
video/vnd.vivo    viv
video/vnd.vivo    vivo
video/x-fli    fli
video/x-ms-asf    asf
video/x-ms-asx    asx
video/x-ms-wmv    wmv
video/x-ms-wmx    wmx
video/x-ms-wvx    wvx
video/x-msvideo    avi
video/x-sgi-movie    movie
www/mime    mime
x-conference/x-cooltalk    ice
x-world/x-vrml    vrm
x-world/x-vrml    vrml

 

 

public String getUserAgent() {
        String user_agent = ProductProperties.get(ProductProperties.USER_AGENT_KEY, null);
        return user_agent;
}

 

清空手机上Cookie

CookieSyncManager.createInstance(getApplicationContext());
        CookieManager.getInstance().removeAllCookie();

 

 

建立GPRS连接

//Dial the GPRS link.
private boolean openDataConnection() {
      // Set up data connection.
      DataConnection conn = DataConnection.getInstance();       
      if (connectMode == 0) {
            ret = conn.openConnection(mContext, "cmwap", "cmwap", "cmwap");
      } else {
            ret = conn.openConnection(mContext, "cmnet", "", "");
      }

}

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值