疯狂java迷

 

项目中用到的android代码

1、全屏窗口
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
Preference Activity
Layout\crc.xml
<?xml version="1.0" encoding="utf-8" ?>
<PreferenceScreen xmlns:android="http://schemas.android.com/apk/res/android">
    <PreferenceCategory android:title="CRC Test">
        <PreferenceScreen
            android:title="1. BIN CRC"
            android:summary="Code Area CRC"
            android:key="bin_crc">
        </PreferenceScreen>
         <PreferenceScreen
            android:title="2. EFS CRC Detail"
            android:summary="EFS CRC Detail"
            android:key="efs_crc">
            <intent
                android:action="android.intent.action.MAIN"
                android:targetPackage="com.dhz.testapp"
                android:targetClass="com.dhz.testapp.efscrc"/>
        </PreferenceScreen>
    </PreferenceCategory>
</PreferenceScreen>

 

 

2、Preference 添加单击处理
PreferenceScreen BINCRC = (PreferenceScreen)getPreferenceScreen().findPreference("bin_crc");
BINCRC.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
         public boolean onPreferenceClick(Preference preference) {
               BINCRC.setSummary("Detect a click");
              return true;
         }
         });

 

 

3、运行一个命令或程序获取结果/正则表达式查找匹配/分隔字符串
Process process1 = new ProcessBuilder("cat", "/opl/etc/system.prop").start();  
     BufferedReader br1 = new BufferedReader(new InputStreamReader(process1.getInputStream()));  
     Pattern pattern = Pattern.compile("apps.setting.platformversion");      
     String line;      
     while ((line = br1.readLine()) != null) {  
      Matcher matcher = pattern.matcher(line);  
      if(matcher.find(){    
       String[] temp = line.split(" = ");    
    
       if(temp.length > 1)
        mRver.setSummary(temp[1]);
       else
        mRver.setSummary("/opl/etc/system.prop not configed well.");
      }
     }
     if(process1 != null)
      process1.destroy();
     if(br1 != null)
      br1.close();

 

 

4、计算一个文件的CRC32值
import java.util.zip.CRC32;

FileInputStream inStream = null;
   BufferedInputStream in = null;
   CRC32 crc32 = new CRC32();
    inStream = new FileInputStream(filePath);
    in = new BufferedInputStream(inStream,size_8k);
     
       for(int i;(i=in.read())!=-1;)
     {
        crc32.update(i);
     }
   
       Log.d(TAG, filePath +" CRC32: "+Long.toHexString(crc32.getValue()));
   if(inStream != null)
     inStream.close();
    if(in != null)
     in.close();

 

 

5、显示一个模态对话框,带yes/no按钮
new AlertDialog.Builder(efscrc.this)
           .setMessage("Work Done! Show results?")
                 .setCancelable(false)
                 .setPositiveButton("Yes",
           new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int whichButton) {
          
            showResult();
  
            }
           })
         .setNegativeButton("No",
           new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int whichButton) {
             dialog.dismiss();
            }
           })
         .show();

 

 

6、判断是否有SDCard
     if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED))
     {
      copyToSDCard(logFilePath);
     }
     else {
      Toast.makeText(FPRITest.this,"No SDCard! Please insert SDCard. ",Toast.LENGTH_SHORT).show();
     }

 

 

7、结果集排序/List遍历
List<String> resultList = new ArrayList<String>();
resultList.add(str1);
......
resultList.add(strn);
Collections.sort(resultList);

FileOutputStream outStream = new FileOutputStream(efsCRCResultFile);
Iterator itr = resultList.iterator();
while (itr.hasNext()) {
   outStream.write(((String)itr.next()).getBytes());
}

 

 

8、非递归方法枚举目录下所有文件(含子目录)
private void getFileList(String dirPath)
{
   LinkedList<File> mDirList = new LinkedList<File>();
    File dir = n
103f
ew File(dirPath);
   mDirList.add(dir);

File files[] = null;
    int count = 0;
    String filePath = null;
    File tmp = null;
       
  
    while (!mDirList.isEmpty()) {
        tmp = mDirList.removeFirst(); 
        //handle files in one directory.
       files = tmp.listFiles();
        if (files == null)
            continue;
        for (int i = 0; i < files.length; i++)
        {
            if (files[i].isDirectory())
            mDirList.add(files[i]);
            else
            {
            Log.d(TAG,files[i].getAbsolutePath() + " " + count);
            count ++;        
            }
        }           
  
    }
   
    Log.d(TAG,"getFileList finish,file count: " + count);
  
}

 

 

9、添加秘密程序,通过拨号启动
AndroidManifest.xml
<receiver android:name=".secret">
       <intent-filter>
       <action android:name="android.provider.Telephony.SECRET_CODE" />
       <data android:scheme="android_secret_code" android:host="1234"/>
      </intent-filter>
</receiver>

secret.java
public class secret extends BroadcastReceiver {
         
