Stop button when recording audio with AudioRecord - java

At the moment I have the code from this site (link text) working great. In the example on the site it starts the recording for 10 seconds and then immediately plays the audio back in reverse. I have modified the code to start recording when a button is pressed, but can only get it to record for the 10 seconds and then save that file. I want to be able to start the recording by pressing a button and then stop the recording on a different button press. I have an idea that it could be an interrupt to the wait() method of the thread object but have no idea how to implement this. My code is as follows:
public void onClickRecord(View v){
text.setText("Recording");
Thread thread = new Thread(new Runnable() {
public void run() {
record();
}
});
thread.start();
synchronized(this) {
try {
wait(10000); //This is the 10 second waiting period while recording
}
catch (InterruptedException e) {
}
}
isRecording = false;
try {
thread.join();
} catch (InterruptedException e) {
}
}
public void onClickStop(View v){
//Here is what needs to be implemented to stop the recording.
}
There is quite a bit of code so I have only posted the bits I think are relevant. If any more is needed just ask.
Thanks.

try the AudioRecord Class !
I think that should be helpful.
Also look at AudioCapture here
http://developer.android.com/guide/topics/media/index.html

Related

Progressbar in Android Studio is not showing while delay

I have a method in which I want a delay of a second, and while the delay is running there should be a loading animation (ProgressBar).
Right now, when the method is now running the loading animation is not appearing. If I do not call the Timeout it does appear, and when I do not make it invisible after, it shows up after the timeout.
How do I show the loading animation while the timeout is running? I have a similar problem trying to do with with Thread.sleep(1000).
public void firstMethod(){
ProgressBar pgLoading = (ProgressBar) findViewById(R.id.pgLoading);
pgLoading.setVisibility(VISIBLE);
try {
TimeUnit.SECONDS.sleep(1);
}catch(InterruptionException ex){
ex.printStackTrace();
}
pgLoading.setVisibility(INVISIBLE);
}
By calling the sleep method you are making the UI thread sleep for 1 second during that time nothing will happen on UI Thread hence you do not see the ProgressBar. You should instead use a TimerTask to wait for this one second and then close the ProgressBar.
Checkout this link on how to use TimerTask.
Main thread can't be blocked. That will cause the entire rendering to stop. That's why you only see the result after that timeout.
These kind of operations shoud be handled in other threads. If you are using Java you can use Runnables but you should consider moving to Kotlin to use coroutines.
E.G:
pgLoading.setVisibility(VISIBLE);
new Thread() {
public void run() {
Thread.sleep(1000);
runOnUiThread(new Runnable() {
#Override
public void run() {
pgLoading.setVisibility(INVISIBLE);
}
});
}
}
}.start();
This is happening because the current thread is being paused.To avoid this put your delay/long process in a different thread.For example:
public void firstMethod(){
ProgressBar pgLoading = (ProgressBar) findViewById(R.id.pgLoading);
pgLoading.setVisibility(View.VISIBLE);
new Thread(()->{
// Do all your long process here
try {
TimeUnit.SECONDS.sleep(1);
}catch( InterruptedException ex){
ex.printStackTrace();
}
runOnUiThread(() -> pgLoading.setVisibility(View.INVISIBLE));
}).start();
}

Activity start too long

Hello I have a problem with opening Activity.
I'm calling startActivity() with Intent by clicking Button.
I need to wait 4-5 seconds before Activity shows up on the screen.
I know how to do.
itemimg = new ItemsInPacagesImageView(imglist1, this, nazovtripu, 0);
I have 17 times similar code (with other ImageViews) I have this in Method with name InitItemimg();
I tried put this method on OnStart activity with this thread
#Override
public void onStart() {
super.onStart();
timer = new Thread() { // new thread
public void run() {
Boolean b = true;
try {
sleep(20);
runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
InitItemimg();;
}
});
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
}
}
};
timer.start();
}
But is no resolve my problem, please do you have some ideas? Thanks
excuse me, I figured so in this method (ItemsInPacagesImageView(imglist1, this, nazovtripu, 0);) on start id deserialization if is some deserialization in row is "fast" but if it's more in row (now 17) with deserialization program spend more time some seconds.
I resolve this problem with put explicit, class which i deserialization in method.
Now i deserialization once instead 17 times. and I safe more miliscond-seconds.

Why the UI thread is getting blocked?

