Android很有用的代码片段

1:查看是否有存储卡插入
[java]  view plain copy
  1. String status=Environment.getExternalStorageState();  
  2. if(status.equals(Enviroment.MEDIA_MOUNTED))  
  3. {  
  4.    说明有SD卡插入  
  5. }  
2:让某个Activity透明

OnCreate中不设Layout this.setTheme(R.style.Theme_Transparent);
以下是Theme_Transparent的定义(注意transparent_bg是一副透明的图片)


3:在屏幕元素中设置句柄

使用Activity.findViewById来取得屏幕上的元素的句柄. 使用该句柄您可以设置或获取任何该对象外露的值.
[java]  view plain copy
  1. TextView msgTextView = (TextView)findViewById(R.id.msg);  
  2.    msgTextView.setText(R.string.push_me);   
4:发送短信

          
[java]  view plain copy
  1. String body=”this is mms demo”;  
  2.           Intent mmsintent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(”smsto”, number, null));  
  3.           mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY, body);  
  4.           mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE, true);  
  5.           mmsintent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT, true);  
  6.            startActivity(mmsintent);  




5:发送彩信

           
[java]  view plain copy
  1. StringBuilder sb = new StringBuilder();  
  2.             sb.append(”file://”);  
  3.             sb.append(fd.getAbsoluteFile());  
  4.             Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(”mmsto”, number, null));  
  5.             // Below extra datas are all optional.  
  6.             intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_SUBJECT, subject);  
  7.             intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY, body);  
  8.             intent.putExtra(Messaging.KEY_ACTION_SENDTO_CONTENT_URI, sb.toString());  
  9.             intent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE, composeMode);  
  10.             intent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT, exitOnSent);  
  11.             startActivity(intent)  


6:发送Mail

         
[java]  view plain copy
  1. mime = “img/jpg”;  
  2.             shareIntent.setDataAndType(Uri.fromFile(fd), mime);  
  3.             shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(fd));  
  4.             shareIntent.putExtra(Intent.EXTRA_SUBJECT, subject);  
  5.             shareIntent.putExtra(Intent.EXTRA_TEXT, body);  

7:注册一个BroadcastReceiver

[java]  view plain copy
  1. registerReceiver(mMasterResetReciever, new IntentFilter(”oms.action.MASTERRESET”));  
  2. private BroadcastReceiver mMasterResetReciever = new BroadcastReceiver() {  
  3.         public void onReceive(Context context, Intent intent){  
  4.             String action = intent.getAction();  
  5.             if(”oms.action.MASTERRESET”.equals(action)){  
  6.                 RecoverDefaultConfig();  
  7.             }  
  8.         }  
  9.     }  

8:定义ContentObserver,监听某个数据表


[java]  view plain copy
  1. private ContentObserver mDownloadsObserver = new DownloadsChangeObserver(Downloads.CONTENT_URI);  
  2. private class DownloadsChangeObserver extends ContentObserver {  
  3.         public DownloadsChangeObserver(Uri uri) {  
  4.             super(new Handler());  
  5.         }  
  6.         @Override  
  7.         public void onChange(boolean selfChange) {}    
  8.         }  


  
9:获得 手机UA

[java]  view plain copy
  1. public String getUserAgent()  
  2.     {  
  3.            String user_agent = ProductProperties.get(ProductProperties.USER_AGENT_KEY, null);  
  4.             return user_agent;  
  5.     }  


10:清空手机上Cookie

[java]  view plain copy
  1. CookieSyncManager.createInstance(getApplicationContext());  
  2.         CookieManager.getInstance().removeAllCookie();  
11:建立GPRS连接

[java]  view plain copy
  1. //Dial the GPRS link.  
  2.    private boolean openDataConnection() {  
  3.        // Set up data connection.  
  4.        DataConnection conn = DataConnection.getInstance();       
  5.            if (connectMode == 0) {  
  6.                ret = conn.openConnection(mContext, “cmwap”, “cmwap”, “cmwap”);  
  7.            } else {  
  8.                ret = conn.openConnection(mContext, “cmnet”, “”, “”);  
  9.            }  
  10.    }  



12:PreferenceActivity 用法

[java]  view plain copy
  1. public class Setting extends PreferenceActivity  
  2. {  
  3.     public void onCreate(Bundle savedInstanceState) {  
  4.         super.onCreate(savedInstanceState);  
  5.         addPreferencesFromResource(R.xml.settings);  
  6.     }  
  7. }  
  8. Setting.xml:  
  9.             android:key=”seting2″  
  10.             android:title=”@string/seting2″  
  11.             android:summary=”@string/seting2″/>  
  12.             android:key=”seting1″  
  13.             android:title=”@string/seting1″  
  14.             android:summaryOff=”@string/seting1summaryOff”  
  15.             android:summaryOn=”@stringseting1summaryOff”/>  

