Android 之6.0 双向通话自动录音

可以先参考下这篇博客,讲得比较详细  http://www.jizhuomi.com/Android/example/354.html

然后我看到这篇博客很叼,其它的文章质量也非常不错,http://blog.csdn.NET/gyhgx/article/details/51669892

项目中需要实现基于Android 6.0 的双向通话自动录音功能,在查阅相关android电话状态监听文章以及Git上的开源录音项目后,整理出此文

实现手机电话状态的监听,主要依靠两个类: 
TelephoneManger和PhoneStateListener 
TelephonseManger提供了取得手机基本服务的信息的一种方式。因此应用程序可以使用TelephonyManager来探测手机基本服务的情况。应用程序可以注册listener来监听电话状态的改变。 
我们不能对TelephonyManager进行实例化,只能通过获取服务的形式:

<code class="hljs mathematica has-numbering" style="display: block; padding: 0px; color: inherit; box-sizing: border-box; font-family: 'Source Code Pro', monospace;font-size:undefined; white-space: pre; border-radius: 0px; word-wrap: normal; background: transparent;"><span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">Context</span>.getSystemService(<span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">Context</span>.TELEPHONY_SERVICE);</code><ul class="pre-numbering" style="box-sizing: border-box; position: absolute; width: 50px; top: 0px; left: 0px; margin: 0px; padding: 6px 0px 40px; border-right-width: 1px; border-right-style: solid; border-right-color: rgb(221, 221, 221); list-style: none; text-align: right; background-color: rgb(238, 238, 238);"><li style="box-sizing: border-box; padding: 0px 5px;">1</li></ul>

注意:对手机的某些信息进行读取是需要一定许可(permission)的。

主要静态成员常量:(它们对应PhoneStateListener.LISTEN_CALL_STATE所监听到的内容)