    @Override
    public void onReceive(Context context, Intent intent) {
    String action = intent.getAction();
    String host = intent.getData() != null ? intent.getData().getHost() : null;
     
    if (Intents.SECRET_CODE_ACTION.equals(action) && "1234".equals(host)) {
       //start an acitivity
      }
    }
}

SECRET_CODE_ACTION
public static final String SECRET_CODE_ACTION Broadcast Action: A "secret code" has been entered in the dialer. Secret codes are of the form *#*##*#*. The intent will have the data URI:
android_secret_code://<code>

 

 

10、格式化SD卡/卸载SD卡
private IMountService   mMountService;
mMountService = getMountService();

private synchronized IMountService getMountService() {
        if (mMountService == null) {
            IBinder service = ServiceManager.getService("mount");
            if (service != null) {
                mMountService = IMountService.Stub.asInterface(service);
            } else {
                Log.e(TAG, "Can't get mount service");
            }
        }
        return mMountService;
     }
//format sdcard
mMountService.formatMedia(Environment.getExternalStorageDirectory().toString());
//unmount sdcard
mMountService.unmountMedia(Environment.getExternalStorageDirectory().toString());

 

 

11、保持屏幕常亮

PowerManager.WakeLock wakeLock;


 

 

12、启用屏幕常亮功能
wakeLock = ((PowerManager)getSystemService(POWER_SERVICE)).
newWakeLock(PowerManager.SCREEN_BRIGHT_WAKE_LOCK | PowerManager.ON_AFTER_RELEASE, "MyActivity");
wakeLock.acquire();

//PowerManager.SCREEN_DIM_WAKE_LOCK 这个可维持在低明状态,还有其他的标志,可参考Andoid文档

 

 

13、关闭屏幕常亮功能
if (wakeLock != null) {
wakeLock.release();
}

 

 

15、需要权限
<uses-permission android:name="android.permission.WAKE_LOCK" />

为了不对其他程序造成影响,启用和关闭屏幕常亮的代码一般被放在 Activity 的 onResume() 和 onPause() 事件中。
调用setting的校准屏幕功能
Intent intent = new Intent();
intent.setAction("android.intent.action.MAIN");
intent.setComponent(new ComponentName("com.android.settings","com.android.settings.Calibration"));
startActivity(intent);

 

 

16、DOM解析XML文档
DOM为XML 文档的解析定义了一组接口。解析器读入整个文档,然后构建一个驻留内存的树结构,然后代码就可以使用 DOM 接口来操作这个树结构。
优点:整个文档树在内存中,便于操作;支持删除、修改、重新排列等多种功能;
缺点:将整个文档调入内存(包括无用的节点),浪费时间和空间;
使用场合:一旦解析了文档还需多次访问这些数据;硬件资源充足(内存、CPU)。
public void parserXml(String fileName) {
try {
   DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
   DocumentBuilder db = dbf.newDocumentBuilder();
   Document document = db.parse(fileName);
 
   NodeList employees = document.getChildNodes();
   for (int i = 0; i < employees.getLength(); i++) { };
 
   NodeList paramList = document.getElementsByTagName("yourTag");
   for(int i=0; i<paramList.getLength(); i++){
    Node paramNode = paramList.item(i);
    NamedNodeMap attrs = paramNode
103f
.getAttributes();
    for(int j=0; j<attrs.getLength();j++){
     String itemName = attrs.item(j).getNodeName();
     String itemVal = attrs.item(j).getNodeValue();
    }
   }
  
} catch (Exception e) {
   e.printStackTrace();
}
}


//////////////////////////
\androin 有用的代码片段
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
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 PreferenceA
103f
ctivity

    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();
                }
            }

 


14:显示toast

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


///////////////////////////
\android 常用代码示例
///////////////////////////
1、
Intent用法2010-04-27 12:09Intent it = new Intent(Activity.Main.this, Activity2.class);
startActivity(it);

 

 

2.
向下一个Activity传递数据(使用Bundle和Intent.putExtras) Intent it = new Intent(Activity.Main.this, Activity2.class);
Bundle bundle=new Bundle();
bundle.putString("name", "This is from MainActivity!");
it.putExtras(bundle); // it.putExtra(“test”, "shuju”);
startActivity(it); // startActivityForResult(it,REQUEST_CODE);
对于数据 的获取可以采用: Bundle bundle=getIntent().getExtras();
String name=bundle.getString("name");

 

 

3.
 向上一个Activity返回结果(使用setResult,针对startActivityForResult(it,REQUEST_CODE)启动 的Activity) Intent intent=getIntent();
Bundle bundle2=new Bundle();
bundle2.putString("name", "This is from ShowMsg!");
intent.putExtras(bundle2);
setResult(RESULT_OK, intent);

 

 

4.
 回调上一个Activity的结果处理函数(onActivityResult) @Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
