Java 在安卓系统中,当点击服务器并等待响应时,如何放置一个线程安全的进度条?
我有一个在活动中录制音频的应用程序。用户有一个开始录制和停止录制按钮来执行此操作。一旦用户单击停止录制按钮,它会将录制的mp3文件发送到服务器(编码字符串),服务器对其进行处理,并收到响应。我想执行以下任务:Java 在安卓系统中,当点击服务器并等待响应时,如何放置一个线程安全的进度条?,java,android,android-asynctask,thread-safety,background-process,Java,Android,Android Asynctask,Thread Safety,Background Process,我有一个在活动中录制音频的应用程序。用户有一个开始录制和停止录制按钮来执行此操作。一旦用户单击停止录制按钮,它会将录制的mp3文件发送到服务器(编码字符串),服务器对其进行处理,并收到响应。我想执行以下任务: 因为这个过程很长,所以我想在一个单独的线程中完成(最好) 发送和接收响应的过程将使用进度条显示 用户应能够在等待时导航到其他屏幕(即当前活动可能被销毁) 我尝试在向服务器发送mp3的功能前后使用Toast消息。但是没有同步,有时候msg来得早,有时候它来得晚。这就是为什么需要一个适当的进度
import android.content.Context;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.media.MediaPlayer;
import android.media.MediaRecorder;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.provider.MediaStore;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.util.Base64;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
public class RecordActivity extends AppCompatActivity {
private static final String LOG_TAG = "AudioRecordTest";
private static String msg = "default";
public final static String Result_MESSAGE = "in.innovatehub.ankita_mehta.tinyears.ResultMESSAGE";
private static final int REQUESTCODE_RECORDING = 109201;
private Button mRecorderApp = null;
private static String mFileName = "music.mp3";
private static String mFilePath = String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS + "/TinyEars/"));
private MediaRecorder mRecorder = null;
private MediaPlayer mPlayer = null;
private ImageButton mRecordImageButton = null;
private ImageButton mPlayImageButton = null;
boolean mStartRecording = true;
boolean mStartPlaying = true;
private Button mShowStatsButton = null;
private static final String TAG = "RecordActivity";
private Handler handler = new Handler();
final Runnable updater = new Runnable() {
public void run() {
handler.postDelayed(this, 1);
if(mRecorder!=null) {
int maxAmplitude = mRecorder.getMaxAmplitude();
if (maxAmplitude != 0) {
// visualizerView.addAmplitude(maxAmplitude);
}
}
else{
}
}
};
private void onRecord(boolean start) {
if (start) {
startRecording();
} else {
stopRecording();
}
}
private void onPlay(boolean start) {
if (start) {
startPlaying();
} else {
stopPlaying();
}
}
private void startPlaying() {
mPlayer = new MediaPlayer();
try {
mPlayer.setDataSource(mFilePath+"/"+mFileName);
mPlayer.prepare();
mPlayer.start();
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
public void onCompletion(MediaPlayer mp) {
Log.i("Completion Listener", "Song Complete");
stopPlaying();
mRecordImageButton.setEnabled(true);
}
});
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
}
private void stopPlaying() {
if (mPlayer != null) {
mPlayer.reset();
mPlayer.release();
mPlayer = null;
mPlayImageButton.setImageResource(R.drawable.playicon);
// mStartPlaying = true;
} else {
mPlayImageButton.setImageResource(R.drawable.pauseicon);
// mStartPlaying = false;
}
}
private void startRecording() {
AudioRecordTest(String.valueOf(System.currentTimeMillis()));
mRecorder = new MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mRecorder.setOutputFile(mFilePath+"/"+mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
try {
mRecorder.prepare();
} catch (IOException e) {
Log.e(LOG_TAG, "prepare() failed");
}
try {
mRecorder.start();
Toast.makeText(getApplicationContext(), "Recording started", Toast.LENGTH_LONG).show();
} catch (Exception e) {
Log.e(LOG_TAG, "start() failed");
}
}
private void stopRecording() {
if (mRecorder != null) {
mRecorder.stop();
mRecorder.release();
Toast.makeText(getApplicationContext(), "Audio recorded successfully",Toast.LENGTH_LONG).show();
mRecorder = null;
mRecordImageButton.setImageResource(R.drawable.micicon);
// mStartRecording = true;
} else {
mRecordImageButton.setImageResource(R.drawable.stopicon);
// mStartRecording = false;
}
}
public void AudioRecordTest(String text) {
boolean exists = (new File(mFilePath+"/"+mFileName)).exists();
if (!exists) {
new File(mFileName).mkdirs();
}
// mFileName += "audiorecordtest.mp3";
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_record);
Log.d(TAG,"HERE IS FILE PATH"+mFilePath+"/"+mFileName);
mRecordImageButton = (ImageButton) findViewById(R.id.imageButton2);
mPlayImageButton = (ImageButton) findViewById(R.id.imageButton3);
mShowStatsButton = (Button) findViewById(R.id.showMeStats);
mRecorderApp = (Button) findViewById(R.id.recorderApp);
AudioRecordTest("00000");
mRecordImageButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
onRecord(mStartRecording);
if (mStartRecording) {
mRecordImageButton.setImageResource(R.drawable.stopicon);
mPlayImageButton.setEnabled(false);
//setText("Stop recording");
} else {
mRecordImageButton.setImageResource(R.drawable.micicon);
mPlayImageButton.setEnabled(true);
mShowStatsButton.setEnabled(true);
mShowStatsButton.setVisibility(View.VISIBLE);
Toast.makeText(getApplicationContext(),"Hold on... we are getting the results!",Toast.LENGTH_SHORT).show();
pressedSavBtn();
Toast.makeText(getApplicationContext(),"Parsing done ... now you may see the results!",Toast.LENGTH_SHORT).show();
//setText("Start recording");
}
mStartRecording = !mStartRecording;
}
});
mPlayImageButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
onPlay(mStartPlaying);
if (mStartPlaying) {
mPlayImageButton.setImageResource(R.drawable.pauseicon);
mRecordImageButton.setEnabled(false);
mShowStatsButton.setEnabled(false);
//setText("Stop playing");
} else {
mPlayImageButton.setImageResource(R.drawable.playicon);
mRecordImageButton.setEnabled(true);
mShowStatsButton.setEnabled(false);
//setText("Start playing");
}
mStartPlaying = !mStartPlaying;
}
});
//Calling recorder ...
mRecorderApp.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
Intent intent = new Intent(MediaStore.Audio.Media.RECORD_SOUND_ACTION);
if (isAvailable(getApplicationContext(), intent)) {
startActivityForResult(intent, REQUESTCODE_RECORDING);
}
}
});
mShowStatsButton = (Button) findViewById(R.id.showMeStats);
mShowStatsButton.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
sendResults(msg);
}
});
}
public void pressedSavBtn(){
try {
thread.start();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
mShowStatsButton.setVisibility(View.VISIBLE);
}
}
public void writeToFile(String data)
{
// Get the directory for the user's public pictures directory.
final File path = new File(mFilePath+"/");
// Make sure the path directory exists.
if(!path.exists())
{
// Make it, if it doesn't exit
path.mkdirs();
}
final File file = new File(path, "config.txt");
// Save your stream, don't forget to flush() it before closing it.
try
{
file.createNewFile();
FileOutputStream fOut = new FileOutputStream(file);
OutputStreamWriter myOutWriter = new OutputStreamWriter(fOut);
myOutWriter.append(data);
myOutWriter.close();
fOut.flush();
fOut.close();
}
catch (IOException e)
{
Log.e("Exception", "File write failed: " + e.toString());
}
}
private static String convertStreamToString(InputStream is) {
BufferedReader reader = new BufferedReader(new InputStreamReader(is));
StringBuilder sb = new StringBuilder();
String line = null;
try {
while ((line = reader.readLine()) != null) {
sb.append((line + "\n"));
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
return sb.toString();
}
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
try {
//THIS IS FILE ENCODING CODE
File file = new File(mFilePath+"/"+mFileName);
byte[] bytes = FileUtils.readFileToByteArray(file);
String encoded = Base64.encodeToString(bytes, 0);
Log.d("~~~~~~~~ Encoded: ", encoded);
writeToFile(encoded);
//THIS IS URL CONN CODE
String link = "http://192.168.50.0:9000/divide_result";
URL url = new URL(link);
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost(link);
try {
// Add your data
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(2);
nameValuePairs.add(new BasicNameValuePair("Name", "StackOverFlow"));
nameValuePairs.add(new BasicNameValuePair("Date", encoded));
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
// Execute HTTP Post Request
HttpResponse response = httpclient.execute(httppost);
String sb = convertStreamToString(response.getEntity().getContent());
Log.d(TAG,"MESSAGE NOW"+sb);
Log.d(TAG, sb);
msg = sb.toString();
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
} catch (Exception e) {
e.printStackTrace();
}
}
});
public void sendResults(String res){
Log.d(TAG, "Inside on create, Navigating to Result Screen Activity!");
Intent intent = new Intent(getApplicationContext(), ResultsScreenActivity.class);
intent.putExtra(Result_MESSAGE, res);
startActivity(intent);
}
public static boolean isAvailable(Context ctx, Intent intent) {
final PackageManager mgr = ctx.getPackageManager();
List<ResolveInfo> list = mgr.queryIntentActivities(intent,PackageManager.MATCH_DEFAULT_ONLY);
return list.size() > 0;
}
protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
if (requestCode == REQUESTCODE_RECORDING) {
if (resultCode == RESULT_OK) {
Uri audioUri = intent.getData();
// make use of this MediaStore uri
// e.g. store it somewhere
}
else {
// react meaningful to problems
}
}
else {
super.onActivityResult(requestCode,
resultCode, intent);
}
}
@Override
public void onPause() {
super.onPause();
if (mRecorder != null) {
mRecorder.release();
mRecorder = null;
}
if (mPlayer != null) {
mPlayer.release();
mPlayer = null;
}
thread.stop();
}
@Override
protected void onDestroy() {
super.onDestroy();
handler.removeCallbacks(updater);
if(mRecorder!=null) {
mRecorder.stop();
mRecorder.reset();
mRecorder.release();
}
}
@Override
public void onWindowFocusChanged(boolean hasFocus) {
super.onWindowFocusChanged(hasFocus);
handler.post(updater);
}
}
导入android.content.Context;
导入android.content.Intent;
导入android.content.pm.PackageManager;
导入android.content.pm.ResolveInfo;
导入android.media.MediaPlayer;
导入android.media.MediaRecorder;
导入android.net.Uri;
导入android.os.Environment;
导入android.os.Handler;
导入android.provider.MediaStore;
导入android.support.v7.app.AppActivity;
导入android.os.Bundle;
导入android.util.Base64;
导入android.util.Log;
导入android.view.view;
导入android.widget.Button;
导入android.widget.ImageButton;
导入android.widget.LinearLayout;
导入android.widget.ProgressBar;
导入android.widget.TextView;
导入android.widget.Toast;
导入org.apache.commons.io.FileUtils;
导入org.apache.http.HttpResponse;
导入org.apache.http.NameValuePair;
导入org.apache.http.client.ClientProtocolException;
导入org.apache.http.client.HttpClient;
导入org.apache.http.client.entity.UrlEncodedFormEntity;
导入org.apache.http.client.methods.HttpPost;
导入org.apache.http.impl.client.DefaultHttpClient;
导入org.apache.http.message.BasicNameValuePair;
导入java.io.BufferedReader;
导入java.io.File;
导入java.io.FileOutputStream;
导入java.io.IOException;
导入java.io.InputStream;
导入java.io.InputStreamReader;
导入java.io.OutputStreamWriter;
导入java.net.URL;
导入java.util.ArrayList;
导入java.util.List;
公共类RecordActivity扩展了AppCompatActivity{
私有静态最终字符串日志\u TAG=“AudioRecordTest”;
私有静态字符串msg=“default”;
公共最终静态字符串Result\u MESSAGE=“in.innovatehub.ankita\u mehta.tinyears.ResultMESSAGE”;
私有静态最终int请求代码_记录=109201;
私有按钮mRecorderApp=null;
私有静态字符串mFileName=“music.mp3”;
私有静态字符串mFilePath=String.valueOf(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS+“/TinyEars/”);
专用媒体记录器mRecorder=null;
私有媒体播放器mPlayer=null;
private ImageButton mRecordImageButton=null;
私有ImageButton mPlayImageButton=null;
布尔值mStartRecording=true;
布尔值mStartPlaying=true;
私有按钮mShowStatsButton=null;
私有静态最终字符串TAG=“RecordActivity”;
私有处理程序=新处理程序();
final Runnable updater=new Runnable(){
公开募捐{
handler.postdayed(这个,1);
if(mRecorder!=null){
int maxampliance=mRecorder.getmaxampliance();
如果(最大振幅!=0){
//可视化视图添加振幅(最大振幅);
}
}
否则{
}
}
};
私有void onRecord(布尔开始){
如果(启动){
startRecording();
}否则{
停止录制();
}
}
专用void onPlay(布尔启动){
如果(启动){
开始播放();
}否则{
停止铺设();
}
}
专用void startPlaying(){
mPlayer=新媒体播放器();
试一试{
mPlayer.setDataSource(mFilePath+“/”+mFileName);
mPlayer.prepare();
mPlayer.start();
mPlayer.setOnCompletionListener(新的MediaPlayer.OnCompletionListener(){
完成时的公共作废(MediaPlayer mp){
Log.i(“完成监听器”、“歌曲完成”);
停止铺设();
mRecordImageButton.setEnabled(真);
}
});
}捕获(IOE异常){
Log.e(Log_标记,“prepare()失败”);
}
}
私人住宅{
if(mPlayer!=null){
mPlayer.reset();
mPlayer.release();
mPlayer=null;
mplaymagebutton.setImageResource(R.drawable.playcon);
//mStartPlaying=true;
}否则{
mplaymagebutton.setImageResource(R.drawable.pauseicon);
//mStartPlaying=false;
}
}
私有无效开始记录(){
AudioRecordTest(String.valueOf(System.currentTimeMillis());
mRecorder=新的MediaRecorder();
mRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
mRecorder.setOutputFormat(MediaRecorder.OutputFormat.MPEG_4);
mRecorder.setOutputFile(mFilePath+“/”+mFileName);
mRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AAC);
试一试{
mRecorder.prepare();
}捕获(IOE异常){
Log.e(Log_标记,“prepare()失败”);
}
试一试{
mRecorder.start();
Toast.makeText(getApplicationContext(),“录制已开始”,Toast.LENGTH_LONG.show();
}捕获(例外e){
Log.e(Log_标记,“start()失败”);
}
}
私有void stopRecording(){
if(mRecorder!=null){
mRecorder.stop();
mRecorder.release();
Toast.makeText(getApplicationContext(),“音频录制成功”,Toast.LENGTH_LONG.show();
mRecorder=null;
mRecordImageButton.setImageResource(R.drawable.micicon);
//mStartRecording=true;
}否则{
mRecordImageButton.setImageResource(R.drawable.stopicon);
//mStartRecording=false;
}
}
公共无效录音测试(字符串文本){
布尔存在=(新文件(mFilePath+“/”+mFileName)).exists();
如果(!存在){
新文件(mFileName).mkdirs();
}
//mFileName+=“audiorecordtest.mp3”;
}
@凌驾
创建时的公共void(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_记录);
Log.d(标记“我在这里
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/activity_record"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center|center_horizontal"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
android:screenOrientation="portrait"
android:orientation="vertical"
tools:context="in.innovatehub.mobile.ankita_mehta.tinyears.RecordActivity">
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/linearLayout_record"
android:orientation="vertical"
android:gravity="center">
<ImageButton
android:id="@+id/imageButton2"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:scaleType="fitXY"
android:src="@drawable/micicon" />
<ImageButton
android:id="@+id/imageButton3"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_gravity="center"
android:scaleType="fitXY"
android:src="@drawable/playicon" />
<Button
android:id="@+id/showMeStats"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center"
android:visibility="gone"
android:onClick="loadStats"
android:text="@string/showMeStats" />
<Button
android:id="@+id/recorderApp"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="invisible"
android:gravity="center"
android:text="@string/UseRecorderApp" />
</LinearLayout>
<LinearLayout
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/loadStatsLinearLayout"
android:gravity="center"
android:visibility="gone"
android:orientation="vertical">
<TextView
android:id="@+id/loadingMessage"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="@string/loadingMessage"
/>
<ProgressBar
android:id="@+id/downloadProgress"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:indeterminate="true"
/>
</LinearLayout>
</LinearLayout>
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal"
android:background="@color/color_white"
android:padding="5dp" >
<ProgressBar
android:id="@+id/layCustomContentProgress"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginRight="10dp" />
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<TextView
android:id="@+id/layCustomProgressHeading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Medium Text"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="@+id/layCustomProgressInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Small Text"
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>
</LinearLayout>
public Dialog getCustomPogressDialog(Context context, String heading, String text) {
// Declare the customer dialog
Dialog dlgProgress = new Dialog(context);
// Set no title for the dialog
dlgProgress.requestWindowFeature(Window.FEATURE_NO_TITLE);
// Set the content view to the customer_alert layout
dlgProgress.setContentView(R.layout.layout_custom_process_progress);
// Cancel the dialog when touched outside.
dlgProgress.setCanceledOnTouchOutside(false);
// Set the main heading
TextView dlgHeading = (TextView) dlgProgress.findViewById(R.id.layCustomProgressHeading);
dlgHeading.setText(heading);
// set the info
TextView dlgInfo = (TextView) dlgProgress.findViewById(R.id.layCustomProgressInfo);
dlgInfo.setText(text);
// Return the refenrece to the dialog
return dlgProgress;
}