13:通过HttpClient从指定server获取数据

            
[java]  view plain copy
  1. DefaultHttpClient httpClient = new DefaultHttpClient();  
  2.             HttpGet method = new HttpGet(“http://www.baidu.com/1.html”);  
  3.             HttpResponse resp;  
  4.             Reader reader = null;  
  5.             try {  
  6.                 // AllClientPNames.TIMEOUT  
  7.                 HttpParams params = new BasicHttpParams();  
  8.                 params.setIntParameter(AllClientPNames.CONNECTION_TIMEOUT, 10000);  
  9.                 httpClient.setParams(params);  
  10.                 resp = httpClient.execute(method);  
  11.                 int status = resp.getStatusLine().getStatusCode();  
  12.                 if (status != HttpStatus.SC_OK) return false;  
  13.                 // HttpStatus.SC_OK;  
  14.                 return true;  
  15.             } catch (ClientProtocolException e) {  
  16.                 // TODO Auto-generated catch block  
  17.                 e.printStackTrace();  
  18.             } catch (IOException e) {  
  19.                 // TODO Auto-generated catch block  
  20.                 e.printStackTrace();  
  21.             } finally {  
  22.                 if (reader != nulltry {  
  23.                     reader.close();  
  24.                 } catch (IOException e) {  
  25.                     // TODO Auto-generated catch block  
  26.                     e.printStackTrace();  
  27.                 }  
  28.             }  
14、获取手机屏幕分辨率
[java]  view plain copy
  1. DisplayMetrics  dm = new DisplayMereics();  
  2.   
  3.         getWindowManager().getDefaultDisplay().getMetrics(dm);  
  4.   
  5.         float width = dm.widthPixels * dm.density;  
  6.   
  7.         float height = dm.heightPixels * dm.density  
     在这里问什么要乘以  dm.density   了,是因为通过dm.widthPixels的到的结果始终是320,不是真实的屏幕分辨率,所以要乘以dm.density得到真实的分辨率。
     15、在Activity里面播放背景音乐
[java]  view plain copy
  1. public void onCreate(Bundle savedInstanceState) {  
  2.              super.onCreate(savedInstanceState);  
  3.              setContentView(R.layout.mainlay);  
  4.              mediaPlayer = MediaPlayer.create(this, R.raw.mu);  
  5.              mediaPlayer.setLooping(true);  
  6.              mediaPlayer.start();  
  7.   
  8.                    }  


      16、让程序的界面不随机器的重力感应而翻转

                 第一种方法,在manifast文件里面

[html]  view plain copy
  1. <activity  
  2.   android:screenOrientation="portrait">  
  3.   </activity>  

                  第二种,在代码里面

[java]  view plain copy
  1. setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);  

     17、使activity全屏显示

[java]  view plain copy
  1. requestWindowFeature(Window.FEATURE_NO_TITLE);  
  2.         getWindow().setFlags(WindowManager.LayoutParams. FLAG_FULLSCREEN ,        
  3.                 WindowManager.LayoutParams. FLAG_FULLSCREEN);  

        18、在RelativeLayout中使selector要注意点

         关于selector的使用方法,可以参考http://blog.csdn.net/aomandeshangxiao/article/details/6759576这篇文章,今天,遇到在RelativeLayout中添加background为selector后没有反应的问题,寻摸了很长时间,一直没有找到原因,其实只要加上一句代码就完全可以解决:

[java]  view plain copy
  1. <span style="font-size:16px;">RelativeLayout 里面加上android:clickable="true"</span>  

这样,RelativLayout就会出现在selector里面定义的效果。


   19、显示或隐藏虚拟键盘

[java]  view plain copy
  1. 显示:  
  2. InputMethodManager imm = (InputMethodManager)(getSystemService(Context.INPUT_METHOD_SERVICE));  
  3. imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);  
  4.   
  5. 隐藏:  
  6. InputMethodManager imm = (InputMethodManager)(getSystemService(Context.INPUT_METHOD_SERVICE));  
  7. imm.hideSoftInputFromWindow(m_edit.getWindowToken(), 0);  

   20、退出程序时清除通知中信息  

[java]  view plain copy
  1. NotificationManager nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);  
  2. nm.cancelAll();  

     21、创建快捷方式