[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. int CALL_STATE_IDLE   //空闲状态,没有任何活动。  
  2.   
  3. int CALL_STATE_OFFHOOK  //摘机状态,至少有个电话活动。该活动或是拨打(dialing)或是通话,或是 on hold。并且没有电话是ringing or waiting  
  4.   
  5. int CALL_STATE_RINGING  //来电状态,电话铃声响起的那段时间或正在通话又来新电,新来电话不得不等待的那段时间。  

项目中使用服务来监听通话状态,所以需要弄清楚手机通话状态在广播中的对应值:

<code class="hljs javascript has-numbering" style="display: block; padding: 0px; color: inherit; box-sizing: border-box; font-family: 'Source Code Pro', monospace;font-size:undefined; white-space: pre; border-radius: 0px; word-wrap: normal; background: transparent;">EXTRA_STATE_IDLE <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//它在手机通话状态改变的广播中,用于表示CALL_STATE_IDLE状态,即空闲状态。</span> EXTRA_STATE_OFFHOOK <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//它在手机通话状态改变的广播中,用于表示CALL_STATE_OFFHOOK状态,即摘机状态。</span> EXTRA_STATE_RINGING <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//它在手机通话状态改变的广播中,用于表示CALL_STATE_RINGING状态,即来电状态</span> ACTION_PHONE_STATE_CHANGED <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//在广播中用ACTION_PHONE_STATE_CHANGED这个Action来标示通话状态改变的广播(intent)。</span> <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//注:需要许可READ_PHONE_STATE。</span> <span class="hljs-built_in" style="color: rgb(102, 0, 102); box-sizing: border-box;">String</span> EXTRA_INCOMING_NUMBER <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//在手机通话状态改变的广播,用于从extra取来电号码。</span> <span class="hljs-built_in" style="color: rgb(102, 0, 102); box-sizing: border-box;">String</span> EXTRA_STATE <span class="hljs-comment" style="color: rgb(136, 0, 0); box-sizing: border-box;">//在通话状态改变的广播,用于从extra取来通话状态。</span></code>

如何实现电话监听呢? 
Android在电话状态改变是会发送action为android.intent.action.PHONE_STATE的广播,而拨打电话时会发送action为

<code class="hljs java has-numbering" style="display: block; padding: 0px; color: inherit; box-sizing: border-box; font-family: 'Source Code Pro', monospace;font-size:undefined; white-space: pre; border-radius: 0px; word-wrap: normal; background: transparent;"><span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">public</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">static</span> <span class="hljs-keyword" style="color: rgb(0, 0, 136); box-sizing: border-box;">final</span> String ACTION_NEW_OUTGOING_CALL = <span class="hljs-string" style="color: rgb(0, 136, 0); box-sizing: border-box;">"android.intent.action.NEW_OUTGOING_CALL"</span>;</code><ul class="pre-numbering" style="box-sizing: border-box; position: absolute; width: 50px; top: 0px; left: 0px; margin: 0px; padding: 6px 0px 40px; border-right-width: 1px; border-right-style: solid; border-right-color: rgb(221, 221, 221); list-style: none; text-align: right; background-color: rgb(238, 238, 238);"><li style="box-sizing: border-box; padding: 0px 5px;">1</li><li style="box-sizing: border-box; padding: 0px 5px;">2</li></ul>

的广播。通过自定义广播接收器,接受上述两个广播便可。

下面给出Java代码:(其中的Toast均为方便测试而添加)

[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1. package com.example.hgx.phoneinfo60.Recording;  
  2.   
  3. import android.content.BroadcastReceiver;  
  4. import android.content.Context;  
  5. import android.content.Intent;  
  6. import android.telephony.TelephonyManager;  
  7. import android.widget.Toast;  
  8.   
  9. /**  
  10.  * Created by hgx on 2016/6/13.  
  11.  */  
  12. public class PhoneCallReceiver extends BroadcastReceiver {  
  13.     private int lastCallState  = TelephonyManager.CALL_STATE_IDLE;  
  14.     private boolean isIncoming = false;  
  15.     private static String contactNum;  
  16.     Intent audioRecorderService;  
  17.   
  18.   
  19.     public PhoneCallReceiver() {  
  20.     }  
  21.   
  22.     @Override  
  23.     public void onReceive(Context context, Intent intent) {  
  24.         //如果是去电  
  25.         if (intent.getAction().equals(Intent.ACTION_NEW_OUTGOING_CALL)){  
  26.             contactNum = intent.getExtras().getString(Intent.EXTRA_PHONE_NUMBER);  
  27.         }else //android.intent.action.PHONE_STATE.查了下android文档,貌似没有专门用于接收来电的action,所以,非去电即来电.  
  28.         {  
  29.             String state = intent.getExtras().getString(TelephonyManager.EXTRA_STATE);  
  30.             String phoneNumber = intent.getExtras().getString(TelephonyManager.EXTRA_INCOMING_NUMBER);  
  31.   
  32.             int stateChange = 0;  
  33.   
  34.             if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)){  
  35.                 //空闲状态  
  36.                 stateChange =TelephonyManager.CALL_STATE_IDLE;  
  37.                 if (isIncoming){  
  38.                     onIncomingCallEnded(context,phoneNumber);  
  39.                 }else {  
  40.                     onOutgoingCallEnded(context,phoneNumber);  
  41.                 }  
  42.             }else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)){  
  43.                 //摘机状态  
  44.                 stateChange = TelephonyManager.CALL_STATE_OFFHOOK;  
  45.                 if (lastCallState != TelephonyManager.CALL_STATE_RINGING){  
  46.                     //如果最近的状态不是来电响铃的话,意味着本次通话是去电  
  47.                     isIncoming =false;  
  48.                     onOutgoingCallStarted(context,phoneNumber);  
  49.                 }else {  
  50.                     //否则本次通话是来电  
  51.                     isIncoming = true;  
  52.                     onIncomingCallAnswered(context, phoneNumber);  
  53.                 }  
  54.             }else if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)){  
  55.                 //来电响铃状态  
  56.                 stateChange = TelephonyManager.CALL_STATE_RINGING;  
  57.                 lastCallState = stateChange;  
  58.                 onIncomingCallReceived(context,contactNum);  
  59.             }  
  60.   
  61.         }  
  62.   
  63.     }  
  64.   
  65.   
  66.     protected void onIncomingCallStarted(Context context,String number){  
  67.         Toast.makeText(context,"Incoming call is started",Toast.LENGTH_LONG).show();  
  68.         context.startService(new Intent(context,AudioRecorderService.class));  
  69.   
  70.     }  
  71.   
  72.     protected void onOutgoingCallStarted(Context context,String number){  
  73.         Toast.makeText(context, "Outgoing call is started", Toast.LENGTH_LONG).show();  
  74.         context.startService(new Intent(context, AudioRecorderService.class));  
  75.     }  
  76.   
  77.     protected void onIncomingCallEnded(Context context,String number){  
  78.         Toast.makeText(context, "Incoming call is ended", Toast.LENGTH_LONG).show();  
  79.         context.startService(new Intent(context, AudioRecorderService.class));  
  80.     }  
  81.   
  82.     protected void onOutgoingCallEnded(Context context,String number){  
  83.         Toast.makeText(context, "Outgoing call is ended", Toast.LENGTH_LONG).show();  
  84.         context.startService(new Intent(context, AudioRecorderService.class));  
  85.     }  
  86.   
  87.     protected void onIncomingCallReceived(Context context,String number){  
  88.         Toast.makeText(context, "Incoming call is received", Toast.LENGTH_LONG).show();  
  89.     }  
  90.     protected void onIncomingCallAnswered(Context context, String number) {  
  91.         Toast.makeText(context, "Incoming call is answered", Toast.LENGTH_LONG).show();  
  92.     }  
  93. }  
