So basically, I am making an application which at the touch of a button generates a sound for 1 second after every 10 seconds and simultaneously records all other sounds as well.
I want the sound recording to happen in that 10 second pause. I tried to use threads and thread interrupts for this. But don't really know how to use them properly for this case.
Here is my code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playButton = (Button)findViewById(R.id.button);
textView = (TextView) findViewById(R.id.textView);
playButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Sound Gen Thread
Runnable myRunnable = new Runnable() {
#Override
public void run() {
new Timer().scheduleAtFixedRate(new TimerTask() {
public void run() {
AudioTrack tone = generateTone(freq, 1000);
tone.play();
}
}, 0, 10000);
}
};
new Thread(myRunnable).start();
//Recording Thread
Runnable myRunnable1 = new Runnable() {
#Override
public void run() {
doInBackground();
}
};
new Thread(myRunnable1).start();
}
});
}
Related
Timer mytimer = new Timer();
int i = 0;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mytimer.scheduleAtFixedRate(new TimerTask()
{
#Override
public void run () {
runOnUiThread(new Runnable() {
#Override
public void run() {
i++;
}
});
}
},0,1000);
Here is my code, after I ran the app on background for few minutes and returned to the app. The app started another timer (sometimes it doesn't starts) and there were two timers running. Please tell me how do I prevent it.
I'm a student trying to create an app for my miniproject for one of my modules and I'm trying to create an app that grabs data from a server every few seconds so it's updated. I tried using java timer and timerTask to run the code repeatedly but the program only run once and the get-button doesn't work as intended (suppose to grab data instantly) after implementing the timer. Android Emulator
public class MainActivity extends AppCompatActivity implements OnClickListener{
private Button speed;
private TextView result;
Timer timer;
TimerTask timerTask;
private TextView sSpeed;
final StringBuilder builder = new StringBuilder();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
result = (TextView) findViewById(R.id.result);
sSpeed = (TextView) findViewById(R.id.sSpeed);
speed = (Button) findViewById(R.id.get_button);
speed.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
getWebsite();
}
});
View aboutButton = this.findViewById(R.id.about_button);
aboutButton.setOnClickListener(this);
View exitButton = this.findViewById(R.id.exit_button);
exitButton.setOnClickListener(this);
}
public void onClick(View v) {
switch (v.getId()){
case R.id.get_button:
getWebsite();
break;
case R.id.about_button:
Intent i = new Intent(this, About.class);
startActivity(i);
break;
case R.id.exit_button:
finish();
break;
}
}
private void getWebsite(){
new Thread(new Runnable() {
#Override
public void run() {
try{
Document doc = Jsoup.connect("http://10.0.2.2:8080/Start_Stop_buttons_UTF8.html").get();
// Elements element = doc.getElementsByTag("p");
Elements element = doc.select("p");
//String title = doc.title();
builder.append(title).append("\n");
for (Element tag : element){
builder.append("\n\n").append(tag.text());
}
}catch(IOException e){
//e.printStackTrace();
builder.append("Error : ").append(e.getMessage()).append("\n");
}
runOnUiThread(new Runnable() {
#Override
public void run() {
String a = builder.toString(); // parse data from html into new string
a = a.substring(a.indexOf(":")+1, a.indexOf("Control")).trim();//trim string content
String b = builder.toString();
b = b.substring(11,b.indexOf(":")+1).trim();
double speed = Double.parseDouble(a);//convert string into double
if (speed<1000)
Log.i("HTML text","too slow");
else if((speed> 1500))Log.i("HTML text","too fast!");
result.setText(a);
sSpeed.setText(b);
}
});
}
}).start();
}
protected void onResume() {
super.onResume();
startTimer();
}
public void startTimer(){
timer = new Timer();
timerTask = new TimerTask() {
#Override
public void run() {
getWebsite();
}
};
timer.schedule(timerTask,1500,3000);
}
public void stopTimer(){
if(timer != null){
timer.cancel();
timer.purge();
}
}
}
Am I implementing the timer correctly to run getwebsite() repeatedly and able to get an instant update when get-button is clicked like it should have? Or is there a better way to implement these features using different method?
You are never calling the startTimer method in your ClickListener. You make one call to getWebsite. Change your call to startTimer.
speed.setOnClickListener(new View.OnClickListener(){
#Override
public void onClick(View view) {
startTimer();
}
});
You also might want to check if the timer is already running before you start a new one. To do that assign a null value on your stopTimer method e.g.
public void stopTimer(){
if(timer != null){
timer.cancel();
timer.purge();
timer = null;
}
}
And your startTimer would look like this
public void startTimer(){
if(timer != null) return; // don't start multiple timers
timer = new Timer();
timerTask = new TimerTask() {
#Override
public void run() {
getWebsite();
}
};
timer.schedule(timerTask,1500,3000);
}
I want complete code to disable a Button for some time for example 2 minutes in Android Studio. Thank you for help.
protected void onclick(View v){
bwasta = (Button) findViewById(R.id.btDes);
new CountDownTimer(10000, 10) { //Set Timer for 10 seconds
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
bwasta.setEnabled(true);
bwasta.setEnabled(false);
}
}.start();
This might help you out.
Button bwasta = (Button) findViewById(R.id.btDes);
bwasta.setEnabled(false);
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(2*
60*
1000);//min secs millisecs
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
YourActivityName.this.runOnUiThread(new Runnable() {
#Override
public void run() {
bwasta.setEnabled(true);
}
});
}
}).start();
DO NOT RELY ON Thread.sleep()
Actually, there is already a Question and an Answer on SO regarding the inaccuracy of Thread.sleep()(as per the OP's experience) here.
The answer then favors the accuracy of a ScheduledThreadPoolExecutor using the schedule() method.
Do the following:
Button bwasta = (Button) findViewById(R.id.btDes);
bwasta.setEnabled(false);
ScheduledThreadPoolExecutor exec = new ScheduledThreadPoolExecutor(1);
exec.schedule(new new Runnable() {
#Override
public void run() {
YourActivityName.this.runOnUiThread(new Runnable() {
#Override
public void run() {
bwasta.setEnabled(true);
}
});
}
}, 2, TimeUnit.MINUTES);
You can use mHandler.postDelayed(mRunnable, mTime) function to achieve this
Button bwasta = (Button) findViewById(R.id.btDes);
bwasta.setEnabled(false);
bwasta.postDelayed(new Runnable() {
public void run() {
bwasta.setEnabled(true);
}
}, 2*60*1000);
I create an application with lots of fragments . In my last fragment I try to print something on LogCatafter 10 seconds . But it dosen't work for me .
This is my Fragment class
public class StepTwentyTwoFragment extends Fragment {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.step22_fragment, container, false);
testMethod();
return v;
}
public static StepTwentyTwoFragment newInstance() {
StepTwentyTwoFragment f = new StepTwentyTwoFragment();
Bundle b = new Bundle();
f.setArguments(b);
return f;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if(isVisibleToUser) {
Activity a = getActivity();
if(a != null) a.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
}
public void testMethod(){
SystemClock.sleep(10000);
Log.d("PPP : ","456");
}
}
Actually I want print this "PPP" after 10 seconds when last fragment is launched. But it begins to print with the loading of some fragments in the application.
Have any ideas about this ?
Thank you.
You shouldn't sleep, nor create threads when you don't need them. Android's main thread is event-loop based and you can schedule events / code to be executed at a point in the future.
Your simplest option is to use
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.step22_fragment, container, false);
Runnable delayedTask = new Runnable() {
#Override
public void run() {
Log.d("PPP : ","456");
}
};
v.postDelayed(delayedTask, 10000);
return v;
}
If you don't have a View you can also create your own handler.
private static final Handler mainThreadHandler = new Handler(Looper.getMainLooper());
public void testMethod(){
Runnable delayedTask = new Runnable() {
#Override
public void run() {
Log.d("PPP : ","456");
}
};
mainThreadHandler.postDelayed(delayedTask, 10000);
}
Use Handler.postDelayed method to achieve this.
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
//Do something after 10000ms
}
}, 10000);
Place the code you want to execute in the run() method.Read more about Handlers from here
Probably you are sleeping the ui thread that's why your log appears after sleep ends.
Use Timer and TimerTask. TimerTask runs on a different thread from ui thread.
Timer timer = new Timer();
TimerTask timer_task = new TimerTask() {
#Override
public void run() {
Log.d("PPP : ","456");
}
};
timer.schedule(timer_task, 10000);
try this
public void executePeriodicTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
#Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
//Write your code here , which you want to execute periodically
} catch (Exception e) {
// TODO Auto-generated catch block
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 50000); //execute in every 50000 ms
}
You can simple Create a Thread Or Handler for that.
If you want to use Thread ->
new Thread(new Runnable() {
#Override
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {}
((Activity)getActivity()).runOnUiThread(new Runnable() {
#Override
public void run() {
Log.d("PPP : ","456");
// Do other Stuff
}
});
}
}).start();
You can use Handler with PostDelayed passing Runnable to it
new Handler().postDelayed(new Runnable(){
#Override
public void run() {
Log.d("PPP : ","456");
}
}, 10000);
i am new to android programming, i searched through all the answers about this topic but still i am not able to implement what i want to do. My problem is: i want to update the picture at imageview with another picture in given periods. The imageview is needed to be updated with different pictures every time, total of 15-20 times. Here is what i have done so far but it is not working at all.
public class IlkMasal extends Activity {
MediaPlayer sound;
private Handler m_handler;
private ImageView image;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.firsttale);
m_handler = new Handler();
Button menu = (Button)findViewById(R.id.Button01);
Button startbutton = (Button)findViewById(R.id.button1);
sound = MediaPlayer.create(this, R.raw.music4);
sound.start();
image = (ImageView)findViewById(R.id.imageView1);
image.setImageResource(R.drawable.picture2);
startbutton.setOnClickListener(new OnClickListener(){
public void onClick(View v){
m_handler.removeCallbacks(m_statusChecker);
m_handler.postDelayed(m_statusChecker, 2000);
}
});
menu.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Intent main= new Intent("android.intent.action.MAIN");
startActivity(main);
}
});
}
Runnable m_statusChecker = new Runnable()
{
public void run(){
image.setImageResource(R.drawable.picture3);
m_handler.removeCallbacks(m_statusChecker);
m_handler.postDelayed(m_statusChecker, 2000);
}
};
}
After i click startbutton i want to update the ui with different pictures every time. I will appreciate your help.
Yo can set this runnable to run on your onClic and you will still need a method to get the next picture you want to show.
final int delay = 5000;
final int period = 1000;
final Runnable r = new Runnable() {
public void run() {
image.setImageResource(getNextPicture());
postDelayed(this, period);
}
};
postDelayed(r, delay);
Regards.
use runOnUiThread for Updating UI Elements from NON Ui Thread as:
Current_Activity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
image.setImageResource(R.drawable.picture3); //Update UI elements here
}
});