I have developed an app that has two buttons (left and right) and a Textview that will pop up on the screen.Each button has it's corresponding word.
The user has to click the button that corresponds to TextView's word as quickly as possible when it shows. I want to calculate it's reaction time on clicking the button.
Below is my code.
public class Place_to_go_1 extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_place_to_go_1);
placeone = Global_variables.getFirst_choice_label();
placetwo = Global_variables.getSecond_choice_label();
p_one = (TextView)findViewById(R.id.p_one);
p_two = (TextView)findViewById(R.id.p_two);
btnleft = (ImageButton)findViewById(R.id.btnleft);
btnright = (ImageButton)findViewById(R.id.btnright);
next = (ImageButton)findViewById(R.id.Next);
lblmaintext = (TextView)findViewById(R.id.lblmaintext);
lblprompt = (TextView)findViewById(R.id.lblprompt);
lblreact = (TextView)findViewById(R.id.lblreact);
imgmain = (ImageView)findViewById(R.id.imgmain);
//prac = (ImageView) findViewById(R.id.prac);
Intent intent = getIntent();
final String randomId = intent.getStringExtra("Info_id");
//============ validate image if not empty
setImage_onLaunch();
//==== populate left and right choices===
populate_headers(placeone, placetwo);
//==== populate attributes=====
populate_attributes();
//============== instruction ======
setInstruction();
//=============media
wrong_press = MediaPlayer.create(this, R.raw.wrong_press);
react_fast = MediaPlayer.create(this, R.raw.react_faster);
//=== left button click trigger
btnleft.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String position = "H";
if (tanan[counter].equals(p_one.getText().toString())) {
lblprompt.setVisibility(View.INVISIBLE);
HashMap<String,String> queryValues = new HashMap<String, String>();
queryValues.put("Info_id",randomId);
queryValues.put("Choice",p_one.getText().toString());
queryValues.put("Reaction_time",String.valueOf(elapsedTime));
queryValues.put("Position",position);
queryValues.put("Main",main);
queryValues.put("Error",error);
mydb.insertTest(queryValues);
counter++;
if (counter < tanan.length) {
btnleft.setEnabled(false);
btnright.setEnabled(false);
timeStamp = System.currentTimeMillis();
//Toast.makeText(Place_to_go_1.this, ""+timeStamp, Toast.LENGTH_SHORT).show();
getreactionTime(p_one.getText().toString(), String.valueOf((((timeStamp) / 1000.0) - ((timeRun) / 1000.0))));
setIntervalTime();
} else {
//======end sa data
postEnd();
}
} else {
// Toast.makeText(Place_to_go_1.this, "Wrong pressed", Toast.LENGTH_SHORT).show();
//wrong_press.start();
wrong_click_audio();
error = "1";
lblprompt.setVisibility(View.VISIBLE);
}
}
});
//==== right button click trigger
btnright.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String position = "A";
if (tanan[counter].equals(p_two.getText().toString())) {
lblprompt.setVisibility(View.INVISIBLE);
HashMap<String,String> queryValues = new HashMap<String, String>();
queryValues.put("Info_id",randomId);
queryValues.put("Choice",p_two.getText().toString());
queryValues.put("Reaction_time", String.valueOf(elapsedTime));
queryValues.put("Position",position);
queryValues.put("Main",main);
queryValues.put("Error",error);
mydb.insertTest(queryValues);
counter++;
if (counter < tanan.length) {
btnleft.setEnabled(false);
btnright.setEnabled(false);
timeStamp = System.currentTimeMillis();
//Toast.makeText(Place_to_go_1.this, ""+timeStamp, Toast.LENGTH_SHORT).show();
getreactionTime(p_two.getText().toString(), String.valueOf((((timeStamp) / 1000.0) - ((timeRun) / 1000.0))));
setIntervalTime();
} else {
//======end sa data
postEnd();
}
} else {
// Toast.makeText(Place_to_go_1.this, "Wrong pressed", Toast.LENGTH_SHORT).show();
// wrong_press.start();
wrong_click_audio();
error = "1";
lblprompt.setVisibility(View.VISIBLE);
}
}
});
// ==== next button for the next activity (Place to go 2)
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = getIntent();
String randomId = intent.getStringExtra("Info_id");
//============= launch activity 2 for place to go
if (instruct == true) {
next.setVisibility(View.INVISIBLE);
// prac.setVisibility(View.VISIBLE);
CountDownTimer();
} else {
//Toast.makeText(getApplication(),"Saved Successfully.",Toast.LENGTH_SHORT).show();
Intent i = new Intent(getApplicationContext(), Place_to_go_2.class);
i.putExtra("Info_id", randomId);
startActivity(i);
}
}
});
}
public void interval(){
if(counter < tanan.length){
lblmaintext.setVisibility(View.VISIBLE);
timeRun = System.currentTimeMillis();
btnleft.setEnabled(true);
btnright.setEnabled(true);
lblmaintext.setText(tanan[counter]);
setImage();
imgmain.setVisibility(View.VISIBLE);
react = true;
reacFaster();
}else{
//======end sa data
Toast.makeText(Place_to_go_1.this, "End data", Toast.LENGTH_SHORT).show();
lblmaintext.setVisibility(View.VISIBLE);
lblmaintext.setText("Ok for now");
}
}
public void setIntervalTime(){
react = false;
lblreact.setVisibility(View.INVISIBLE);
reactFaster_timer.cancel();
lblmaintext.setVisibility(View.INVISIBLE);
lblreact.setVisibility(View.INVISIBLE);
imgmain.setVisibility(View.INVISIBLE);
timer = new CountDownTimer(Global_variables.interval_time_before_choices_will_show,Global_variables.interval_time_before_choices_will_show) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
interval();
}
}.start();
}
int counter_countdown = 0;
int drawwable_amber = R.drawable.amber;
String arr[] = {"Ready...","Set...","Start."};
public void CountDownTimer(){
btnleft.setVisibility(View.INVISIBLE);
btnright.setVisibility(View.INVISIBLE);
lblmaintext.setBackgroundResource(0);
timer = new CountDownTimer(4000,1000) {
#Override
public void onTick(long millisUntilFinished) {
lblmaintext.setTextSize(35);
lblmaintext.setText(arr[counter_countdown]);
counter_countdown++;
}
#Override
public void onFinish() {
btnleft.setVisibility(View.VISIBLE);
btnright.setVisibility(View.VISIBLE);
lblmaintext.setBackgroundResource(drawwable_amber);
// lblmaintext.setText(tanan[counter]);
//setImage();
val_first_launch();
timeRun = System.currentTimeMillis();
react = true;
reacFaster();
}
}.start();
}
public void reacFaster(){
reactFaster_timer = new CountDownTimer(Global_variables.reaction_time_first_param,Global_variables.reaction_time_second_param) {
#Override
public void onTick(long millisUntilFinished) {
}
#Override
public void onFinish() {
if(react == true){
//Toast.makeText(Place_to_go_1.this, "please react faster", Toast.LENGTH_SHORT).show();
react_fast.start();
lblreact.setVisibility(View.VISIBLE);
}
}
}.start();
}
public void populate_headers(String one,String two){
//== this methos sets headers as random==//
headers = new ArrayList<String>();
headers.add(one);
headers.add(two);
Collections.shuffle(headers);
p_one.setText(headers.get(0));
p_two.setText(headers.get(1));
}
public void populate_attributes(){
attributes = new ArrayList<String>();
for(int h =0;h < 5;h++){
attributes.add(placeone);
attributes.add(placetwo);
}
Collections.shuffle(attributes);
tanan = new String[attributes.size()];
for(int k = 0; k < tanan.length;k++ ){
tanan[k] = attributes.get(k);
}
}
public void postEnd(){
instruct = false;
lblprompt.setVisibility(View.INVISIBLE);
btnright.setVisibility(View.INVISIBLE);
btnleft.setVisibility(View.INVISIBLE);
next.setVisibility(View.VISIBLE);
lblmaintext.setBackgroundResource(0);
lblmaintext.setTextSize(20);
p_one.setVisibility(View.INVISIBLE);
p_two.setVisibility(View.INVISIBLE);
imgmain.setVisibility(View.INVISIBLE);
reactFaster_timer.cancel();
lblreact.setVisibility(View.INVISIBLE);
lblmaintext.setText("Well done!\nNext, is the main task. It is exactly the same as before but this time words will appear on the screen that might distract you. \nPlease respond as quickly as you can.\n Press Next to begin");
}
//=========== validate if image is enabled/ disble if not set
public void setImage_onLaunch(){
if(Global_variables.getFirst_choice_image().equals("") || Global_variables.getSecond_choice_image().equals("")){
disbaleImage();
}else{
}
}
public void setImage(){
/* if(tanan[counter].equals(p_one.getText().toString())){
imgmain.setImageBitmap(BitmapFactory.decodeFile(Global_variables.getFirst_choice_image()));
}else{
imgmain.setImageBitmap(BitmapFactory.decodeFile(Global_variables.getSecond_choice_image()));
}*/
if(placeone.equals(tanan[counter])){
imgmain.setImageBitmap(BitmapFactory.decodeFile(Global_variables.getFirst_choice_image()));
}else{
imgmain.setImageBitmap(BitmapFactory.decodeFile(Global_variables.getSecond_choice_image()));
}
}
public void val_first_launch(){
if(Global_variables.getFirst_choice_image().equals("") || Global_variables.getSecond_choice_image().equals("")){
lblmaintext.setVisibility(View.VISIBLE);
lblmaintext.setText(tanan[counter]);
}else{
imgmain.setVisibility(View.VISIBLE);
if(placeone.equals(tanan[counter])){
imgmain.setImageBitmap(BitmapFactory.decodeFile(Global_variables.getFirst_choice_image()));
}else{
imgmain.setImageBitmap(BitmapFactory.decodeFile(Global_variables.getSecond_choice_image()));
}
}
}
public void disbaleImage(){
imgmain.setBackgroundResource(0);
imgmain.setVisibility(View.GONE);
}
#Override
public void onBackPressed() {
super.onBackPressed();
startActivity(new Intent(getApplication(), MainActivity.class));
finish();
}
public String getreactionTime(String domain, String time){
// Toast.makeText(Place_to_go_1.this, time, Toast.LENGTH_SHORT).show();
//== get reaction time to every activity
Global_variables.set_timeStamps(domain, time);
return domain;
}
//===== prompt instruction====
public void setInstruction(){
btnleft.setVisibility(View.INVISIBLE);
btnright.setVisibility(View.INVISIBLE);
lblmaintext.setBackgroundResource(0);
lblmaintext.setTextSize(20);
lblmaintext.setText("Instruction:\n\nIf " + p_one.getText().toString() + " appears, press arrow left.\n If " + p_two.getText().toString() +
" appears, press arrow right.\n\nRespond as quickly as you can.");
next.setVisibility(View.VISIBLE);
}
//===== prompt instruction====
public void wrong_click_audio(){
wrong_press.start();
}
//=============end class====================
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
// Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
// Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
//Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
}
}
}
Here a simple logic to calculate reaction time is to create a variable which hold a time when a question is popped up to user and the time when a user show a click reaction to question and calculate the time difference between these two action.
long timeWhenQuestionShowed = System.currentTimeMillis();
long timeWhenUserReacted = System.currentTimeMillis();
long reactionTime = timeWhenQuestionShowed - timeWhenUserReacted;
This should help:
Try using onTouch instead of onClick.
long timeBefor=0;
long timeReaction=0;
btnleft.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN: // when pressed
timeBefore=System.currentTimeMillis();
break;
case MotionEvent.ACTION_UP: // when released
timeReaction=System.currentTimeMillis() - timeBefore; // calculate difference
break;
}
}
timeReaction is your desired value.
The idea is to calculate the difference between 2 points in time. I will write 2 examples of calculating time difference in Java / measuring reaction time in Java:
System.nanoTime() or System.currentTimeMillis()
Differences are discussed here: Time measuring overhead in Java
long endTimeNanoSec = 0;
long startTimeNanoSec = System.nanoTime();
myWorkThatNeedsTiming(); // wait for user button press here
endTimeNanoSec = System.nanoTime();
long totalWorkTimeNanos = endTimeNanoSec - startTimeNanoSec;
Java StopWatch
JavaDoc: StopWatch
Stopwatch stopwatch = Stopwatch.createStarted();
myWorkThatNeedsTiming(); // wait for user button press here
stopwatch.stop();
long totalWorkTimeMillis = stopwatch.elapsedMillis();
Related
I want to show a custom XML dialog dialogue that will appear after a specific time in the first run, let's say after a min
how can I do it
but I'm confused about what should I do in a situation like below
if the user open the app for the first time and just spent 30 sec and just pause the app(screen lock or in onPause) or just close the app completely
Just as a note - I have already implemented a one time show dialog(directly in main activity without any layout file ) when the app runs for the first time already
Code
To view the already implemented dialog(shows up on the first run) please
go to the // Caution dialog (showDialog method)
MainActivity.java
public class MainActivity extends AppCompatActivity {
MediaPlayer player1;
MediaPlayer player2;
SeekBar seekBar1;
SeekBar seekBar2;
TextView elapsedTimeLable1;
TextView elapsedTimeLable2;
TextView remainingTimeLable1;
TextView remainingTimeLable2;
ImageView play1;
ImageView play2;
int totalTime1;
#SuppressLint("HandlerLeak")
private final Handler handler1 = new Handler() {
#SuppressLint("SetTextI18n")
#Override
public void handleMessage(#NonNull Message msg) {
int currentPosition1 = msg.what;
//Update SeekBar
seekBar1.setProgress(currentPosition1);
// Update Timelable
String elapsedTime1 = createTimerLable1(currentPosition1);
elapsedTimeLable1.setText(elapsedTime1);
String remainingTime1 = createTimerLable1(totalTime1 - currentPosition1);
remainingTimeLable1.setText("- " + remainingTime1);
}
};
int totalTime2;
#SuppressLint("HandlerLeak")
private final Handler handler2 = new Handler() {
#SuppressLint("SetTextI18n")
#Override
public void handleMessage(#NonNull Message msg) {
int currentPosition2 = msg.what;
// Update SeekBar
seekBar2.setProgress(currentPosition2);
// Update Timelable
String elapsedTime2 = createTimerLable2(currentPosition2);
elapsedTimeLable2.setText(elapsedTime2);
String remainingTime2 = createTimerLable2(totalTime2 - currentPosition2);
remainingTimeLable2.setText("- " + remainingTime2);
}
};
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#SuppressLint("ObsoleteSdkInt")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
Window w = getWindow();
// clear FLAG_TRANSLUCENT_STATUS flag:
w.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
// add FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS flag to the window
w.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
// finally change the color
w.setStatusBarColor(ContextCompat.getColor(this, R.color.Card_Elevation_Color));
}
// PlayButton * The ButtonClick is in the last if you want to jump directly there *
play1 = findViewById(R.id.playbtn1);
play2 = findViewById(R.id.playbtn2);
// TimeLables
elapsedTimeLable1 = findViewById(R.id.cTime1);
elapsedTimeLable2 = findViewById(R.id.cTime2);
remainingTimeLable1 = findViewById(R.id.tTime1);
remainingTimeLable2 = findViewById(R.id.tTime2);
// MediaPlayer
player1 = MediaPlayer.create(this, R.raw.dog_howl);
player1.setLooping(true);
player1.seekTo(0);
totalTime1 = player1.getDuration();
player2 = MediaPlayer.create(this, R.raw.dog_bark);
player2.setLooping(true);
player2.seekTo(0);
totalTime2 = player2.getDuration();
//SeekBar
seekBar1 = findViewById(R.id.seekbar1);
seekBar2 = findViewById(R.id.seekbar2);
seekBar1.setMax(totalTime1);
seekBar2.setMax(totalTime2);
seekBar1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress1, boolean fromUser1) {
if (fromUser1) {
player1.seekTo(progress1);
seekBar1.setProgress(progress1);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress2, boolean fromUser2) {
if (fromUser2) {
player2.seekTo(progress2);
seekBar2.setProgress(progress2);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
// Thread (Update SeekBar & TimeLabel)
new Thread(() -> {
while (player1 != null) {
try {
Message msg = new Message();
msg.what = player1.getCurrentPosition();
handler1.sendMessage(msg);
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
}
}).start();
new Thread(() -> {
while (player2 != null) {
try {
Message msg = new Message();
msg.what = player2.getCurrentPosition();
handler2.sendMessage(msg);
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
}
}).start();
// Admob Banner Ad
MobileAds.initialize(this, initializationStatus -> {
});
AdView mAdView = findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
// Caution dialog
SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
boolean firstStart = preferences.getBoolean("firstStart", true);
if (firstStart) {
showDialog();
}
}
// Caution dialog
private void showDialog() {
new AlertDialog.Builder(this)
.setTitle("Caution!")
.setMessage("In case you're wearing any kind of headphones please remove it before playing the ' Howl ' audio")
.setPositiveButton("ok", (dialogInterface, i) -> dialogInterface.dismiss())
.create().show();
SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("firstStart", false);
editor.apply();
}
public String createTimerLable1(int duration) {
String timerLabel1 = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel1 += min + ":";
if (sec < 10) timerLabel1 += "0";
timerLabel1 += sec;
return timerLabel1;
}
public String createTimerLable2(int duration) {
String timerLabel2 = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel2 += min + ":";
if (sec < 10) timerLabel2 += "0";
timerLabel2 += sec;
return timerLabel2;
}
public void playBtnClick1(View view) {
if (player2.isPlaying()) {
player2.pause();
play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
if (!player1.isPlaying()) {
// Stoping
player1.start();
play1.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
} else {
// Playing
player1.pause();
play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
}
public void playBtnClick2(View view) {
if (player1.isPlaying()) {
player1.pause();
play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
if (!player2.isPlaying()) {
// Stoping
player2.start();
play2.setImageResource(R.drawable.ic_baseline_pause_circle_filled_24);
} else {
// Playing
player2.pause();
play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
}
#Override
protected void onPause() {
super.onPause();
if (player1 != null) {
player1.pause();
play1.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
if (player2 != null) {
player2.pause();
play2.setImageResource(R.drawable.ic_baseline_play_circle_filled_24);
}
}
}
but I'm confused about what should I do in a situation like below
if the user open the app for the first time and just spent 30 sec and just pause the app(screen lock or in onPause) or just close the
app completely
This is impossible to do if your app is closed.My suggestion would be to create a service on another process that does this dialog such that even if the app process is closed,the service process will still be running unless it is stopped explicitly.
Defining a Process of a Service
The android:process field defines the name of the process where the
service is to run. Normally, all components of an application run in
the default process created for the application. However, a component
can override the default with its own process attribute, allowing you
to spread your application across multiple processes.
If the name assigned to this attribute begins with a colon (':'), the
service will run in its own separate process.
<service android:name="com.example.appName" android:process=":externalProcess" />
This is of course in the manifest file .
You might also need to show a system dialog thus you will need a system Alert Window permission i your manifest and request for the permision on runtime.
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
Then on runtime request like this:
public static void openOverlaySettings(Activity activity) {
final Intent intent = new Intent(Settings.ACTION_MANAGE_OVERLAY_PERMISSION,
Uri.parse("package:" + activity.getPackageName()));
try {
activity.startActivityForResult(intent, 6);
} catch (ActivityNotFoundException e) {
Log.e("Drawers permission :", e.getMessage());
}
}
To check if granted use :
if(!Settings.canDrawOverlays(context)) {
openOverlaySettings(context);
ok=false;
}
Then in your service you should create the dialog like below
View aldv= LayoutInflater.from(act).inflate(R.layout.your_layout,null);
ald=new AlertDialog.Builder(act,R.style.AppTheme)
.setView(aldv)
.setCancelable(true)
.create();
ald.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
I designed an online music player which streams file from my server and shows them in a recyclerView. when I click on the specific song it plays automatically, but when I go back to my recyclerview and I choose it again it doesn't play anymore and even duration of song becomes an insane number. I even tried to handle my media player onBackPressed() method or in OnRestart() or onResume() method. I'm confused. Please let me know about any suggestion.
Here's my code for player:
public class PlayerActivity extends AppCompatActivity implements View.OnClickListener {
private CircularMusicProgressBar cover;
private ImageButton playPause, rewind, forward, repeat, fav, download;
private TextView title, term, spendingTime, totalTime, emptyRec;
private Context context;
public static MediaPlayer mediaPlayer;
int i;
private Timer timer;
private Bundle extra;
Uri uri;
RecyclerView recyclerView;
RequestQueue requestQueue;
SuggestionAdapter suggestionAdapter;
LinearLayoutManager layoutManager;
List<Listening> list = new ArrayList<>();
String url = "https://www.learnhere.ir/listening.php";
AccessDataOnServer suggestionData;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player);
initFields();
playOnStart();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play_pause:
if (i == 1) {
i = 2;
playPause.setImageResource(R.drawable.ic_baseline_play);
mediaPlayer.pause();
} else {
i = 1;
playPause.setImageResource(R.drawable.ic_baseline_pause);
int b = mediaPlayer.getCurrentPosition();
mediaPlayer.seekTo(b);
mediaPlayer.start();
}
break;
case R.id.rewind:
Toast.makeText(context, "rewind", Toast.LENGTH_SHORT).show();
break;
case R.id.forward:
Toast.makeText(context, "forward", Toast.LENGTH_SHORT).show();
break;
case R.id.repeat:
Toast.makeText(context, "repeat", Toast.LENGTH_SHORT).show();
break;
case R.id.fav:
Toast.makeText(context, "fav", Toast.LENGTH_SHORT).show();
break;
case R.id.download:
Toast.makeText(context, "download", Toast.LENGTH_SHORT).show();
break;
}
}
public void initFields() {
i = 0;
context = this;
cover = findViewById(R.id.cover_progress);
playPause = findViewById(R.id.play_pause);
rewind = findViewById(R.id.rewind);
forward = findViewById(R.id.forward);
repeat = findViewById(R.id.repeat);
fav = findViewById(R.id.fav);
download = findViewById(R.id.download);
title = findViewById(R.id.title_tv);
term = findViewById(R.id.term_tv);
emptyRec = findViewById(R.id.empty_rec);
spendingTime = findViewById(R.id.spending_time);
totalTime = findViewById(R.id.total_time);
playPause.setOnClickListener(this);
rewind.setOnClickListener(this);
forward.setOnClickListener(this);
repeat.setOnClickListener(this);
fav.setOnClickListener(this);
download.setOnClickListener(this);
extra = getIntent().getExtras();
Picasso.get().load(extra.getString("cover")).into(cover);
title.setText(extra.getString("title"));
term.setText(extra.getString("term"));
timer = new Timer();
uri = Uri.parse(extra.getString("link"));
recyclerView = findViewById(R.id.suggestion_recycler);
requestQueue = Volley.newRequestQueue(context);
layoutManager = new LinearLayoutManager(context, LinearLayoutManager.VERTICAL, false);
suggestionAdapter = new SuggestionAdapter(list, context);
suggestionData = new AccessDataOnServer();
recyclerView.setAdapter(suggestionAdapter);
recyclerView.setLayoutManager(layoutManager);
suggestionData.getSuggestion(context, list, recyclerView, url, requestQueue);
if (list.size() <= 1) {
emptyRec.setVisibility(View.VISIBLE);
recyclerView.setVisibility(View.GONE);
} else {
emptyRec.setVisibility(View.GONE);
recyclerView.setVisibility(View.VISIBLE);
}
}
public void play() {
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
try {
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioAttributes(
new AudioAttributes
.Builder()
.setContentType(AudioAttributes.CONTENT_TYPE_MUSIC)
.build());
mediaPlayer.setDataSource(context, uri);
mediaPlayer.prepare();
mediaPlayer.start();
} catch (Exception e) {
e.printStackTrace();
}
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
getTime();
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
});
thread.start();
}
public void playOnStart() {
Toast.makeText(context, "Please wait until the audio plays...", Toast.LENGTH_SHORT).show();
play();
i = 1;
playPause.setImageResource(R.drawable.ic_baseline_pause);
}
public String millisecondToSecond(long millisecond) {
String finalTimerString = "";
String secondString = "";
String minuteString = "";
//convert total duration into time
int hour = (int) (millisecond / (1000 * 60 * 60));
int minute = (int) (millisecond % (1000 * 60 * 60) / (1000 * 60));
int second = (int) (millisecond % (1000 * 60 * 60) % (1000 * 60) / 1000);
//Add hours if there
if (hour > 0) {
finalTimerString = hour + ":";
}
//Prepending 0 to second if it's one digit
if (second < 10) {
secondString = "0" + second;
} else {
secondString = "" + second;
}
//Prepending 0 to minute if it's one digit
if (minute < 10) {
minuteString = "0" + minute;
} else {
minuteString = "" + minute;
}
finalTimerString = finalTimerString + minuteString + ":" + secondString;
//Return timer string
return finalTimerString;
}
public void getTime() {
timer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
// Without runOnUiThread we don't have access to modifiers like text view
runOnUiThread(new Runnable() {
#Override
public void run() {
long current = mediaPlayer.getCurrentPosition();
int i = (mediaPlayer.getCurrentPosition() * 100) / mediaPlayer.getDuration();
spendingTime.setText("" + millisecondToSecond(current));
cover.setValue(i);
int duration = mediaPlayer.getDuration();
String time = String.format(Locale.US, "%02d:%02d",
TimeUnit.MILLISECONDS.toMinutes(duration),
TimeUnit.MILLISECONDS.toSeconds(duration) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration)));
totalTime.setText(time);
}
});
}
}, 0, 1000);
}
#Override
public void onBackPressed() {
mediaPlayer.stop();
finish();
}
#Override
protected void onRestart() {
super.onRestart();
playOnStart();
}
Well I reviewed your codes and it seems you aren't using Media player class properly.
I made a few changes to each block of your codes. I hope it solves your problem.
First of all change the following scope:
public static MediaPlayer mediaPlayer;
To
MediaPlayer mediaPlayer = new MediaPlayer();
I made a method for your mediaPlayer and you should use it in your onCreate() :
private void prepareMediaPlayer() {
try {
mediaPlayer.setDataSource(context, uri);
mediaPlayer.prepare();
updateSeekBarTimer();
} catch (Exception e) {
e.printStackTrace();
}
}
A method to update your seekbar :
private void updateSeekBarTimer() {
try {
if (mediaPlayer.isPlaying()) {
total_time = mediaPlayer.getDuration();
current_time = mediaPlayer.getCurrentPosition();
totalTime.setText("" + utils.milliSecondsToTimer(total_time));
spendingTime.setText("" + utils.milliSecondsToTimer(current_time));
int progress = (int) (utils.getProgressPercentage(current_time, total_time));
seekBar.setProgress(progress);
Runnable runnable = new Runnable() {
#Override
public void run() {
updateSeekBarTimer();
}
};
handler.postDelayed(runnable, 1000);
}
} catch (Exception e) {
e.printStackTrace();
}
}
And finally you need an Interface to decide what happens when your track ends:
public class PlayerActivity extends AppCompatActivity implements View.OnClickListener, MediaPlayer.OnCompletionListener
#Override
public void onCompletion(MediaPlayer mp) {
handler.removeCallbacks(null);
playPause.setImageResource(R.drawable.ic_baseline_play);
if (rep) {
mediaPlayer.start();
playPause.setImageResource(R.drawable.ic_baseline_pause);
updateSeekBarTimer();
} else {
seekBar.setProgress(0);
totalTime.setText(R.string.zero_time);
spendingTime.setText(R.string.zero_time);
playPause.setImageResource(R.drawable.ic_baseline_play);
mediaPlayer.reset();
prepareMediaPlayer();
}
}
I am working on app that calculate time when specific app run, to save ram, I want to stop some of the threads by using check box. i want a command when I press the check box the thread stops even "if condition" is right"
the if conditon of detecting app :
if (MainActivity.tgbutton.isChecked())
{
if (packageName.equals("com.facebook.katana"))
{
if (f==1)
{
}
else
{
// Toast.makeText(getApplicationContext(),"fb on", Toast.LENGTH_SHORT).show();
f=1;
facebook = true;
startTimef = SystemClock.uptimeMillis();
customHandlerf.postDelayed(updateTimerThreadfacebook, 0);
}
}
else
{
if(f==1)
{
//Toast.makeText(getApplicationContext(),"fb off", Toast.LENGTH_SHORT).show();
facebook = false;
timeSwapBufff += timeInMillisecondsf;
customHandlerf.removeCallbacks(updateTimerThreadfacebook);
f=2;
}
}
}
the check box :
blabla.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
// what to write here to disable thread???
}
}
});
the thread itself :
private Runnable updateTimerThreadfacebook = new Runnable() {
public void run() {
if (facebook = true)
{
timeInMillisecondsf = SystemClock.uptimeMillis() - startTimef;
updatedTimef = timeSwapBufff + timeInMillisecondsf;
int secsf = (int) (updatedTimef / 1000);
int minsf = secsf / 60;
secsf = secsf % 60;
MainActivity.facebook.setText("" + minsf + ":" + String.format("%02d", secsf));
customHandlerf.postDelayed(this, 0);
}
}
};
you should use value on your run method
public class MyClass implements Runnable{
boolean signal=false;
public setisFinish(boolean sig)
{
signal = sig;
}
#Override
public void run()
{
if(!signal)
//Do SomeThing
}
public void foo()
{
System.out.println("foo");
}
}
and in your click listener
blabla.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (((CheckBox) v).isChecked()) {
myThread.setisFinish(true);
}
}
});
this code resume your thread and you can start it whenever you whant and if you want interrupt your thread use this code
myThread.interrupt();
Overwrap your Runnable object with Thread class:
private Thread updateTimerThreadfacebook = new Thread(new Runnable() {
public void run() {
if (facebook = true) {
timeInMillisecondsf = SystemClock.uptimeMillis() - startTimef;
updatedTimef = timeSwapBufff + timeInMillisecondsf;
int secsf = (int) (updatedTimef / 1000);
int minsf = secsf / 60;
secsf = secsf % 60;
MainActivity.facebook.setText("" + minsf + ":" + String.format("%02d", secsf));
customHandlerf.postDelayed(this, 0);
}
}
});
when you want to stop it use interrupt method.
updateTimerThreadfacebook.interrupt();
I've searched the internet far and wide about getting the UI to update in real-time in Android to no avail. I implemented an AysncTask class as most of the other posts suggested, but it's still not updating my UI in real-time like I want. It only updates after the program is done running. I've even been getting the "Skipped n frames. The application may be doing too much work in its main thread." error, which I don't understand because I'm trying to do these updates in the UI thread. About 5 seconds into running my program the screen turns black and stays like that until its done finishing. Any help would be much appreciated as I've been pulling my hair out on this one for awhile Here's my code.
EDIT: Solved. Removed the Thread.sleep(n) from my UI thread and added it to my AsyncTask. Thanks everyone!
Main class:
public class Home extends Activity {
// Declare objects
Button turingB, socratesB, voltaireB, descartesB, platoB;
int[] eating, thinking, hungry;
Philosopher socrates, turing, voltaire, descartes, plato;
Philosopher[] philosophers;
Chopstick[] chopsticks;
TextView info;
String value;
Context context;
int toastLength;
boolean turingHungry, socratesHungry, voltaireHungry, descartesHungry, platoHungry;
String running;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
// Instantiate objects (keep track of each button individually
context = getApplicationContext();
toastLength = Toast.LENGTH_SHORT;
info = (TextView) findViewById(R.id.textView1);
info.setText("Click Start to begin!");
socratesB = (Button) findViewById(R.id.button1);
descartesB = (Button) findViewById(R.id.button5);
platoB = (Button) findViewById(R.id.button4);
voltaireB = (Button) findViewById(R.id.button3);
turingB = (Button) findViewById(R.id.button2);
running = "false";
// Set all philosophers to thinking (blue)
// socratesB.setBackgroundColor(Color.BLUE);
// descartesB.setBackgroundColor(Color.BLUE);
// platoB.setBackgroundColor(Color.BLUE);
// voltaireB.setBackgroundColor(Color.BLUE);
// turingB.setBackgroundColor(Color.BLUE);
turingHungry = false;
socratesHungry = false;
voltaireHungry = false;
descartesHungry = false;
platoHungry = false;
//Button platoTempButton = (Button) findViewById(R.id.button4);
// Listen for buttons
OnClickListener pBtn = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
platoHungry = true;
}
};
//platoTempButton.setOnClickListener(pBtn);
OnClickListener tBtn = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
turingHungry = true;
}
};
OnClickListener sBtn = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
socratesHungry = true;
}
};
OnClickListener vBtn = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
voltaireHungry = true;
}
};
OnClickListener dBtn = new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
descartesHungry = true;
}
};
platoB.setOnClickListener(pBtn);
turingB.setOnClickListener(tBtn);
socratesB.setOnClickListener(sBtn);
voltaireB.setOnClickListener(vBtn);
descartesB.setOnClickListener(dBtn);
// Set arrays to count time spent eating, thinking, hungry
eating = new int[5];
thinking = new int[5];
hungry = new int[5];
// Create the chopsticks
chopsticks = new Chopstick[5];
for (int i = 0; i < 5; i ++)
{
chopsticks[i] = new Chopstick(i);
}
for (Chopstick chop: chopsticks)
{
chop.available = true;
}
// Create the philosophers
philosophers = new Philosopher[5];
philosophers[0] = new Philosopher(0, chopsticks[0], chopsticks[1], "Plato", platoB);
philosophers[1] = new Philosopher(1, chopsticks[1], chopsticks[2], "Turing", turingB);
philosophers[2] = new Philosopher(2, chopsticks[2], chopsticks[3], "Socrates", socratesB);
philosophers[3] = new Philosopher(3, chopsticks[3], chopsticks[4], "Voltaire", voltaireB);
philosophers[4] = new Philosopher(4, chopsticks[4], chopsticks[0], "Descartes", descartesB);
// Get sim time from user
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Simulation Time");
alert.setMessage("Please length of time for the simulation to run (in seconds)");
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
value = String.valueOf(input.getText());
}
});
alert.show();
// Get info
Bundle extras = getIntent().getExtras();
if (extras != null)
{
running = extras.getString("runApp");
value = extras.getString("numToRun");
}
// Run app
if (running.equals("true"))
{
System.out.println("RUNNING!!!");
run(value);
}
}
public void run(String length)
{
int num = Integer.parseInt(length);
// Run num times
for (int i = 0; i < num; i++)
{
try {
// Pass current index, and data arrays to step method
step(i, eating, thinking, hungry);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
// Print out some data
for (int j = 0; j < 5; j++)
{
System.out.println("Philosopher " + j + " ate: " + eating[j]);
System.out.println("Philosopher " + j + " thought: " + thinking[j]);
System.out.println("Philosopher " + j + " was hungry: " + hungry[j]);
}
running = "false";
}
// Run simulation n times (n specified by the user)
public void startSim(View v)
{
Intent my_intent = new Intent(this, Home.class);
my_intent.putExtra("runApp", "true");
my_intent.putExtra("numToRun", value);
startActivity(my_intent);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.home, menu);
return true;
}
// Reset simulation
public void reset(View v)
{
Intent my_intent = new Intent(this, Home.class);
startActivity(my_intent);
}
// Return hunger status of philosopher
public boolean isHungry(String name) {
if (name.equals("Voltaire"))
return voltaireHungry;
else if (name.equals("Socrates"))
return socratesHungry;
else if (name.equals("Plato"))
return platoHungry;
else if (name.equals("Turing"))
return turingHungry;
else if (name.equals("Descartes"))
return descartesHungry;
else
return false;
}
// Step method for simulation
// Takes the current index and each of the data arrays
public void step(int i, int[] eating, int[] thinking, int[] hungry) throws InterruptedException
{
// Make random number
Random randomGenerator = new Random();
int num = randomGenerator.nextInt(10);
// Randomly set a philosopher isFull to false (hungry) (10% chance for each to become hungry if not specified by the user)
if (isHungry(philosophers[0].name))
philosophers[0].isFull = false;
if (num == 1 || isHungry(philosophers[1].name))
philosophers[1].isFull = false;
if (num == 2 || isHungry(philosophers[2].name))
philosophers[2].isFull = false;
if (num == 3 || isHungry(philosophers[3].name))
philosophers[3].isFull = false;
if (num == 4 || isHungry(philosophers[4].name))
philosophers[4].isFull = false;
// For each philosopher
for (Philosopher phil: philosophers)
{
// Print current info
System.out.println("PHIL: " + phil.name + " NUM: " + num + " RIGHT: " + phil.rightChopstick.available + " LEFT: " + phil.leftChopstick.available);
// Temp id var
int tempId = phil.id;
// If philosopher is hungry, try to eat
if (phil.isFull == false)
{
// Try to eat only if both chopsticks are available
if (phil.rightChopstick.pickUp(phil.name) && phil.leftChopstick.pickUp(phil.name))
{
// Change button color
new Background(phil.button).execute((long) 1);
//Toast.makeText(context, phil.name + " is eating.", toastLength).show();
// Increment time spent eating
eating[tempId]++;
}
// Check to see if the philosopher is already eating (has both chopsticks)
else if (phil.rightChopstick.who.equals(phil.name) && phil.leftChopstick.who.equals(phil.name))
{
//Toast.makeText(context, phil.name + " is eating.", toastLength).show();
new Background(phil.button).execute((long) 1);
// Increment eating
eating[tempId]++;
// 30% chance to stop eating
if (num >= 5 && num <=7)
{
// Put down chopsticks
phil.rightChopstick.putDown();
phil.leftChopstick.putDown();
// Stop eating
phil.isFull = true;
}
}
// Hungry
else
{
// Change button color
new Background(phil.button).execute((long) 3);
//Toast.makeText(context, phil.name + " is hungry.", toastLength).show();
// Increment time spent hungry
hungry[tempId]++;
}
}
// Thinking
else
{
new Background(phil.button).execute((long) 2);
//Toast.makeText(context, phil.name + " is thinking.", toastLength).show();
// Increment time spent thinking
thinking[tempId]++;
}
Thread.sleep(1000);
}
// Make each step count as 1 second (1000 miliseconds)
System.out.println("--------------------------------------------------------------");
Thread.sleep(5000);
}
}
Background class (AsyncTask):
public class Background extends AsyncTask<Long, Void, Void>
{
// Variables
String color;
Button button;
public Background(Button button)
{
this.button = button;
}
#Override
protected Void doInBackground(Long... params) {
// Get which color the button needs to be
try
{
// Change the color based on the value passed in
if (params[0] == 3)
{
color = "RED";
}
else if (params[0] == 2)
{
color = "BLUE";
}
else if (params[0] == 1)
{
color = "GREEN";
}
}
catch (Exception e)
{
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// Set button to that color
System.out.println("Updating color in real time...");
button.setBackgroundColor(Color.parseColor(color));
}
#Override
protected void onPreExecute() {
}
#Override
protected void onProgressUpdate(Void... values) {
}
}
Here is one problem
Thread.sleep(1000);
and here is another
Thread.sleep(5000);
these are both making the UI sleep for a total of 6 seconds. You almost never want to call sleep() on the UI Thread. You can do this in doInBackground() or anywhere else that runs on a background Thread.
Edit
You don't set your Listeners. For example:
platoB.setOnClickListener(new pBtn());
Progress can be set with publishProgress in your asynctask, you get a call to onProgressUpdate in the UI thread.
I have a runnable timer that update a textview every second, when the activity is onStop (or called into the background) the timer continues to run. The issue i am having is that when i re-launch the activity it starts the same timer again, so the numbers are going up twice as fast as they should. I have it coded so that it will kill both timers before it restarts them but i believe that when the activity is started again the timers are not being killed. Here is an example of my code :
t.cancel();
cd.cancel();
t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
That is only a small part but it should kill the timer (t.cancel();) then start a new one, this only happens when the activity is stopped and then restarted. please help this issue is driving me absolutely insane.
=========================================================
For the brave souls willing to read alot, here is my entire activity that i am having the issue with:
public class PayTracker extends Activity {
private static double Reserve;
private static int Reserve1;
public static double money;
public static double counter;
private static int go;
private static int countdown;
public static int convert;
public static double HW;
public static double OTW;
public static double HPD;
public static double DPPS;
public Timer t = new Timer();
public Timer cd = new Timer();
public static String mcountdown = "Time till overtime";
public static String mmoney = "total cash";
public static String mcounter = "ticks";
public static String mReserve = "building total";
public static String mReserve1 = "building total 2";
public static String mHW;
public static String mOTW;
public static String mHPD;
public static String mDPPS;
public static String mgo;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pay_tracker);
getActionBar().setDisplayHomeAsUpEnabled(true);
// Receive messages from options page
double pHW, pOTW, pHPD;
Intent intent = getIntent();
pHW = intent.getDoubleExtra(Options.MESSAGE_HW, 0);
pOTW = intent.getDoubleExtra(Options.MESSAGE_OTW, 0);
pHPD = intent.getDoubleExtra(Options.MESSAGE_HPD, 0);
if(pHW != 0){
HW = pHW;
OTW = pOTW;
HPD = pHPD;
}
// Color buttons
Button buttonc = (Button) findViewById(R.id.clockin);
buttonc.getBackground().setColorFilter(0xFF00FF00, PorterDuff.Mode.MULTIPLY);
Button buttond = (Button) findViewById(R.id.clockout);
buttond.getBackground().setColorFilter(0xFFFF0000, PorterDuff.Mode.MULTIPLY);
// go = 0;
// Calculate pay per second
final double PPS = (HW/3600);
DPPS = (PPS/50);
final double OTPPS = (OTW/3600);
final double DOTPPS = (OTPPS/50);
final double HPDPS = (HPD*3600);
final double DHPDPS = (HPDPS*50);
// Display
final TextView t1 = (TextView) findViewById(R.id.yourpay);
t1.setTextColor(Color.parseColor("#008000"));
final TextView t2 = (TextView) this.findViewById(R.id.payper);
final String result2 = String.format("%.8f", OTPPS);
final String result = String.format("%.8f", PPS);
// if(go != 1){
// go = 1;
// if(go == 1){
t.cancel();
cd.cancel();
// go = 0;
// }
// if(go == 0){
// go = 1;
t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
if(DHPDPS==0){
money = (DPPS+Reserve);
Reserve = (money);
String end = String.format("%1f", money);
t1.setText("$" + end);
}else if(counter > DHPDPS && DOTPPS != 0 && DHPDPS != 0){
money = (DOTPPS+Reserve);
Reserve = (money);
String end = String.format("%1f", money);
t1.setText("$" + end);
} else{
money = (DPPS+Reserve);
Reserve = (money);
String end = String.format("%1f", money);
t1.setText("$" + end);
}
counter++;
//if(counter == 3000)
// t.cancel();
// Display pay per second
if(counter <= DHPDPS || DHPDPS == 0){
t2.setText("Your pay per second is: $"+result);
}else{
t2.setText("Your pay per second is: $"+result2);
}
}
});
}
}, 20, 20);
// Make countdown to overtime display
final Intent intent1 = new Intent(this, PayTracker.class);
// Create the notification
final Notification notification = new Notification(R.drawable.ic_launcher, "Click here to check your pay!", System.currentTimeMillis());
// Create an Intent for the notification to launch
// Create a PendingIntent for the associated Intent
final PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent1, 0);
cd = new Timer();
final TextView count = (TextView) findViewById(R.id.countdown);
convert = (int)HPDPS;
cd.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run(){
countdown = (convert - Reserve1);
int hours = (countdown/3600);
if(OTPPS != 0 && HPDPS != 0){
count.setText("Seconds Remaining to Overtime: " + countdown + "\nAbout " + hours + " Hours");
Reserve1++;
}
// Set the notification's details
final String end = String.format("%.6f", money);
notification.setLatestEventInfo(getApplicationContext(), "Your Current Pay:", "$"+end, pendingIntent);
// Submit the notification to the system
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(0, notification);
}
});
}
}, 1000, 1000);
// }
// }
final Button b = (Button) findViewById(R.id.clockout);
b.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
if(go == 1)
go = 0;
if (t != null){
t.cancel();
cd.cancel();
}
}
});
}
public void onRestoreInstanceState(Bundle savedInstanceState) {
// Always call the superclass so it can restore the view hierarchy
super.onRestoreInstanceState(savedInstanceState);
// Restore value of members from saved state
countdown = savedInstanceState.getInt(mcountdown);
Reserve = savedInstanceState.getInt(mReserve);
money = savedInstanceState.getInt(mmoney);
counter = savedInstanceState.getInt(mcounter);
Reserve1 = savedInstanceState.getInt(mReserve1);
HW = savedInstanceState.getInt(mHW);
OTW = savedInstanceState.getInt(mOTW);
HPD = savedInstanceState.getInt(mHPD);
DPPS = savedInstanceState.getInt(mDPPS);
go = savedInstanceState.getInt(mgo);
}
#Override
public void onStart(){
super.onStart();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_pay_tracker, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
}
return super.onOptionsItemSelected(item);
}
public void sendMessage(View view) {
// Calculate pay per second
final double PPS = (HW/3600);
DPPS = (PPS/50);
final double OTPPS = (OTW/3600);
final double DOTPPS = (OTPPS/50);
final double HPDPS = (HPD*3600);
final double DHPDPS = (HPDPS*50);
// Display
final TextView t1 = (TextView) findViewById(R.id.yourpay);
t1.setTextColor(Color.parseColor("#008000"));
final TextView t2 = (TextView) this.findViewById(R.id.payper);
final String result2 = String.format("%.8f", OTPPS);
final String result = String.format("%.8f", PPS);
//if(go != 1){
// go = 1;
t.cancel();
cd.cancel();
t = new Timer();
t.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run() {
if(DHPDPS==0){
money = (DPPS+Reserve);
Reserve = (money);
String end = String.format("%1f", money);
t1.setText("$" + end);
}else if(counter > DHPDPS && DOTPPS != 0 && DHPDPS != 0){
money = (DOTPPS+Reserve);
Reserve = (money);
String end = String.format("%1f", money);
t1.setText("$" + end);
} else{
money = (DPPS+Reserve);
Reserve = (money);
String end = String.format("%1f", money);
t1.setText("$" + end);
}
counter++;
if(counter == 3000)
t.cancel();
// Display pay per second
if(counter <= DHPDPS || DHPDPS == 0){
t2.setText("Your pay per second is: $"+result);
}else{
t2.setText("Your pay per second is: $"+result2);
}
}
});
}
}, 20, 20);
// Make countdown to overtime display
final Intent intent1 = new Intent(this, PayTracker.class);
// Create the notification
final Notification notification = new Notification(R.drawable.ic_launcher, "Click here to check your pay!", System.currentTimeMillis());
// Create an Intent for the notification to launch
// Create a PendingIntent for the associated Intent
final PendingIntent pendingIntent = PendingIntent.getActivity(getApplicationContext(), 0, intent1, 0);
cd = new Timer();
final TextView count = (TextView) findViewById(R.id.countdown);
convert = (int)HPDPS;
cd.schedule(new TimerTask() {
#Override
public void run() {
runOnUiThread(new Runnable() {
public void run(){
countdown = (convert - Reserve1);
int hours = (countdown/3600);
if(OTPPS != 0 && HPDPS != 0){
count.setText("Seconds Remaining to Overtime: " + countdown + "\nAbout " + hours + " Hours");
Reserve1++;
}
// Set the notification's details
final String end = String.format("%.6f", money);
notification.setLatestEventInfo(getApplicationContext(), "Your Current Pay:", "$"+end, pendingIntent);
// Submit the notification to the system
((NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE)).notify(0, notification);
}
});
}
}, 1000, 1000);
//}
}
#Override
public void onSaveInstanceState(Bundle savedInstanceState) {
// Save the user's current game state
savedInstanceState.putInt(mcountdown, countdown);
savedInstanceState.putDouble(mReserve, Reserve);
savedInstanceState.putDouble(mmoney, money);
savedInstanceState.putDouble(mcounter, counter);
savedInstanceState.putDouble(mReserve1, Reserve1);
savedInstanceState.putDouble(mHW, HW);
savedInstanceState.putDouble(mOTW, OTW);
savedInstanceState.putDouble(mHPD, HPD);
savedInstanceState.putDouble(mDPPS, DPPS);
savedInstanceState.putInt(mgo, go);
// Always call the superclass so it can save the view hierarchy state
super.onSaveInstanceState(savedInstanceState);
}
#Override
public void onDestroy() {
super.onDestroy();
if(t != null)
t.cancel();
if(cd != null)
cd.cancel();
}
}
This is one way to get around that.
static Timer mTimer = null;
onCreate() {
if (mTimer == null)
mTimer = new Timer();
} else {
// You shouldn't have to do nothing because your timer should be running
}
}
Note that there are several issues in general here. The static is basically saying just to create one instance of that object. As a side effect it also tries to reclaim the same memory address. Either way, once your app is in the background it can be cleaned up by the system at any time so your not guaranteed to get your Timer back. There are a bunch of other ways to get around that, but that is out of scope for this question.