1.Android EditText的输入监听,输入字符的动态获取

有时候我们可能会用到时时的监听EditText输入字符的时时监听,监听字符的个数,做一些正则表达式的处理等。如下方法可以实现:

我做的是时时的把EditeText输入的数据同步到TextView上

布局文件:

[html] view plain copy
  1. <RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"
  2. xmlns:tools="http://schemas.android.com/tools"
  3. android:layout_width="match_parent"
  4. android:layout_height="match_parent">
  5. <TextView
  6. android:id="@+id/textview"
  7. android:layout_width="wrap_content"
  8. android:layout_height="wrap_content"
  9. android:layout_centerHorizontal="true"
  10. android:layout_centerVertical="true"
  11. android:padding="@dimen/padding_medium"
  12. tools:context=".Test02Activity"/>
  13. <EditText
  14. android:id="@+id/editText1"
  15. android:layout_width="fill_parent"
  16. android:layout_height="wrap_content"
  17. android:layout_alignLeft="@+id/textview"
  18. android:layout_below="@+id/textview"
  19. android:layout_marginTop="31dp"
  20. >
  21. <requestFocus/>
  22. </EditText>
  23. </RelativeLayout>

java代码:

[html] view plain copy
  1. packagecom.example.testdemo;
  2. importandroid.os.Bundle;
  3. importandroid.app.Activity;
  4. importandroid.util.Log;
  5. importandroid.view.Menu;
  6. importandroid.view.MenuItem;
  7. importandroid.widget.EditText;
  8. importandroid.widget.TextView;
  9. importandroid.support.v4.app.NavUtils;
  10. importandroid.text.Editable;
  11. importandroid.text.TextWatcher;
  12. publicclassTest02ActivityextendsActivity{
  13. privatestaticfinalStringTAG="Test";
  14. privateEditTextmEditText;
  15. privateTextViewmTextView;
  16. @Override
  17. publicvoidonCreate(BundlesavedInstanceState){
  18. super.onCreate(savedInstanceState);
  19. setContentView(R.layout.activity_test02);
  20. mEditText=(EditText)findViewById(R.id.editText1);
  21. mTextView=(TextView)findViewById(R.id.textview);
  22. mEditText.addTextChangedListener(newTextWatcher(){
  23. @Override
  24. publicvoidafterTextChanged(Editables){
  25. Log.d(TAG,"afterTextChanged");
  26. }
  27. @Override
  28. publicvoidbeforeTextChanged(CharSequences,intstart,intcount,
  29. intafter){
  30. Log.d(TAG,"beforeTextChanged:"+s+"-"+start+"-"+count+"-"+after);
  31. }
  32. @Override
  33. publicvoidonTextChanged(CharSequences,intstart,intbefore,
  34. intcount){
  35. Log.d(TAG,"onTextChanged:"+s+"-"+"-"+start+"-"+before+"-"+count);
  36. mTextView.setText(s);
  37. }
  38. });
  39. }
  40. @Override
  41. publicbooleanonCreateOptionsMenu(Menumenu){
  42. getMenuInflater().inflate(R.menu.activity_test02,menu);
  43. returntrue;
  44. }
  45. }


2.Android读取并备份用户短信(xml方式)

清单文件中需要加入两个权限:



MainActivity实现:

[java] view plain copy
  1. packagecom.mth.readMessage;
  2. importjava.io.File;
  3. importjava.io.FileOutputStream;
  4. importorg.xmlpull.v1.XmlSerializer;
  5. importandroid.app.Activity;
  6. importandroid.content.ContentResolver;
  7. importandroid.database.Cursor;
  8. importandroid.net.Uri;
  9. importandroid.os.Bundle;
  10. importandroid.os.Environment;
  11. importandroid.util.Xml;
  12. importandroid.view.View;
  13. importandroid.view.View.OnClickListener;
  14. importandroid.widget.Button;
  15. importandroid.widget.Toast;
  16. /**
  17. *说明:本程序的目的是通过创建xml文件在sd卡上
  18. *完成短信的备份
  19. *
  20. */
  21. publicclassMainActivityextendsActivity{
  22. privateButtonread_message;
  23. //短信备份的文件对象
  24. privateFilesmsBackUpFile;
  25. @Override
  26. protectedvoidonCreate(BundlesavedInstanceState){
  27. super.onCreate(savedInstanceState);
  28. setContentView(R.layout.activity_main);
  29. read_message=(Button)findViewById(R.id.read);
  30. read_message.setOnClickListener(newOnClickListener(){
  31. @Override
  32. publicvoidonClick(Viewarg0){
  33. try{
  34. /*
  35. *创建一个存储备份短信的文件对象(在sd卡上面创建一个叫sms.xml的文件对象)
  36. */
  37. smsBackUpFile=newFile(Environment
  38. .getExternalStorageDirectory(),"sms.xml");
  39. //创建一个xml文件的生成器
  40. XmlSerializerxmlSerializer=Xml.newSerializer();
  41. //完成序列化器初始操作
  42. FileOutputStreamout=newFileOutputStream(smsBackUpFile);
  43. xmlSerializer.setOutput(out,"utf-8");
  44. //内容提供者。
  45. ContentResolverresolver=getContentResolver();
  46. /*
  47. *uri查询什么样的路径(短信的路径)
  48. *projection获取数据中的哪几列数据
  49. *selectionselectionArgssortOrder查询条件可以都写null
  50. */
  51. //游标(结果集)
  52. Cursorcursor=resolver.query(Uri.parse("content://sms"),
  53. newString[]{"address","date","type","body"},
  54. null,null,null);
  55. /**
  56. *生成的xml文件格式
  57. *<smss>
  58. *<sms>
  59. *<address>110</address>
  60. *<body>nihaoa</body>
  61. *<date>时间</date>
  62. *<type>类型</type>
  63. *</sms>
  64. *</smss>
  65. */
  66. /**
  67. *生成xml文件的头
  68. */
  69. xmlSerializer.startDocument("utf-8",true);
  70. /**
  71. *生成根节点
  72. */
  73. xmlSerializer.startTag(null,"smss");
  74. while(cursor.moveToNext()){
  75. xmlSerializer.startTag(null,"sms");
  76. Stringaddress=cursor.getString(0);
  77. Stringdate=cursor.getString(1);
  78. Stringtype=cursor.getString(2);
  79. Stringbody=cursor.getString(3);
  80. /**
  81. *地址
  82. */
  83. xmlSerializer.startTag(null,"address");
  84. xmlSerializer.text(address);
  85. xmlSerializer.endTag(null,"address");
  86. /**
  87. *date
  88. */
  89. xmlSerializer.startTag(null,"date");
  90. xmlSerializer.text(date);
  91. xmlSerializer.endTag(null,"date");
  92. /**
  93. *body
  94. */
  95. xmlSerializer.startTag(null,"body");
  96. xmlSerializer.text(body);
  97. xmlSerializer.endTag(null,"body");
  98. /**
  99. *type
  100. */
  101. xmlSerializer.startTag(null,"type");
  102. xmlSerializer.text(type);
  103. xmlSerializer.endTag(null,"type");
  104. xmlSerializer.endTag(null,"sms");
  105. }
  106. cursor.close();
  107. /**
  108. *根节点配对
  109. */
  110. xmlSerializer.endTag(null,"smss");
  111. /**
  112. *生成文档的结尾
  113. */
  114. xmlSerializer.endDocument();
  115. /**
  116. *关闭输出流
  117. */
  118. out.close();
  119. Toast.makeText(getApplicationContext(),"短信备份成功!",
  120. Toast.LENGTH_LONG).show();
  121. }catch(Exceptione){
  122. //TODOAuto-generatedcatchblock
  123. e.printStackTrace();
  124. }
  125. }
  126. });
  127. }
  128. }

3.android电源管理PowerManager

PowerManager这个类提供了电源管理的一些功能,比如可以让屏幕或者键盘亮起来等。还有对设备的重启的api

官网是这么解释的

PowerManagerClass Overview

这个类提供了控制设备电源状态的管理功能。

设备的电池的持续时间(寿命)会受到使用这个API的重要影响。在非必要的情况下不要使用WakeLock,即使必须使用,也要最低限度使用这个api,使用完之后应确保立即释放掉。

通过Context.getSystemService()获得PowerManager的实例。

使用PowerManager的实例去获得一个WakeLock对象,使用这个方法:newWakeLock()创建一个PowerManager.WakeLock对象.使用WakeLock对象可以去管理设备电源的状态,使用方法特别简单:如下例子