下面是AudioRecorderService的java实现:

[html]  view plain  copy
 print ? 在CODE上查看代码片 派生到我的代码片
  1.  package com.example.hgx.phoneinfo60.Recording;  
  2. import android.app.Service;  
  3. import android.content.Intent;  
  4. import android.media.AudioFormat;  
  5. import android.media.AudioRecord;  
  6. import android.media.MediaRecorder;  
  7. import android.os.AsyncTask;  
  8. import android.os.Environment;  
  9. import android.os.IBinder;  
  10. import android.provider.MediaStore;  
  11. import android.util.Log;  
  12. import android.widget.Toast;  
  13.   
  14. import com.example.hgx.phoneinfo60.MyApplication;  
  15.   
  16. import java.io.DataOutputStream;  
  17. import java.io.File;  
  18. import java.io.FileInputStream;  
  19. import java.io.FileNotFoundException;  
  20. import java.io.FileOutputStream;  
  21. import java.io.IOException;  
  22. import java.net.HttpURLConnection;  
  23. import java.net.URL;  
  24. /**  
  25.  * Created by hgx on 2016/6/13.  
  26.  */  
  27.   
  28. public class AudioRecorderService extends Service {  
  29.     private static int RECORD_RATE = 0;  
  30.     private static int RECORD_BPP = 32;  
  31.     private static int RECORD_CHANNEL = AudioFormat.CHANNEL_IN_MONO;  
  32.     private static int RECORD_ENCODER = AudioFormat.ENCODING_PCM_16BIT;  
  33.     private AudioRecord audioRecorder = null;  
  34.     private Thread recordT = null;  
  35.     private Boolean isRecording = false;  
  36.     private int bufferEle = 1024bytesPerEle = 2;// want to play 2048 (2K) since 2 bytes we use only 1024 2 bytes in 16bit format  
  37.     private static int[] recordRate ={44100 , 22050 , 11025 , 8000};  
  38.     int bufferSize = 0;  
  39.     File uploadFile;  
  40.   
  41.   
  42.   
  43.     @Override  
  44.     public IBinder onBind(Intent intent) {  
  45.         // TODO: Return the communication channel to the service.  
  46.         //maintain the relationship between the caller activity and the callee service, currently useless here  
  47.        return null;  
  48.     }  
  49.   
  50.     @Override  
  51.     public void onDestroy() {  
  52.         if (isRecording){  
  53.             stopRecord();  
  54.         }else{  
  55.             Toast.makeText(MyApplication.getContext(), "Recording is already stopped",Toast.LENGTH_SHORT).show();  
  56.         }  
  57.         super.onDestroy();  
  58.     }  
  59.   
  60.     @Override  
  61.     public int onStartCommand(Intent intent, int flags, int startId) {  
  62.         if (!isRecording){  
  63.             startRecord();  
  64.         }else {  
  65.             Toast.makeText(MyApplication.getContext(), "Recording is already started",Toast.LENGTH_SHORT).show();  
  66.         }  
  67.         return 1;  
  68.     }  
  69.   
  70.     private void startRecord(){  
  71.         audioRecorder = initializeRecord();  
  72.         if (audioRecorder != null){  
  73.             Toast.makeText(MyApplication.getContext(), "Recording is  started",Toast.LENGTH_SHORT).show();  
  74.             audioRecorder.startRecording();  
  75.         }else  
  76.             return;  
  77.   
  78.         isRecording = true;  
  79.         recordT = new Thread(new Runnable() {  
  80.             @Override  
  81.             public void run() {  
  82.                 writeToFile();  
  83.             }  
  84.         },"Recording Thread");  
  85.         recordT.start();  
  86.   
  87.     }  
  88.   
  89.     private void writeToFile(){  
  90.         byte bDate[] = new byte[bufferEle];  
  91.         FileOutputStream fos =null;  
  92.         File recordFile = createTempFile();  
  93.         try {  
  94.             fos = new FileOutputStream(recordFile);  
  95.         } catch (FileNotFoundException e) {  
  96.             e.printStackTrace();  
  97.         }  
  98.   
  99.         while (isRecording){  
  100.             audioRecorder.read(bDate,0,bufferEle);  
  101.         }  
  102.   
  103.         try {  
  104.             fos.write(bDate);  
  105.         } catch (IOException e) {  
  106.             e.printStackTrace();  
  107.         }  
  108.   
  109.         try {  
  110.             fos.close();  
  111.         } catch (IOException e) {  
  112.             e.printStackTrace();  
  113.         }  
  114.     }  
  115.   
  116.     //Following function converts short data to byte data  
  117.     private byte[] writeShortToByte(short[] sData) {  
  118.         int size = sData.length;  
  119.         byte[] byteArrayData = new byte[size * 2];  
  120.         for (int i = 0; i < size; i++) {  
  121.             byteArrayData[i * 2] = (byte) (sData[i] & 0x00FF);  
  122.             byteArrayData[(i * 2) + 1] = (byte) (sData[i] >> 8);  
  123.             sData[i] = 0;  
  124.         }  
  125.   
  126.         return byteArrayData;  
  127.     }  
  128.   
  129.     //Creates temporary .raw file for recording  
  130.     private File createTempFile() {  
  131.         File tempFile = new File(Environment.getExternalStorageDirectory(), "aditi.raw");  
  132.         return tempFile;  
  133.     }  
  134.   
  135.     //Create file to convert to .wav format  
  136.     private File createWavFile() {  
  137.         File wavFile = new File(Environment.getExternalStorageDirectory(), "aditi_" + System.currentTimeMillis() + ".wav");  
  138.         return wavFile;  
  139.     }  
  140.   
  141.     /*  
  142.      *  Convert raw to wav file  
  143.      *  @param java.io.File temporay raw file  
  144.      *  @param java.io.File destination wav file  
  145.      *  @return void  
  146.      *  
  147.      * */  
  148.     private void convertRawToWavFile(File tempFile, File wavFile) {  
  149.         FileInputStream fin = null;  
  150.         FileOutputStream fos = null;  
  151.         long audioLength = 0;  
  152.         long dataLength = audioLength + 36;  
  153.         long sampleRate = RECORD_RATE;  
  154.         int channel = 1;  
  155.         long byteRate = RECORD_BPP * RECORD_RATE * channel / 8;  
  156.         String fileName = null;  
  157.   
  158.         byte[] data = new byte[bufferSize];  
  159.         try {  
  160.             fin = new FileInputStream(tempFile);  
  161.             fos = new FileOutputStream(wavFile);  
  162.             audioLength = fin.getChannel().size();  
  163.             dataLength = audioLength + 36;  
  164.             createWaveFileHeader(fos, audioLength, dataLength, sampleRate, channel, byteRate);  
  165.   
  166.             while (fin.read(data) != -1) {  
  167.                 fos.write(data);  
  168.             }  
  169.   
  170.             uploadFile = wavFile.getAbsoluteFile();  
  171.         } catch (FileNotFoundException e) {  
  172.             //Log.e("MainActivity:convertRawToWavFile",e.getMessage());  
  173.         } catch (IOException e) {  
  174.             //Log.e("MainActivity:convertRawToWavFile",e.getMessage());  
  175.         } catch (Exception e) {  
  176.             //Log.e("MainActivity:convertRawToWavFile",e.getMessage());  
  177.         }  
  178.     }  
  179.   
  180.     /*  
  181.    * To create wav file need to create header for the same  
  182.    *  
  183.    * @param java.io.FileOutputStream  
  184.    * @param long  
  185.    * @param long  
  186.    * @param long  
  187.    * @param int  
  188.    * @param long  
  189.    * @return void  
  190.    */  
  191.     private void createWaveFileHeader(FileOutputStream fos, long audioLength, long dataLength, long sampleRate, int channel, long byteRate) {  
  192.   
  193.         byte[] header = new byte[44];  
  194.   
  195.         header[0] = 'R'; // RIFF/WAVE header  
  196.         header[1] = 'I';  
  197.         header[2] = 'F';  
  198.         header[3] = 'F';  
  199.         header[4] = (byte) (dataLength & 0xff);  
  200.         header[5] = (byte) ((dataLength >> 8) & 0xff);  
  201.         header[6] = (byte) ((dataLength >> 16) & 0xff);  
  202.         header[7] = (byte) ((dataLength >> 24) & 0xff);  
  203.         header[8] = 'W';  
  204.         header[9] = 'A';  
  205.         header[10] = 'V';  
  206.         header[11] = 'E';  
  207.         header[12] = 'f'; // 'fmt ' chunk  
  208.         header[13] = 'm';  
  209.         header[14] = 't';  
  210.         header[15] = ' ';  
  211.         header[16] = 16; // 4 bytes: size of 'fmt ' chunk  
  212.         header[17] = 0;  
  213.         header[18] = 0;  
  214.         header[19] = 0;  
  215.         header[20] = 1; // format = 1  
  216.         header[21] = 0;  
  217.         header[22] = (byte) channel;  
  218.         header[23] = 0;  
  219.         header[24] = (byte) (sampleRate & 0xff);  
  220.         header[25] = (byte) ((sampleRate >> 8) & 0xff);  
  221.         header[26] = (byte) ((sampleRate >> 16) & 0xff);  
  222.         header[27] = (byte) ((sampleRate >> 24) & 0xff);  
  223.         header[28] = (byte) (byteRate & 0xff);  
  224.         header[29] = (byte) ((byteRate >> 8) & 0xff);  
  225.         header[30] = (byte) ((byteRate >> 16) & 0xff);  
  226.         header[31] = (byte) ((byteRate >> 24) & 0xff);  
  227.         header[32] = (byte) (2 * 16 / 8); // block align  
  228.         header[33] = 0;  
  229.         header[34] = 16; // bits per sample  
  230.         header[35] = 0;  
  231.         header[36] = 'd';  
  232.         header[37] = 'a';  
  233.         header[38] = 't';  
  234.         header[39] = 'a';  
  235.         header[40] = (byte) (audioLength & 0xff);  
  236.         header[41] = (byte) ((audioLength >> 8) & 0xff);  
  237.         header[42] = (byte) ((audioLength >> 16) & 0xff);  
  238.         header[43] = (byte) ((audioLength >> 24) & 0xff);  
  239.   
  240.         try {  
  241.             fos.write(header, 0, 44);  
  242.         } catch (IOException e) {  
  243.             // TODO Auto-generated catch block  
  244.             //Log.e("MainActivity:createWavFileHeader()",e.getMessage());  
  245.         }  
  246.   
  247.     }  
  248.   
  249.     /*  
  250.     * delete created temperory file  
  251.     * @param  
  252.     * @return void  
  253.     */  
  254.     private void deletTempFile() {  
  255.         File file = createTempFile();  
  256.         file.delete();  
  257.     }  
  258.   
  259.     /*  
  260.      * Initialize audio record  
  261.      *  
  262.      * @param  
  263.      * @return android.media.AudioRecord  
  264.      */  
  265.     private AudioRecord initializeRecord() {  
  266.         short[] audioFormat = new short[]{AudioFormat.ENCODING_PCM_16BIT, AudioFormat.ENCODING_PCM_8BIT};  
  267.         short[] channelConfiguration = new short[]{AudioFormat.CHANNEL_IN_MONO, AudioFormat.CHANNEL_IN_STEREO};  
  268.         for (int rate : recordRate) {  
  269.             for (short aFormat : audioFormat) {  
  270.                 for (short cConf : channelConfiguration) {  
  271.                     //Log.d("MainActivity:initializeRecord()","Rate"+rate+"AudioFormat"+aFormat+"Channel Configuration"+cConf);  
  272.                     try {  
  273.                         int buffSize = AudioRecord.getMinBufferSize(rate, cConf, aFormat);  
  274.                         bufferSize = buffSize;  
  275.   
  276.                         if (buffSize != AudioRecord.ERROR_BAD_VALUE) {  
  277.                             AudioRecord aRecorder = new AudioRecord(MediaRecorder.AudioSource.DEFAULT, rate, cConf, aFormat, buffSize);  
  278.   
  279.                             if (aRecorder.getState() == AudioRecord.STATE_INITIALIZED) {  
  280.                                 RECORD_RATE = rate;  
  281.                                 //Log.d("MainActivity:InitializeRecord - AudioFormat",String.valueOf(aFormat));  
  282.                                 //Log.d("MainActivity:InitializeRecord - Channel",String.valueOf(cConf));  
  283.                                 //Log.d("MainActivity:InitialoizeRecord - rceordRate", String.valueOf(rate));  
  284.                                 return aRecorder;  
  285.                             }  
  286.                         }  
  287.                     } catch (Exception e) {  
  288.                         //Log.e("MainActivity:initializeRecord()",e.getMessage());  
  289.                     }  
  290.                 }  
  291.             }  
  292.         }  
  293.         return null;  
  294.     }  
  295.   
  296.     /*  
  297.     * Method to stop and release audio record  
  298.     *  
  299.     * @param  
  300.     * @return void  
  301.     */  
  302.     private void stopRecord() {  
  303.         if (null != audioRecorder) {  
  304.             isRecording = false;  
  305.             audioRecorder.stop();  
  306.             audioRecorder.release();  
  307.             audioRecorder = null;  
  308.             recordT = null;  
  309.             Toast.makeText(getApplicationContext(), "Recording is stopped", Toast.LENGTH_LONG).show();  
  310.         }  
  311.         convertRawToWavFile(createTempFile(), createWavFile());  
  312.         if (uploadFile.exists()) {  
  313.             //Log.d("AudioRecorderService:stopRecord()", "UploadFile exists");  
  314.         }  
  315.         new UploadFile().execute(uploadFile);  
  316.         deletTempFile();  
  317.     }  
  318.   
  319.     /*  
  320.      * Asynchronous task to upload audio file in background  
  321.      *  
  322.      *  
  323.      */  
  324.     private class UploadFile extends AsyncTask<File, Void, Void> {  
  325.         protected Void doInBackground(File... files) {  
  326.   
  327.             if (files[0] == null)  
  328.                 return null;  
  329.             try {  
  330.                 File fileToUpload = files[0];  
  331.                 String boundary = "*****";  
  332.                 String lineEnd = "\r\n";  
  333.                 String twoHyphens = "--";  
  334.                 int maxBufferSize = 1 * 1024 * 1024;  
  335.                 String fileName = fileToUpload.getAbsolutePath();  
  336.                 FileInputStream fis = new FileInputStream(new File(fileName));  
  337.                 URL serverUrl = new URL("http://192.168.78.128/UploadToServer.php");  
  338.                 HttpURLConnection connection = (HttpURLConnection) serverUrl.openConnection();  
  339.                 connection.setDoInput(true);  
  340.                 connection.setDoOutput(true);  
  341.                 connection.setUseCaches(false);  
  342.                 connection.setRequestMethod("POST");  
  343.                 connection.setRequestProperty("Connection", "Keep-Alive");  
  344.                 connection.setRequestProperty("ENCTYPE", "multipart/form-data");  
  345.                 connection.setRequestProperty("Content-Type", "multipart/form-data;boundary=" + boundary);  
  346.                 connection.setRequestProperty("uploaded_file", fileName);  
  347.                 DataOutputStream dos = new DataOutputStream(connection.getOutputStream());  
  348.   
  349.                 dos.writeBytes(twoHyphens + boundary + lineEnd);  
  350.                 dos.writeBytes("Content-Disposition: form-data; name=\"uploadedfile\";filename=\"" + fileName + "\"" + lineEnd);  
  351.                 dos.writeBytes(lineEnd);  
  352.   
  353.                 // create a buffer of  maximum size  
  354.                 int bytesAvailable = fis.available();  
  355.                 int bufferSize = Math.min(bytesAvailable, maxBufferSize);  
  356.                 byte[] buffer = new byte[bufferSize];  
  357.   
  358.                 // read file and write it into form...  
  359.                 int bytesRead = fis.read(buffer, 0, bufferSize);  
  360.   
  361.   
  362.                 while (bytesRead > 0) {  
  363.   
  364.                     dos.write(buffer, 0, bufferSize);  
  365.                     bytesAvailable = fis.available();  
  366.                     bufferSize = Math.min(bytesAvailable, maxBufferSize);  
  367.                     bytesRead = fis.read(buffer, 0, bufferSize);  
  368.   
  369.                 }  
  370.   
  371.                 dos.writeBytes(lineEnd);  
  372.                 dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd);  
  373.                 // Responses from the server (code and message)  
  374.                 int serverResponseCode = connection.getResponseCode();  
  375.                 String serverResponseMessage = connection.getResponseMessage();  
  376.   
  377.                 // /Log.d("AudioRecorderService:AsyncTask",String.valueOf(serverResponseCode));  
  378.                 // /Log.d("AudioRecorderService:AsyncTask",serverResponseMessage);  
  379.   
  380.                 if (serverResponseCode == 200) {  
  381.   
  382.                     Toast.makeText(getApplicationContext(), "File is uploaded successfully", Toast.LENGTH_SHORT).show();  
  383.   
  384.                 }  
  385.   
  386.                 //close the streams //  
  387.                 fis.close();  
  388.                 dos.flush();  
  389.                 dos.close();  
  390.   
  391.   
  392.             } catch (Exception e) {  
  393.                 Log.e("AudioRecorder:Asynctask", e.getMessage());  
  394.             }  
  395.   
  396.   
  397.             return null;  
  398.   
  399.         }  
  400.     }  
  401. }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值