HardBirch

Android很有用的代码片段

时间:11-07-13 栏目:安卓源码解析与小应用 作者:张飞不张,文采横飞 评论:0 点击: 5,557 次

1:查看是否有存储卡插入

String status=Environment.getExternalStorageState();
if(status.equals(Enviroment.MEDIA_MOUNTED))
{
   说明有SD卡插入
}

2:让某个Activity透明

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

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

使用Activity.findViewById来取得屏幕上的元素的句柄. 使用该句柄您可以设置或获取任何该对象外露的值.

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

4:发送短信

          

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

5:发送彩信

           

StringBuilder sb = new StringBuilder();
            sb.append(”file://”);
            sb.append(fd.getAbsoluteFile());
            Intent intent = new Intent(Intent.ACTION_SENDTO, Uri.fromParts(”mmsto”, number, null));
            // Below extra datas are all optional.
            intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_SUBJECT, subject);
            intent.putExtra(Messaging.KEY_ACTION_SENDTO_MESSAGE_BODY, body);
            intent.putExtra(Messaging.KEY_ACTION_SENDTO_CONTENT_URI, sb.toString());
            intent.putExtra(Messaging.KEY_ACTION_SENDTO_COMPOSE_MODE, composeMode);
            intent.putExtra(Messaging.KEY_ACTION_SENDTO_EXIT_ON_SENT, exitOnSent);
            startActivity(intent)

6:发送Mail

         

mime = “img/jpg”;
            shareIntent.setDataAndType(Uri.fromFile(fd), mime);
            shareIntent.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(fd));
            shareIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
            shareIntent.putExtra(Intent.EXTRA_TEXT, body);

7:注册一个BroadcastReceiver

registerReceiver(mMasterResetReciever, new IntentFilter(”oms.action.MASTERRESET”));
private BroadcastReceiver mMasterResetReciever = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent){
            String action = intent.getAction();
            if(”oms.action.MASTERRESET”.equals(action)){
                RecoverDefaultConfig();
            }
        }
    }

8:定义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) {}
        }

 
9:获得 手机UA

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

10:清空手机上Cookie

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

11:建立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”, “”, “”);
            }
    }

12:PreferenceActivity 用法

public class Setting extends PreferenceActivity
{
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        addPreferencesFromResource(R.xml.settings);
    }
}
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”/>

13:通过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();
                }
            }

声明: 本文由( 张飞不张,文采横飞 )原创编译,转载请保留链接: Android很有用的代码片段

Android很有用的代码片段:目前有

  1. android中调用其它android应用
    在android中,有时候需要调用其他应用的activity,可以是使用一下方法:# ComponentName comp = new ComponentName("com.Test","com.login.Main");
    # intent = new Intent();
    # intent.setComponent(comp);
    # intent.setAction("android.intent.action.VIEW");
    #
    # startActivity(intent);

    2011-10-10 17:41 [回复]
  2. Log.v("@@@@@@@@@@",Thread.currentThread().getId()+" "+Thread.currentThread().getName());获取线程id和线程名称。

    2011-10-17 22:06 [回复]
  3. 如果在布局文件中引用TabHost是可以实现将TabWidget显示在屏幕下方,我的上一篇帖子就使用的这种方法,设置TabWidget的属性 android:layout_alignParentBottom="true"就可以了。这篇帖子中用的是TabActivity,设置这个属性就不起作用了。

    2011-10-18 10:14 [回复]
  4. 为了让tabHost显示在下方,要将RadioGroup的layout_gravity设置为bottom,再将FrameLayout的 layout_weight设置为1,这样就可以将RadioGroup撑到最下方。style="@style/main_tab_bottom"里面定义了样式文件。可以试试咯!

    2011-10-18 10:14 [回复]
  5. # DisplayMetrics displayMetrics = new DisplayMetrics();
    # this.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
    # int height = displayMetrics.heightPixels;
    # int width = displayMetrics.widthPixels;

    获取屏幕宽高。

    2011-11-16 10:55 [回复]
  6. 不错……

    2011-11-16 10:57 [回复]
  7. [reply]yizaitianya1987[/reply]
    转载的。

    2011-11-16 14:19 [回复]
  8. 5楼
    jyygn:

    不错

    2011-11-22 11:44 [回复]
  9. [reply]jyygn[/reply]
    呵呵,备用,留作代码库。。。

    2011-11-22 16:48 [回复]
  10. String archiveFilePath="sdcard/download/Law.apk";//安装包路径
    PackageManager pm = getPackageManager();
    PackageInfo info = pm.getPackageArchiveInfo(archiveFilePath, PackageManager.GET_ACTIVITIES);
    if(info != null){
    ApplicationInfo appInfo = info.applicationInfo;
    String appName = pm.getApplicationLabel(appInfo).toString();
    String packageName = appInfo.packageName; //得到安装包名称
    String version=info.versionName; //得到版本信息
    Toast.makeText(test4.this, "packageName:"+packageName+";version:"+version, Toast.LENGTH_LONG).show();
    Drawable icon = pm.getApplicationIcon(appInfo);//得到图标信息
    TextView tv = (TextView)findViewById(R.id.tv); //显示图标
    tv.setBackgroundDrawable(icon);

    2011-11-22 22:29 [回复]
  11. (1)android中获取当前程序路径
    getApplicationContext().getFilesDir().getAbsolutePath()
    (2)android取已安装的程序列表
    List<PackageInfo> packageInfoList = getPackageManager().getInstalledPackages(0);

    2011-11-22 22:29 [回复]
  12. PackageInfo info = this.getPackageManager().getPackageInfo(this.getPackageName(), 0);
    int versionCode=nfo.versionCode
    string versionName=info.versionName

    2011-11-23 11:47 [回复]

发表评论


QQ群互动

Linux系统与内核学习群:194051772

WP建站技术学习交流群:194062106

魔豆之路QR

魔豆的Linux内核之路

魔豆的Linux内核之路

优秀工程师当看优秀书籍

优秀程序员,要看优秀书!

赞助商广告

友荐云推荐