<span class="typ" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(102, 0, 102);">PowerManager</span><span class="pln" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(0, 0, 0);"> pm </span><span class="pun" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(102, 102, 0);">=</span><span class="pln" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(0, 0, 0);"> </span><span class="pun" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(102, 102, 0);">(</span><span class="typ" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(102, 0, 102);">PowerManager</span><span class="pun" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(102, 102, 0);">)</span><span class="pln" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(0, 0, 0);"> getSystemService</span><span class="pun" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(102, 102, 0);">(</span><span class="typ" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(102, 0, 102);">Context</span><span class="pun" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(102, 102, 0);">.</span><span class="pln" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(0, 0, 0);">POWER_SERVICE</span><span class="pun" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(102, 102, 0);">);</span><span class="pln" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(0, 0, 0);">  </span><span class="typ" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(102, 0, 102);">PowerManager</span><span class="pun" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(102, 102, 0);">.</span><span class="typ" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(102, 0, 102);">WakeLock</span><span class="pln" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(0, 0, 0);"> wl </span><span class="pun" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(102, 102, 0);">=</span><span class="pln" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(0, 0, 0);"> pm</span><span class="pun" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(102, 102, 0);">.</span><span class="pln" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(0, 0, 0);">newWakeLock</span><span class="pun" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(102, 102, 0);">(</span><span class="typ" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(102, 0, 102);">PowerManager</span><span class="pun" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(102, 102, 0);">.</span><span class="pln" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(0, 0, 0);">SCREEN_DIM_WAKE_LOCK</span><span class="pun" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(102, 102, 0);">,</span><span class="pln" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(0, 0, 0);"> </span><span class="str" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(0, 136, 0);">"My Tag"</span><span class="pun" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(102, 102, 0);">);</span><span class="pln" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(0, 0, 0);">  wl</span><span class="pun" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(102, 102, 0);">.</span><span class="pln" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(0, 0, 0);">acquire</span><span class="pun" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(102, 102, 0);">();</span><span class="pln" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(0, 0, 0);">  //在释放之前,屏幕一直亮着(有可能会变暗,但是还可以看到屏幕内容)</span><span class="pln" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(0, 0, 0);">  wl</span><span class="pun" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(102, 102, 0);">.</span><span class="pln" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(0, 0, 0);">release</span><span class="pun" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(102, 102, 0);">();</span><span class="pln" style="padding: 0px; margin: 0px; line-height: 25.200000762939453px; color: rgb(0, 0, 0);">  </span>

下面定义的这些标记不同程度的影响系统电源。这些标记都是独占的,并且每次只能指定其中一个。

Flag Value CPU Screen Keyboard
PARTIAL_WAKE_LOCK On* Off(关闭) Off(关闭)
SCREEN_DIM_WAKE_LOCK On Dim(变暗) Off(关闭)
SCREEN_BRIGHT_WAKE_LOCK On Bright(高亮) Off(关闭)
FULL_WAKE_LOCK On Bright(高亮) Bright(高亮)

如果你使用的是局部唤醒锁的话(使用PARTIAL_WAKE_LOCK标志),CPU会继续运行,将忽略任何的计时器,甚至按下电源按钮。其他的唤醒锁话,CPU也会继续运转,但是使用者仍然可以按电源按钮让设备睡眠。

另外,你可以使用两个以上的标记,但是他只影响屏幕的行为。和PARTIAL_WAKE_LOCK同时使用的话,没有任何影响。

Flag Value Description
ACQUIRE_CAUSES_WAKEUP Normal wake locks don't actually turn on the illumination. Instead, they cause the illumination to remain on once it turns on (e.g. from user activity). This flag will force the screen and/or keyboard to turn on immediately, when the WakeLock is acquired. A typical use would be for notifications which are important for the user to see immediately.正常情况下是不会是屏幕等变亮,相反,当获得wakeLock之后需要一个触发事件才会使屏幕或者键盘变亮。典型应用是一个对用户来说比较重要的通知时,使用这个锁。
ON_AFTER_RELEASE If this flag is set, the user activity timer will be reset when the WakeLock is released, causing the illumination to remain on a bit longer. This can be used to reduce flicker if you are cycling between wake lock conditions.帮忙翻译一下吧
最后啰嗦一句,这个电源管理是activity级别的。