[java]  view plain copy
  1. Intent intent=new Intent();  
  2. //设置快捷方式的图标  
  3. intent.putExtra(Intent.EXTRA_SHORTCUT_ICON_RESOURCE, Intent.ShortcutIconResource.fromContext(this, R.drawable.img));  
  4. //设置快捷方法的名称  
  5. intent.putExtra(Intent.EXTRA_SHORTCUT_NAME, "点击启动哥的程序");            //设置点击快键图标的响应操作  
[java]  view plain copy
  1. intent.putExtra(Intent.EXTRA_SHORTCUT_INTENT, new Intent(this,MainActivity.class));  
  2. //传递Intent对象给系统  
  3. setResult(RESULT_OK, intent);  
  4. finish();  

 

   22、获取文件中的类名:

[java]  view plain copy
  1. String path = context.getPackageManager().getApplicationInfo(  
  2.                                         context.getPackageName(), 0).sourceDir;  
  3.                         DexFile dexfile = new DexFile(path);  
  4.                         Enumeration<String> entries = dexfile.entries();  
  5.                         while (entries.hasMoreElements()) {  
  6.                                 String name = (String) entries.nextElement();  
  7.                                 ......  
  8.                         }  



23. TextView中的getTextSize返回值是以像素(px)为单位的,

而setTextSize()是以sp为单位的.

所以如果直接用返回的值来设置会出错,解决办法是:

用setTextSize()的另外一种形式,可以指定单位:

[java]  view plain copy
  1. TypedValue.COMPLEX_UNIT_PX : Pixels    
  2. TypedValue.COMPLEX_UNIT_SP : Scaled Pixels    
  3. TypedValue.COMPLEX_UNIT_DIP : Device Independent Pixels  

24. 在继承自View时,绘制bitmap时,需要将图片放到新建的drawable-xdpi

中,否则容易出现绘制大小发生改变


25. 在文字中加下划线: textView.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); 


26. scrollView是继承自frameLayout,所以在使用LayoutParams时需要用frameLayout

 

27、android阴影字体设置

 

[html]  view plain copy
  1. <TextView  android:id="@+id/tvText1"   
  2.  android:layout_width="wrap_content"   
  3.  android:layout_height="wrap_content"   
  4.  android:text="text1"   
  5.  android:textSize="30sp"   
  6.  android:textStyle="bold"   
  7.  android:textColor="#FFFFFF"   
  8.  android:shadowColor="#ff0000ff"  
  9.  android:shadowDx="5"  
  10.  android:shadowDy="5"       
  11.  android:shadowRadius="10"/>  


 

android:shadowColor 阴影颜色

android:shadowDx 阴影的水平偏移量

android:shadowDy 阴影的垂直偏移量

android:shadowRadius 阴影的范围

 

为了统一风格和代码的复用,通常可以把这个样式抽取放入到style.xml文件中

[html]  view plain copy
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.     <style name="textstyle">         
  4.         <item name="android:shadowColor">#ff0000ff</item>  
  5.         <item name="android:shadowRadius">10</item>  
  6.         <item name="android:shadowDx">5</item>  
  7.         <item name="android:shadowDy">5</item>       
  8.     </style>  
  9. </resources>  
[html]  view plain copy
  1. <TextView  
  2.         style="@style/textstyle"  
  3.         android:layout_width="fill_parent"  
  4.         android:layout_height="wrap_content"  
  5.         android:text="字体样式"  
  6.         android:textSize="30sp"  
  7.         android:textStyle="bold" />  

 

28、android实现手机震动功能

[java]  view plain copy
  1. import android.app.Activity;  
  2. import android.app.Service;  
  3. import android.os.Vibrator;  
  4.   
  5. public class TipHelper {   
  6.     public static void Vibrate(final Activity activity, long milliseconds) {  
  7.         Vibrator vib = (Vibrator) activity.getSystemService(Service.VIBRATOR_SERVICE);  
  8.         vib.vibrate(milliseconds);  
  9.     }  
  10.     public static void Vibrate(final Activity activity, long[] pattern,boolean isRepeat) {  
  11.         Vibrator vib = (Vibrator) activity.getSystemService(Service.VIBRATOR_SERVICE);  
  12.         vib.vibrate(pattern, isRepeat ? 1 : -1);  
  13.     }  
  14. }  


还需要在AndroidManifest.xml 中添加震动权限:

[html]  view plain copy
  1. <uses-permission android:name="android.permission.VIBRATE" />  
通过上面操作,我们可以使用TipHelper所定义的函数了。两个Vibrate函数的参数简单介绍如下:

