Right now I have an activity, let's say 'Activity A' that runs the Timer. It is to update my Firebase when the time is up.
timer.scedule(new TimerTask()){
#Override
public void run() {
notification();
Firebase areaRef = mAreaRef.child(bKey);
areaRef.addListenerForSingleValueEvent(new com.firebase.client.ValueEventListener() {
#Override
public void onDataChange(com.firebase.client.DataSnapshot dataSnapshot) {
checkData = dataSnapshot.child("data").getValue(Integer.class);
Integer addData = checkData+1;
}
#Override
public void onCancelled(FirebaseError firebaseError) {
}
});
}
},millis);
There will be a button at 'Activity B'. When the button is clicked, the timer at 'Activity A' must be stopped.
How do I do this?
There just can be only one "Activity" activated in the same time. Your 'Activity A' can be instead by a service. And then your problem is solved by 'Activity B' directly call service method to stop the timer when the button is clicked.
If your timer task really needs to be alive across activities, maybe you should consider use a Service instead of a timer in specified activity.
1.Change Timer to CountDownTimer call start() to begin call cancel() to stop.
How to notify Activity A to stop the CountDownTimer, you can change SharedPreferences to others way to deal with data notify
public class MainActivity extends AppCompatActivity {
CountDownTimer timer = new CountDownTimer(30000, 1000) {
public void onTick(long millisUntilFinished) {
SharedPreferences sharedPreferences = getSharedPreferences("count", 0);
if (sharedPreferences.getBoolean("stop", false)) {
timer.cancel();
} else {
Log.d("tag", millisUntilFinished / 1000 + "");
}
}
public void onFinish() {
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer.start();
Intent intent = new Intent(this, ActivityB.class);
startActivity(intent);
}
}
public class ActivityB extends AppCompatActivity {
Button mStop;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_b);
mStop =(Button) findViewById(R.id.stop);
mStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
SharedPreferences sharedPreferences = getSharedPreferences("count",0);
SharedPreferences.Editor edit= sharedPreferences.edit();
edit.putBoolean("stop", true);
edit.apply();
}
});
}
}
Related
I am trying to use progressbar like a 30 secs timer. It works well but when i click back button the progressbar progress continues. I am unable to reset the progressbar progress to 0 when i click the backbutton.
Here is my code:
MainAcitivty:
public class MainActivity extends AppCompatActivity {
public Button btnA;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnA = (Button)findViewById(R.id.btnA);
btnA.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intentA = new Intent(MainActivity.this,SecondActivity.class);
startActivity(intentA);
}
});
}
}
SecondActivity:
public class SecondActivity extends AppCompatActivity{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_second);
Context context;
float from;
float to;
final TextView textV;
final ProgressBar mProgressBar;
CountDownTimer mCountDownTimer;
final int[] i = {0};
textV = (TextView)findViewById(R.id.tvFinal);
mProgressBar = (ProgressBar)findViewById(R.id.progressbar);
mProgressBar.setProgress(i[0]);
mCountDownTimer=new CountDownTimer(30000,1000) {
#Override
public void onTick(long millisUntilFinished) {
Log.v("Log_tag", "Tick of Progress"+ i[0] + millisUntilFinished);
i[0]++;
mProgressBar.setProgress((int) i[0] *100/(30000/1000));
}
#Override
public void onFinish() {
i[0]++;
mProgressBar.setProgress(100);
textV.setText("finish");
Intent intent = new Intent(SecondActivity.this, SecondActivity.class);
startActivity(intent);
}
};
mCountDownTimer.start();
}
}
in order to implement behaviour of back button you need to override onBackPressed() and then implement method to reset progressbar result.
Example:
#Override
public void onBackPressed() {
super.onBackPressed();
progressBar.setProgress(0);
}
So im working on slideshow-like project, but my problem is, when im at the middle of slideshow, I want to go back at my main activity where my slideshow will start using back button on my smartphone. What happen is, it will go back as soon as I pressed back button, but the other slideshows will carry on after 3 seconds which I set in my handler.postDelayed(r1, 3000);. Please help. Thank you
public class Dad1 extends AppCompatActivity {
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dad1);
Runnable r1 = new Runnable() {
#Override
public void run() {
Intent i = new Intent(getApplicationContext(), Dad2.class);
startActivity(i);
finish();
}
};
Handler handler = new Handler();
handler.postDelayed(r1, 3000);
}
}
What you can do is keep the Handler object at the Activity level. When back button is pressed then just cancel the Handler callbacks. So in that case your Handler's run method will not be called.
Please find the sample code below:
public class Dad1 extends AppCompatActivity {
private Handler handler;
private Runnable myRunnable;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initRunnable();
handler.postDelayed(myRunnable,3000);
}
private void initRunnable() {
myRunnable = new Runnable() {
#Override
public void run() {
Intent i = new Intent(getApplicationContext(), Dad2.class);
startActivity(i);
finish();
}
};
}
#Override
public void onBackPressed() {
super.onBackPressed();
if(handler!=null){
handler.removeCallbacks(myRunnable);
}
}
}
I want to start the Main2Activity's task(Loading the WebView) when button is pressed but not to show the Main2Activity's Screen until onPageFinished() is called. i had some ideas to get this by Intents however it seems doesn't work.
Here my code :
MainActivity.java :
public class MainActivity extends AppCompatActivity {
Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
super.handleMessage(msg);
Intent intent = new Intent(MainActivity.this,Main2Activity.class);
startActivity(intent);
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final Button button = (Button)findViewById(R.id.Button);
button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Runnable runnable = new Runnable() {
#Override
public void run() {
handler.sendEmptyMessage(0);
}
};
Thread thread = new Thread(runnable);
thread.start();
}
}
);
}
}
Main2Activity.java :
public class Main2Activity extends AppCompatActivity {
Intent intent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
final WebView webView = (WebView)findViewById(R.id.webview);
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(webView, url);
intent.putExtra("DONE",1);
// Toast.makeText(getApplicationContext(), "Done!",
//Toast.LENGTH_SHORT).show();
}
});
webView.loadUrl("file:///android_asset/2.2.html");
}
}
is this possible using Intents or i have to do this with some other techniques?
How can i Achieve this goal ?
Thanks All.
I think you should directly go to Main2Activity on button click, without calling any thread in MainActivity.
Then in Main2Activity show an image or something until onPageFinished() is called.
I want the countdowntimer to be on a separate thread and for it to update the UI on each tick. Every time I click start the app just closes and I get the 'app has stopped' error message.
public class Activity_MultiplayerGame extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity__multiplayer_game);
}
public void btnStart_onClick(View view){
CountDownTimer timer = new CountDownTimer(15000, 1000){
#Override
public void onTick(final long millisUntilFinished) {
runOnUiThread(new Runnable() {
#Override
public void run() {
TextView countdownText = (TextView) findViewById(R.id.countdown);
Integer timeUntilFinished = (int) millisUntilFinished/1000;
countdownText.setText(timeUntilFinished);
}
});
}
#Override
public void onFinish() {
TextView countdownText = (TextView) findViewById(R.id.countdown);
countdownText.setText("Finished");
}
};
timer.start();
}
}
I've made the assumption that creating a CountDownTimer gives it its own thread?
you can use Handler. I wrote a sample for you
this code increase a counter every one second and show and update counter value on a textView.
public class MainActivity extends Activity {
private Handler handler = new Handler();
private TextView textView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView = (TextView) findViewById(R.id.text);
startTimer();
}
int i = 0;
Runnable runnable = new Runnable() {
#Override
public void run() {
i++;
textView.setText("counter:" + i);
startTimer();
}
};
public void startTimer() {
handler.postDelayed(runnable, 1000);
}
public void cancelTimer() {
handler.removeCallbacks(runnable);
}
#Override
protected void onStop() {
super.onStop();
cancelTimer();
}
}
You cannot update UI from other thread than main (ui) thread on android. There are many ways to approach the problem, but I suppose you should start with AsyncTask if you really need another thread. Check doInBackround and onProgressUpdate methods.
If you don't need other thread (and if this is only about the counter you dont') you can check Handler class and postAtTime(Runnable, long), postDelayed(Runnable, long) methods. Or you can make subclass of Handler class and use combination of sendMessageDelayed(android.os.Message, long) and overridden handleMessage().
Here's your problem:
countdownText.setText(timeUntilFinished);
You have passed integer to setText(int) method, which actually takes the string resource id rather than the integer to be displayed. You should use the method setText(String).
Try this:
countdownText.setText(String.valueOf(timeUntilFinished));
This code also work it decrease counter(or increase whatever you want) and show in text view you can also stop or reset counter via click the same button.
public class MainActivity extends AppCompatActivity {
TextView textView;
Button count;
boolean timelapseRunning = true;
int NUM_OF_COUNT=15;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView=(TextView)findViewById(R.id.textview);
count=(Button)findViewById(R.id.count);
runTimer();
}
public void onclick(View view){
if (!timelapseRunning) {
timelapseRunning=true;
} else {
timelapseRunning = false;
}
if(NUM_OF_COUNT==0){
NUM_OF_COUNT=15;
}
}
private void runTimer() {
final Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
textView.setText(""+NUM_OF_COUNT);
if (!timelapseRunning && NUM_OF_COUNT>0) {
NUM_OF_COUNT--;
}
handler.postDelayed(this, 1000);
}
});
}
}
The CountDownTimer gives out callbacks on the same thread, in which it was created. So the runOnUiThread in onTick is absolutely not required if the CountDownTimer constructor was called on UI thread.
Also,
TextView countdownText = (TextView) findViewById(R.id.countdown);
being called in onTick method is poor design, as findViewById method consumes considerable processing power.
Finally the actual problem as Nabin Bhandari pointed out is the integer value passed to setText method. You need to wrap it to string.
This code is enough
final TextView countdownText = (TextView) findViewById(R.id.countdown);
CountDownTimer timer = new CountDownTimer(15000, 1000) {
#Override
public void onTick(long millisUntilFinished) {
countdownText.setText(String.valueOf(millisUntilFinished/1000));
}
#Override
public void onFinish() {
countdownText.setText("Finished");
}
};
timer.start();
I want the button to finish the activity. Why do I have to press it TWICE for it to finish, I do not want this. Note, I have to press the button twice before the activity ends, which I do not want.
MainActivity Class:
private Runnable updateOkay= new Runnable() {
public void run() {
if (true) {
Intent i = new Intent(this, WorkTimerNotification.class);
startActivity(i); }
WorkTimerNotification class:
public Button confirmButton;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_work_timer_notification);
confirmButton = (Button) findViewById(R.id.confirmOK_button);
confirmButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
finish();
}
});
}
}
Solved by setting
android:launchMode = "singleInstance"
in AndroidManifest.xml file.