zoukankan      html  css  js  c++  java
  • 转: N个Android很有用的代码片段

    我也无法找到原文出自哪里,网上转帖太多了!

    1:查看是否有存储卡插入
    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来取得屏幕上的元素的句柄. 使用该句柄您可以设置或获取任何该对象外露的值.

    1 TextView msgTextView = (TextView)findViewById(R.id.msg);
    2 msgTextView.setText(R.string.push_me);

    4:发送短信

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

               

       5:发送彩信

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

    根本没有第6个???          

    7:发送Mail

    1 String 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);

                

    8:注册一个BroadcastReceiver

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

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

    private ContentObserver mDownloadsObserver = new DownloadsChangeObserver(Downloads.CONTENT_URI);
    
    private class DownloadsChangeObserver extends ContentObserver {
            public DownloadsChangeObserver(Uri uri) {
                super(new Handler());
            }
    
            @Override
            public void onChange(boolean selfChange) {}  
    }

       

    10:获得 手机UA

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

    11:清空手机上Cookie

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

    12:建立GPRS连接

      

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

    13:PreferenceActivity 用法

    1 public class Setting extends PreferenceActivity
    2 3     public void onCreate(Bundle savedInstanceState) {
    4         super.onCreate(savedInstanceState);
    5         addPreferencesFromResource(R.xml.settings);
    6     }
    7

    Setting.xml:

                android:key=”seting2″
                android:title=”@string/seting2″
                android:summary=”@string/seting2″/>

                android:key=”seting1″
                android:title=”@string/seting1″
                android:summaryOff=”@string/seting1summaryOff”
                android:summaryOn=”@stringseting1summaryOff”/>

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

                

     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 
    13 
    14                 if (status != HttpStatus.SC_OK) return false;
    15 
    16 
    17                 // HttpStatus.SC_OK;
    18                 return true;
    19             } catch (ClientProtocolException e) {
    20                 // TODO Auto-generated catch block
    21                 e.printStackTrace();
    22             } catch (IOException e) {
    23                 // TODO Auto-generated catch block
    24                 e.printStackTrace();
    25             } finally {
    26                 if (reader != null) try {
    27                     reader.close();
    28                 } catch (IOException e) {
    29                     // TODO Auto-generated catch block
    30                     e.printStackTrace();
    31                 }
    32             }

    15:显示toast

    1 Toast.makeText(this._getApplicationContext(), R.string._item, Toast.LENGTH_SHORT).show();

    16.在当前Activity中启动另外一个Activity

     

    1 startActivity(new Intent(this,目标Activity.class)); 

     

    17:从当前ContentView从查找控件 

    (Button)findViewById(R.id.btnAbout)   
    //R.id.btnAbout指控件id

     

    18:获取屏幕宽高 

    1 DisplayMetrics dm = new DisplayMetrics();   //获取窗口属性  
    2 getWindowManager().getDefaultDisplay().getMetrics(dm);
    3 int screenWidth = dm.widthPixels;//320    
    4 int screenHeight = dm.heightPixels;//480 

     19:无标题栏、全屏

    1 //无标题栏    
    2 requestWindowFeature(Window.FEATURE_NO_TITLE);   
    3 
    4 //全屏模式    
    5 getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,    WindowManager.LayoutParams.FLAG_FULLSCREEN);  

    注意在setContentView()之前调用,否则无效。

    20注册activity 
        所有用到的Activity都必须在AndroidManifest.xml中注册,否则会报空指针错误。  如:,注意是包名+类名。

  • 相关阅读:
    [LeetCode]Word Break
    [LeetCode]singleNumber
    [LeetCode]Palindrome
    新浪博客无法访问
    C++基础之顺序容器
    C++基础之IO类
    [LeetCode]Restore IP Addresses
    [LeetCode]Maximal Rectangle
    [LeetCode]Reverse Linked List II
    ACM 树形数组
  • 原文地址:https://www.cnblogs.com/mushui/p/3334106.html
Copyright © 2011-2022 走看看