final Activity activity  :调用该方法的Activity实例

long milliseconds :震动的时长,单位是毫秒

long[] pattern    :自定义震动模式 。数组中数字的含义依次是[静止时长,震动时长,静止时长,震动时长。。。]时长的单位是毫秒

boolean isRepeat : 是否反复震动,如果是true,反复震动,如果是false,只震动一次

29、常用的正则表达式

       ^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$    //email地址 
       ^[a-zA-z]+://(\w+(-\w+)*)(\.(\w+(-\w+)*))*(\?\S*)?$  //url
       ^(d{2}|d{4})-((0([1-9]{1}))|(1[1|2]))-(([0-2]([1-9]{1}))|(3[0|1]))$ //年-月-日
       ^((0([1-9]{1}))|(1[1|2]))/(([0-2]([1-9]{1}))|(3[0|1]))/(d{2}|d{4})$  //月/日/年
       ^([w-.]+)@(([[0-9]{1,3}.[0-9]{1,3}.[0-9]{1,3}.)|(([w-]+.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(]?)$   //Emil
       ^((\+?[0-9]{2,4}\-[0-9]{3,4}\-)|([0-9]{3,4}\-))?([0-9]{7,8})(\-[0-9]+)?$     //电话号码
       ^(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5]).(d{1,2}|1dd|2[0-4]d|25[0-5])$   //IP地址

       (^\s*)|(\s*$)   // 首尾空格

       ^[a-zA-Z][a-zA-Z0-9_]{4,15}$  // 帐号是否合法(字母开头,允许5-16字节,允许字母数字下划线)

       ^[1-9]*[1-9][0-9]*$  //  腾讯QQ号

30、输入框不挤压activity布局:

在manifest文件activity下 加:

[html]  view plain copy
  1. android:windowSoftInputMode="adjustPan"  

31、listview中item中button可点击:

[html]  view plain copy
  1. android:descendantFocusability="blocksDescendants"  

32、获取移动设备的IP地址:

[java]  view plain copy
  1. public class Tools {  
  2.     public static String getLocalIpAddress() {    
  3.         try {    
  4.             for (Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces(); en.hasMoreElements();) {    
  5.                 NetworkInterface intf = en.nextElement();    
  6.                 for (Enumeration<InetAddress> enumIpAddr = intf.getInetAddresses(); enumIpAddr.hasMoreElements();) {    
  7.                     InetAddress inetAddress = enumIpAddr.nextElement();    
  8.                     if (!inetAddress.isLoopbackAddress()) {    
  9.                         return inetAddress.getHostAddress().toString();    
  10.                     }    
  11.                 }    
  12.             }    
  13.         } catch (SocketException ex) {    
  14.             Log.e("出错啦", ex.toString());    
  15.         }    
  16.         return null;    
  17.     }    
  18. }  
  19. 然后  
  20.         WifiManager wm = (WifiManager)getSystemService(WIFI_SERVICE);  
  21.         WifiInfo wi = wm.getConnectionInfo();  
  22.         System.out.println("IP地址是:"+Tools.getLocalIpAddress());  
  23.         System.out.println("SSID:"+wi.getSSID());  
  24. 最后记得加两个权限  
  25.     <uses-permission android:name="android.permission.INTERNET"/>  
  26.     <uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>  


33、高仿小米launcher跨屏拖动item(GridView长按item进行拖动

        触发长按事件后浮动原理:

     

[java]  view plain copy
  1. windowParams = new WindowManager.LayoutParams();  
  2.   windowParams.gravity = Gravity.TOP | Gravity.LEFT;  
  3.   windowParams.x = x - itemWidth / 2;  
  4.   windowParams.y = y - itemHeight / 2;  
  5.   windowParams.height = WindowManager.LayoutParams.WRAP_CONTENT;  
  6.   windowParams.width = WindowManager.LayoutParams.WRAP_CONTENT;  
  7.   ImageView iv = new ImageView(getContext());  
  8.   iv.setImageBitmap(bm);  
  9.   windowManager = (WindowManager) getContext().getSystemService(  
  10.   Context.WINDOW_SERVICE);// "window"  
  11.   windowManager.addView(iv, windowParams);  
       拖动效果:

[java]  view plain copy
  1. if (dragImageView != null) {  
  2.   windowParams.alpha = 0.6f;  
  3.   windowParams.x = x - itemWidth / 2;  
  4.   windowParams.y = y - itemHeight / 2;  
  5.   windowManager.updateViewLayout(dragImageView, windowParams);  
  6.   }  




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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值