// TODO Auto-generated method stub
super.onActivityResult(requestCode, resultCode, data);
if (requestCode==REQUEST_CODE){
if(resultCode==RESULT_CANCELED)
setTitle("cancle");
else if (resultCode==RESULT_OK) {
String temp=null;
Bundle bundle=data.getExtras();
if(bundle!=null) temp=bundle.getString("name");
setTitle(temp);
}
}
}

 

 

5、
显示网页
Uri uri = Uri.parse("http://google.com");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);

 

 

6、
显示地图
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


 

7、
路径规划
Uri uri = Uri.parse("http://maps.google.com/maps?f=d&saddr=startLat%20startLng&daddr=endLat%20endLng&hl=en");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
startActivity(it);
 //where startLat, startLng, endLat, endLng are a lo
e3c
ng with 6 decimals like: 50.123456

 

打 电话

1. //叫出拨号程序
2. Uri uri = Uri.parse("tel:0800000123");
3. Intent it = new Intent(Intent.ACTION_DIAL, uri);
4. startActivity(it);

1. //直接打电话出去
2. Uri uri = Uri.parse("tel:0800000123");
3. Intent it = new Intent(Intent.ACTION_CALL, uri);
4. startActivity(it);
5. //用這個,要在 AndroidManifest.xml 中,加上
6. //<uses-permission id="android.permission.CALL_PHONE" />

传 送SMS/MMS

1. //调用短信程序
2. Intent it = new Intent(Intent.ACTION_VIEW, uri);
3. it.putExtra("sms_body", "The SMS text");
4. it.setType("vnd.android-dir/mms-sms");
5. startActivity(it);

1. //传送消息
2. Uri uri = Uri.parse("smsto://0800000123");
3. Intent it = new Intent(Intent.ACTION_SENDTO, uri);
4. it.putExtra("sms_body", "The SMS text");
5. startActivity(it);

1. //传送 MMS
2. Uri uri = Uri.parse("content://media/external/images/media/23");
3. Intent it = new Intent(Intent.ACTION_SEND);
4. it.putExtra("sms_body", "some text");
5. it.putExtra(Intent.EXTRA_STREAM, uri);
6. it.setType("image/png");
7. startActivity(it);

传 送 Email

1. Uri uri = Uri.parse("mailto:xxx@abc.com");
2. Intent it = new Intent(Intent.ACTION_SENDTO, uri);
3. startActivity(it);
1. Intent it = new Intent(Intent.ACTION_SEND);
2. it.putExtra(Intent.EXTRA_EMAIL, "me@abc.com");
3. it.putExtra(Intent.EXTRA_TEXT, "The email body text");
4. it.setType("text/plain");
5. startActivity(Intent.createChooser(it, "Choose Email Client"));
1. Intent it=new Intent(Intent.ACTION_SEND);
2. String[] tos={"me@abc.com"};
3. String[] ccs={"you@abc.com"};
4. it.putExtra(Intent.EXTRA_EMAIL, tos);
5. it.putExtra(Intent.EXTRA_CC, ccs);
6. it.putExtra(Intent.EXTRA_TEXT, "The email body text");
7. it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
8. it.setType("message/rfc822");
9. startActivity(Intent.createChooser(it, "Choose Email Client"));

1. //传送附件
2. Intent it = new Intent(Intent.ACTION_SEND);
3. it.putExtra(Intent.EXTRA_SUBJECT, "The email subject text");
4. it.putExtra(Intent.EXTRA_STREAM, "file:///sdcard/mysong.mp3");
5. sendIntent.setType("audio/mp3");
6. startActivity(Intent.createChooser(it, "Choose Email Client"));

播 放多媒体

Uri uri = Uri.parse("file:///sdcard/song.mp3");
Intent it = new Intent(Intent.ACTION_VIEW, uri);
it.setType("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);

Market 相关

1. //寻找某个应用
2. Uri uri = Uri.parse("market://search?q=pname:pkg_name");
3. Intent it = new Intent(Intent.ACTION_VIEW, uri);
4. startActivity(it);
5. //where pkg_name is the full package path for an application

1. //显示某个应用的相关信息
2. Uri uri = Uri.parse("market://details?id=app_id");
3. Intent it = new Intent(Intent.ACTION_VIEW, uri);
4. startActivity(it);
5. //where app_id is the application ID, find the ID
6. //by clicking on your application on Market home
7. //page, and notice the ID from the address bar

Uninstall 应用程序

1. Uri uri = Uri.fromParts("package", strPackageName, null);
2. Intent it = new Intent(Intent.ACTION_DELETE, uri);
3. startActivity(it);

/////////////////////////////////////////////////////////
\
///////////////////////////////////////////////////////
1、用代码安装APK程序
Intent i = new Intent(Intent.ACTION_VIEW);  
String filePath = "/sdcard/XXX.apk";  
i.setDataAndType(Uri.parse("file://" + filePath),"application/vnd.android.package-archive");  
context.startActivity(i);  

 

posted on 2011-12-01 16:34  疯狂java迷  阅读(626)  评论(0)    收藏  举报

导航