一个小例子

package com.example.powers;import android.os.Bundle;import android.os.PowerManager;import android.os.PowerManager.WakeLock;import android.app.Activity;import android.content.Context;import android.util.Log;import android.view.Menu;import android.view.MenuItem;import android.support.v4.app.NavUtils;public class MainActivity extends Activity {private WakeLock wakeLock;@Overridepublic void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);}@Overrideprotected void onResume() {super.onResume();// 开始获得唤醒锁acquireWakeLock();}@Overridepublic void finish() {super.finish();// 释放锁releaseWakeLock();}private void acquireWakeLock() {if (wakeLock == null) {Log.d("debug", "Acquiring wake lock");PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);wakeLock = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK, this.getClass().getCanonicalName());wakeLock.acquire();}}private void releaseWakeLock() {if (wakeLock != null && wakeLock.isHeld()) {wakeLock.release();wakeLock = null;}}@Overridepublic boolean onCreateOptionsMenu(Menu menu) {getMenuInflater().inflate(R.menu.activity_main, menu);return true;}}


4. android中解析服务器发过来的JSON数据
解析JSON的效率要比xml高很多,建议在开发中,数据不是很复杂就用JSON传输数据
[java] view plain copy
  1. publicclassVideoService{
  2. publicList<Video>getJsonVieos()throwsIOException,JSONException{
  3. Stringpath="http://111.14.19.37:8080/vidoe/video/list.do?format=json";
  4. URLurl=newURL(path);
  5. HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
  6. conn.setConnectTimeout(5*1000);
  7. conn.setRequestMethod("GET");
  8. InputStreamis=conn.getInputStream();
  9. byte[]data=InputStreamUtil.getByteArray(is);//用自己写的工具类把流转成byte数组
  10. Stringjson=newString(data);
  11. JSONArrayarray=newJSONArray(json);
  12. List<Video>videos=newArrayList<Video>();
  13. for(inti=0;i<array.length();i++){
  14. JSONObjectjo=array.getJSONObject(i);
  15. intid=jo.getInt("id");
  16. Stringtitle=jo.getString("title");
  17. inttimelength=jo.getInt("timelength");
  18. videos.add(newVideo(id,title,timelength));
  19. }
  20. returnvideos;
  21. }
  22. }



5.Post方式发送http请求

[java] view plain copy
  1. publicbooleanuploadPostMethod(Stringpath,Map<String,String>params)throwsIOException{
  2. StringBuildersb=newStringBuilder();
  3. for(Map.Entry<String,String>entry:params.entrySet()){
  4. //sb.append(entry.getKey()).append('=').append(entry.getValue()).append('&');
  5. sb.append(entry.getKey()).append('=').append(URLEncoder.encode(entry.getValue(),"UTF-8")).append('&');
  6. }
  7. sb.deleteCharAt(sb.length()-1);
  8. byte[]entitydata=sb.toString().getBytes();
  9. URLurl=newURL(path);
  10. HttpURLConnectionconn=(HttpURLConnection)url.openConnection();
  11. conn.setConnectTimeout(5*1000);
  12. conn.setRequestMethod("POST");
  13. conn.setDoOutput(true);
  14. conn.setRequestProperty("Content-Type","application/x-www-form-urlencoded");
  15. conn.setRequestProperty("Content-Length",String.valueOf(entitydata.length));
  16. OutputStreamos=conn.getOutputStream();
  17. os.write(entitydata);
  18. os.flush();
  19. os.close();
  20. if(conn.getResponseCode()==200){
  21. returntrue;
  22. }
  23. returnfalse;
  24. }





6.android使用http协议实现文件的上传

http协议上传文件一般最大是2M,比较适合上传小于两M的文件

下面是封装的一个文件类:

[java] view plain copy
  1. importjava.io.File;
  2. importjava.io.FileInputStream;
  3. importjava.io.FileNotFoundException;
  4. importjava.io.InputStream;
  5. /**
  6. *上传的文件
  7. */
  8. publicclassFormFile{
  9. /*上传文件的数据*/
  10. privatebyte[]data;
  11. privateInputStreaminStream;
  12. privateFilefile;
  13. /*文件名称*/
  14. privateStringfilname;
  15. /*请求参数名称*/
  16. privateStringparameterName;
  17. /*内容类型*/
  18. privateStringcontentType="application/octet-stream";
  19. /**
  20. *
  21. *@paramfilname文件名称
  22. *@paramdata上传的文件数据
  23. *@paramparameterName参数
  24. *@paramcontentType内容类型
  25. */
  26. publicFormFile(Stringfilname,byte[]data,StringparameterName,StringcontentType){
  27. this.data=data;
  28. this.filname=filname;
  29. this.parameterName=parameterName;
  30. if(contentType!=null)this.contentType=contentType;
  31. }
  32. /**
  33. *
  34. *@paramfilname文件名
  35. *@paramfile上传的文件
  36. *@paramparameterName参数
  37. *@paramcontentType内容内容类型
  38. */
  39. publicFormFile(Stringfilname,Filefile,StringparameterName,StringcontentType){
  40. this.filname=filname;
  41. this.parameterName=parameterName;
  42. this.file=file;
  43. try{
  44. this.inStream=newFileInputStream(file);
  45. }catch(FileNotFoundExceptione){
  46. e.printStackTrace();
  47. }
  48. if(contentType!=null)this.contentType=contentType;
  49. }
  50. publicFilegetFile(){
  51. returnfile;
  52. }
  53. publicInputStreamgetInStream(){
  54. returninStream;
  55. }
  56. publicbyte[]getData(){
  57. returndata;
  58. }
  59. publicStringgetFilname(){
  60. returnfilname;
  61. }
  62. publicvoidsetFilname(Stringfilname){
  63. this.filname=filname;
  64. }
  65. publicStringgetParameterName(){
  66. returnparameterName;
  67. }
  68. publicvoidsetParameterName(StringparameterName){
  69. this.parameterName=parameterName;
  70. }
  71. publicStringgetContentType(){
  72. returncontentType;
  73. }
  74. publicvoidsetContentType(StringcontentType){
  75. this.contentType=contentType;
  76. }
  77. }

下面的方法封装的http协议上传数据:

[java] view plain copy
  1. /**
  2. *直接通过HTTP协议提交数据到服务器,实现如下面表单提交功能:
  3. *<FORMMETHOD=POSTACTION="http://192.168.0.200:8080/ssi/fileload/test.do"enctype="multipart/form-data">
  4. <INPUTTYPE="text"NAME="name">
  5. <INPUTTYPE="text"NAME="id">
  6. <inputtype="file"name="imagefile"/>
  7. <inputtype="file"name="zip"/>
  8. </FORM>
  9. *@parampath上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.xxx.cn或http://192.168.1.10:8080这样的路径测试)
  10. *@paramparams请求参数key为参数名,value为参数值
  11. *@paramfile上传文件
  12. */
  13. publicstaticbooleanpost(Stringpath,Map<String,String>params,FormFile[]files)throwsException{
  14. finalStringBOUNDARY="---------------------------7da2137580612";//数据分隔线
  15. finalStringendline="--"+BOUNDARY+"--\r\n";//数据结束标志
  16. intfileDataLength=0;
  17. for(FormFileuploadFile:files){//得到文件类型数据的总长度
  18. StringBuilderfileExplain=newStringBuilder();
  19. fileExplain.append("--");
  20. fileExplain.append(BOUNDARY);
  21. fileExplain.append("\r\n");
  22. fileExplain.append("Content-Disposition:form-data;name=\""+uploadFile.getParameterName()+"\";filename=\""+uploadFile.getFilname()+"\"\r\n");
  23. fileExplain.append("Content-Type:"+uploadFile.getContentType()+"\r\n\r\n");
  24. fileExplain.append("\r\n");
  25. fileDataLength+=fileExplain.length();
  26. if(uploadFile.getInStream()!=null){
  27. fileDataLength+=uploadFile.getFile().length();
  28. }else{
  29. fileDataLength+=uploadFile.getData().length;
  30. }
  31. }
  32. StringBuildertextEntity=newStringBuilder();
  33. for(Map.Entry<String,String>entry:params.entrySet()){//构造文本类型参数的实体数据
  34. textEntity.append("--");
  35. textEntity.append(BOUNDARY);
  36. textEntity.append("\r\n");
  37. textEntity.append("Content-Disposition:form-data;name=\""+entry.getKey()+"\"\r\n\r\n");
  38. textEntity.append(entry.getValue());
  39. textEntity.append("\r\n");
  40. }
  41. //计算传输给服务器的实体数据总长度
  42. intdataLength=textEntity.toString().getBytes().length+fileDataLength+endline.getBytes().length;
  43. URLurl=newURL(path);
  44. intport=url.getPort()==-1?80:url.getPort();
  45. Socketsocket=newSocket(InetAddress.getByName(url.getHost()),port);
  46. OutputStreamoutStream=socket.getOutputStream();
  47. //下面完成HTTP请求头的发送
  48. Stringrequestmethod="POST"+url.getPath()+"HTTP/1.1\r\n";
  49. outStream.write(requestmethod.getBytes());
  50. Stringaccept="Accept:image/gif,image/jpeg,image/pjpeg,image/pjpeg,application/x-shockwave-flash,application/xaml+xml,application/vnd.ms-xpsdocument,application/x-ms-xbap,application/x-ms-application,application/vnd.ms-excel,application/vnd.ms-powerpoint,application/msword,*/*\r\n";
  51. outStream.write(accept.getBytes());
  52. Stringlanguage="Accept-Language:zh-CN\r\n";
  53. outStream.write(language.getBytes());
  54. Stringcontenttype="Content-Type:multipart/form-data;boundary="+BOUNDARY+"\r\n";
  55. outStream.write(contenttype.getBytes());
  56. Stringcontentlength="Content-Length:"+dataLength+"\r\n";
  57. outStream.write(contentlength.getBytes());
  58. Stringalive="Connection:Keep-Alive\r\n";
  59. outStream.write(alive.getBytes());
  60. Stringhost="Host:"+url.getHost()+":"+port+"\r\n";
  61. outStream.write(host.getBytes());
  62. //写完HTTP请求头后根据HTTP协议再写一个回车换行
  63. outStream.write("\r\n".getBytes());
  64. //把所有文本类型的实体数据发送出来
  65. outStream.write(textEntity.toString().getBytes());
  66. //把所有文件类型的实体数据发送出来
  67. for(FormFileuploadFile:files){
  68. StringBuilderfileEntity=newStringBuilder();
  69. fileEntity.append("--");
  70. fileEntity.append(BOUNDARY);
  71. fileEntity.append("\r\n");
  72. fileEntity.append("Content-Disposition:form-data;name=\""+uploadFile.getParameterName()+"\";filename=\""+uploadFile.getFilname()+"\"\r\n");
  73. fileEntity.append("Content-Type:"+uploadFile.getContentType()+"\r\n\r\n");
  74. outStream.write(fileEntity.toString().getBytes());
  75. if(uploadFile.getInStream()!=null){
  76. byte[]buffer=newbyte[1024];
  77. intlen=0;
  78. while((len=uploadFile.getInStream().read(buffer,0,1024))!=-1){
  79. outStream.write(buffer,0,len);
  80. }
  81. uploadFile.getInStream().close();
  82. }else{
  83. outStream.write(uploadFile.getData(),0,uploadFile.getData().length);
  84. }
  85. outStream.write("\r\n".getBytes());
  86. }
  87. //下面发送数据结束标志,表示数据已经结束
  88. outStream.write(endline.getBytes());
  89. BufferedReaderreader=newBufferedReader(newInputStreamReader(socket.getInputStream()));
  90. if(reader.readLine().indexOf("200")==-1){//读取web服务器返回的数据,判断请求码是否为200,如果不是200,代表请求失败
  91. returnfalse;
  92. }
  93. outStream.flush();
  94. outStream.close();
  95. reader.close();
  96. socket.close();
  97. returntrue;
  98. }
  99. /**
  100. *提交数据到服务器
  101. *@parampath上传路径(注:避免使用localhost或127.0.0.1这样的路径测试,因为它会指向手机模拟器,你可以使用http://www.xxx.cn或http://192.168.1.10:8080这样的路径测试)
  102. *@paramparams请求参数key为参数名,value为参数值
  103. *@paramfile上传文件
  104. */
  105. publicstaticbooleanpost(Stringpath,Map<String,String>params,FormFilefile)throwsException{
  106. returnpost(path,params,newFormFile[]{file});
  107. }



7.android 从internet获取html,图片

在清单文件中加上网络访问权限

<!--访问internet权限-->

<uses-permissionandroid:name="android.permission.INTERNET"/>

利用HttpURLConnection对象,我们可以从网络中获取网页数据.

URL url = newURL("http://www.sohu.com");

HttpURLConnection conn= (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(5*1000);//设置连接超时

conn.setRequestMethod(“GET”);//get方式发起请求

if(conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");

InputStream is =conn.getInputStream();//得到网络返回的输入流

Stringresult =readData(is, "GBK");

conn.disconnect();

//第一个参数为输入流,第二个参数为字符集编码

public static StringreadData(InputStream inSream, String charsetName) throws Exception{

ByteArrayOutputStreamoutStream = new ByteArrayOutputStream();

byte[]buffer = new byte[1024];

intlen = -1;

while((len = inSream.read(buffer)) != -1 ){

outStream.write(buffer,0, len);

}

byte[]data = outStream.toByteArray();

outStream.close();

inSream.close();

returnnew String(data, charsetName);

}

利用HttpURLConnection对象,我们可以从网络中获取文件数据.

URL url = newURL("http://photocdn.sohu.com/20100125/Img269812337.jpg");

HttpURLConnection conn= (HttpURLConnection) url.openConnection();

conn.setConnectTimeout(5*1000);

conn.setRequestMethod("GET");

if(conn.getResponseCode() != 200) throw new RuntimeException("请求url失败");

InputStream is =conn.getInputStream();

readAsFile(is,"Img269812337.jpg");

public static voidreadAsFile(InputStream inSream, File file) throws Exception{

FileOutputStreamoutStream = new FileOutputStream(file);

byte[]buffer = new byte[1024];

intlen = -1;

while((len = inSream.read(buffer)) != -1 ){

outStream.write(buffer,0, len);

}

outStream.close();

inSream.close();

}





8.Android根据Button状态(normal,focused,pressed)显示不同背景图片

Android中Button 有focused, selected, pressed 等不同状态,通过配置一个XML格式的 drawable "selector" 即可实现”在不同状态下显示不同背景图片“的功能。
1. 在res/drawable目录下添加一个xml文件,用来描述Button在不同状态下对应的不同图片。我这里给该xml文件命名为btn_background.xml
<?xml version="1.0" encoding="UTF-8"?>
<selectorxmlns:android="http://schemas.android.com/apk/res/android">
<itemandroid:state_pressed="true"
android:drawable
="@drawable/btn_pressed"
/>
<!--pressed-->
<itemandroid:state_focused="true"
android:drawable
="@drawable/btn_normal"
/>
<!--focused-->
<itemandroid:drawable="@drawable/btn_normal"
/>
<!--default-->
</selector>

2. 在res/layout目录下,对应的layout xml文件中,将Button的android:background属性设置为btn_background即可。


<?xml version="1.0" encoding="utf-8"?>
<LinearLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:orientation
="vertical"
android:layout_width
="fill_parent"
android:layout_height
="fill_parent"
>
<Button
android:layout_width="wrap_content"
android:layout_height
="wrap_content"
android:background
="@drawable/btn_background"
/>
</LinearLayout>


3.运行结果

默认状态(unselected)

点击状态(pressed)

更多相关文章

  1. SpringBoot 2.0 中 HikariCP 数据库连接池原理解析
  2. 一句话锁定MySQL数据占用元凶
  3. Android--Animation动画介绍和实现
  4. Android(安卓)NDK开发(二)——CMake脚本构建项目
  5. Androd studio无线调试及镜像投屏
  6. Android读取XML文件中的数据
  7. 用Android(安卓)Studio在windows下面查看android源码
  8. Android中ImageView使用网络图片资源的方法
  9. Android(安卓)6.0系统读写文件出现FileNotFoundException:EACCES

随机推荐

  1. Android——数据存储(Login)
  2. Android(安卓)Studio 将引用第三方jar包
  3. 完美解决 No IDEA annotations attached
  4. Android窗口机制(三)Window和WindowManager
  5. Android 属性大全
  6. Android中的自绘View的那些事儿(四)之 Comp
  7. Android(安卓)| gravity和layout_gravity
  8. 安卓textview edittext 中inputType的类
  9. Android游戏引擎-Rokon
  10. 如何在Android中获知屏幕打开或者关闭