In the below code I am trying to run a thread when a button is clicked. In the button listener I create a new thread and run it...but at run time, when the button is pressed, the button itself freezes and the app does not respond and I receive ANR dialog. Moreover, when the socket is connected successfully even the TexView
mtvStatus.setText("RFC-SOCKET CONNECTED");
displays nothing.
Please let me know why this is happening.
button listener:
this.mbtnConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BluetoothSocket rfcSocket = mSPPCtrl.rfcConnect();
if (rfcSocket.isConnected()) {
mtvStatus.setText("RFC-SOCKET CONNECTED");
Thread rx = new Thread(new RxRun(rfcSocket));
rx.run();
} else {
mtvStatus.setText("RFC-SOCKET NOT CONNECTED");
}
}
});
runnable class
private class RxRun implements Runnable {
private BluetoothSocket mRFCSocket = null;
private OutputStream mRFCOS = null;
private InputStream mRFCIS = null;
public RxRun(BluetoothSocket rfcSocket) {
this.mRFCSocket = rfcSocket;
try {
this.mRFCOS = rfcSocket.getOutputStream();
} catch (IOException e) {
e.printStackTrace();
}
try {
this.mRFCIS = rfcSocket.getInputStream();
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void run() {
try {
this.mRFCOS.write(DIRON.getBytes());
} catch (IOException e) {
e.printStackTrace();
}
while (this.mRFCSocket.isConnected()) {
try {
int readBytes = this.mRFCIS.read(new byte[5120]);
Log.d(TAG, CSubTag.bullet("RxRun", "readBytes:" + readBytes));
//mtvRx.setText(""+readBytes);
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
...when the button is pressed, the button itself freezes and the app does not respond and I receive ANR dialog. Moreover, when the socket is connected successfully even the TexView displays nothing.
It's expected, because you haven't actually started the rx thread. Here is what is going on:
mSPPCtrl gets connected,
mtvStatus's text is set to "RFC-SOCKET CONNECTED", but you cannot visually see it because
run() method of the RxRun instance is called manually where the loop while (this.mRFCSocket.isConnected()) may last as long as the socket is connected.
All the above said is invoked on UI-thread and that's the reason of ANR.
You should not call run() manually. Start the rx thread with
rx.start();
Also I highly recommend to move all the rfcSocket logic inside of the thread and notify the UI-thread on success/failure of connection.
EDIT
Here is one the option mentioned in my comment.
Start the rx thread on a button click
this.mbtnConnect.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
new Thread(new RxRun(rfcSocket)).start();
}
});
Move your logic inside of the run() method:
public void run() {
BluetoothSocket rfcSocket = mSPPCtrl.rfcConnect();
if (rfcSocket.isConnected()) {
mtvStatus.post(new Runnable() {
#Override
public void run() {
mtvStatus.setText("RFC-SOCKET CONNECTED");
}
});
} else {
mtvStatus.post(new Runnable() {
#Override
public void run() {
mtvStatus.setText("RFC-SOCKET NOT CONNECTED");
}
});
return;
}
// the rest of your logic
}
Some links that might help:
Android documentation on Threads
SO question Android basics: running code in the UI thread
another SO post on Update UI from Thread
The error here is really simple - do not use run() on the Thread instance, as this will actually run it's Runnable on the current Thread! Use start() and it will work fine :-)

Android pause/resume AsynTask

I have a UI thread(MainActivity) calling an AsynTask object(DownloadManager), which, in turn calls 3 threads (DownloaderThread).
How do I pause/resume the 3 DownloaderThreads without pausing the AsynTask or the UI thread?
Following is the code I have currently implemented for the pause functionality, but when the Pause button is clicked, the app crashes with the dialog: "app has stopped". Code:
DownloadManager (AsynTask):
public void onPause() {
try{
t0.wait();
t1.wait();
t2.wait();
this.wait();
}catch (InterruptedException ex){
}
}
DownloaderThread (implements Runnable and is passed to a Thread instance in DownloadManager:
public class DownloaderThread implements Runnable {
private Object mPauseLock;
private Boolean mPaused;
private Boolean mFinished;
public void run(){
android.os.Process.setThreadPriority(android.os.Process.THREAD_PRIORITY_BACKGROUND);
try{
while(!mFinished){
//do something
synchronized (mPauseLock){
while (mPaused){
try{
mPauseLock.wait();
}catch (InterruptedException e){
}
}
}
}
}
}
public void onPause(){
synchronized (mPauseLock){
mPaused = true;
}
}
You can't really pause an AsyncTask once it started. You can, however, store the progress when activity is paused/destroyed and start from the progress once you are back to the original Activity. But I recommend the best way to complete task for your scenario is to use Service.

Java/Android Thread pause error

i have a class that implements runnable with the run function.
#Override
public void run()
{
while(running)
{
// thread code goes here::
threadCode();////
// thread code ends here
try
{
Thread.sleep(10);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}
Now i am trying to pause the thread if something happens.
I tried to use wait() and notify() but it crashed the app, afterwards i came with idea to use the "running" boolean and set it to false as for pause, and then back to true to resume.
Unfortunately it still crashes the app.
It gives me fatal error on logcat.
"Can't create handler inside thread that has not called Looper.prepare()"
Is there any working simple way to pause a thread? ;/
Thx
EDIT:
it's not about thread at all.
I found where it crashes.
It crashes on alert dialog
here is the code of it:
AlertDialog.Builder builder1 = new AlertDialog.Builder(c);
builder1.setTitle("Game over!");
builder1.setMessage("You survived "+secs+"."+msecs+ " seconds.");
builder1.setCancelable(false);
builder1.setPositiveButton("Replay",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
// intialStuff();
dialog.cancel();
}
});
builder1.setNegativeButton("Rage quit",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
i try to run it on canvas class
maybe it cant work on canvas class?
C is context of main activity.
On Android Threads work differently as against on a regular java 'main' based program. Threads spanned from the UI thread should use a Looper for their own use else they fall back to the main UI thread's Looper. For your query calling Looper.prepare() from inside the run method, probably the fist line inside it would do. However from a long term scalability and correct approach perspective consider using a Loader or an AsynchTask.
There were 2 problems, first was i set int value on the message of the AlertDialog which caused the crash.
The fix is:
setMessage("You survived "+Integer.toString(secs)+"."+Integer.toString(msecs)+" seconds.")
The second problem and the main, i had to use hander on the thread so the AlertDialog will not crash.
Second fix:
create handler.
private Handler threadHandler = new Handler()
{
public void handleMessage(android.os.Message msg)
{
//Go to thread function
threadCode();
}
};
call it from the run function:
#Override
public void run()
{
while(true)
{
try
{
Thread.sleep(10);
//handler
if(running)
threadHandler.sendEmptyMessage(0);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
}
}

Categories

Resources