Music plays only one time from server in online music player - java

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();
}
}

Related

how to show a dialog after 1 or 2 min after opning app for first time

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);

CountDownTimer adds time with each loop

I'm working on a fragment that includes two timers that take user input. Timer B is linked to timer A such that when timer A is started, so is timer B. The purpose of timer A is to count down once. The purpose of timer B is to count down, beep once at 0, reset to the original value, and repeat. The problem I'm having is that when timer B reaches 0, it doesn't reset and start counting down right away. The timer seems to be delayed further by calling ToneGenerator. This results in the two timers becoming more and more out of sync each time timer B resets.
For example, say timer A is set to 10 seconds and timer B is set to 2 seconds.
-The timers are started-
timer A:10, 9, 8, 7, 6, 5, 4, 3, 2, 1, 0
timer B: 2, 1, 0, 2, 1, 0, 2, 1, 0, 2, 1
The timer only beeps 3 times (when timer B is at 0,) when it should beep 5 times (5 sets of 2 second intervals = 10 seconds: the value of timer A.) In other words, I'd like timer B to beep when timer A is at 8, 6, 4, 2, and 0.
How might I accomplish this?
I've consulted the forums, YT, and have tried playing around with the value for millisInFuture.
Fragment
public class fragmentdro extends Fragment {
private EditText session_edit_text;
private EditText dro_edit_text;
private TextView session_text_view;
private TextView dro_text_view;
private Button session_start_button;
private Button dro_start_button;
private Button session_reset_button;
private Button dro_reset_button;
private Button session_set_button;
private Button dro_set_button;
private CountDownTimer sessionTimer;
private CountDownTimer droTimer;
private boolean SessionTimerRunning;
private boolean DROTimerRunning;
private long SessionStartTimeInMillis;
private long DROStartTimeInMillis;
private long SessionTimeLeftInMillis = SessionStartTimeInMillis;
private long DROTimeLeftInMillis = DROStartTimeInMillis;
private long SessionEndTime;
private long DROEndTime;
View View;
public View onCreateView(#NonNull LayoutInflater inflater, #NonNull ViewGroup container, #NonNull Bundle savedInstanceState) {
View = inflater.inflate(R.layout.dro_fragment, container, false);
session_edit_text = View.findViewById(R.id.session_edit_text);
dro_edit_text = View.findViewById(R.id.dro_edit_text);
session_text_view = View.findViewById(R.id.session_text_view);
dro_text_view = View.findViewById(R.id.dro_text_view);
session_start_button = View.findViewById(R.id.session_start_button);
dro_start_button = View.findViewById(R.id.dro_start_button);
session_reset_button = View.findViewById(R.id.session_reset_button);
dro_reset_button = View.findViewById(R.id.dro_reset_button);
session_set_button = View.findViewById(R.id.session_set_button);
dro_set_button = View.findViewById(R.id.dro_set_button);
InputMethodManager imm = (InputMethodManager)getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
ToneGenerator toneGenerator = new ToneGenerator(AudioManager.STREAM_ALARM, 100);
Timer A
session_set_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(android.view.View view) {
String Sessioninput = session_edit_text.getText().toString();
if (Sessioninput.length() == 0) {
Toast.makeText(getActivity(), "Fill it in", Toast.LENGTH_SHORT).show();
return;
}
long millisInput = Long.parseLong(Sessioninput) * 1000;
if (millisInput == 0) {
Toast.makeText(getActivity(), "Please enter a positive number", Toast.LENGTH_SHORT).show();
return;
}
setSessionTime(millisInput);
session_edit_text.setText("");
imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
}
});
session_start_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(android.view.View view) {
if (SessionTimerRunning) {
pauseSessionTimer();
resetDROTimer();
} else {
startSessionTimer();
startDROTimer();
}
}
});
session_reset_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(android.view.View view) {
if (SessionTimerRunning) {
resetSessionTimer();
} else {
resetSessionTimer();
}
}
});
public void setSessionTime(long milliseconds) {
SessionStartTimeInMillis = milliseconds;
resetSessionTimer();
}
public void startSessionTimer() {
SessionEndTime = System.currentTimeMillis() + SessionTimeLeftInMillis;
sessionTimer = new CountDownTimer(SessionTimeLeftInMillis, 100) {
#Override
public void onTick(long millisUntilFinished) {
SessionTimeLeftInMillis = millisUntilFinished;
updateSessionText();
}
#Override
public void onFinish() {
SessionTimerRunning = false;
session_start_button.setText("Start");
session_start_button.setVisibility(android.view.View.INVISIBLE);
session_reset_button.setVisibility(android.view.View.VISIBLE);
}
}.start();
SessionTimerRunning = true;
session_start_button.setText("Pause");
}
public void pauseSessionTimer() {
sessionTimer.cancel();
droTimer.cancel();
SessionTimerRunning = false;
DROTimerRunning = false;
session_start_button.setText("Start");
updateSessionText();
}
public void resetSessionTimer() {
if (SessionTimerRunning) {
sessionTimer.cancel();
SessionTimeLeftInMillis = (SessionStartTimeInMillis);
updateSessionInterface();
startSessionTimer();
} else {
SessionTimeLeftInMillis = (SessionStartTimeInMillis);
updateSessionText();
updateSessionInterface();
session_reset_button.setVisibility(android.view.View.VISIBLE);
session_start_button.setVisibility(android.view.View.VISIBLE);
}
}
public void updateSessionText() {
int minutes = (int) (SessionTimeLeftInMillis/1000/60);
int seconds = (int) (SessionTimeLeftInMillis/1000)%60;
String timeLeftFormatted = String.format(Locale.getDefault(),
timeLeftFormatted = String.format(Locale.getDefault(), "%2d:%02d", minutes, seconds));
session_text_view.setText(timeLeftFormatted);
}
public void updateSessionInterface() {
if (SessionTimerRunning) {
session_edit_text.setVisibility(android.view.View.INVISIBLE);
session_set_button.setVisibility(android.view.View.INVISIBLE);
session_reset_button.setVisibility(android.view.View.VISIBLE);
session_start_button.setText("Pause");
} else {
session_edit_text.setVisibility(android.view.View.VISIBLE);
session_set_button.setVisibility(android.view.View.VISIBLE);
session_reset_button.setVisibility(android.view.View.VISIBLE);
session_start_button.setText("Start");
}
}
Timer B
dro_set_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(android.view.View view) {
String DROinput = dro_edit_text.getText().toString();
if (DROinput.length() == 0) {
Toast.makeText(getActivity(), "Fill it in", Toast.LENGTH_SHORT).show();
return;
}
long millisInput = Long.parseLong(DROinput) * 1000;
if (millisInput == 0) {
Toast.makeText(getActivity(), "Please enter a positive number", Toast.LENGTH_SHORT).show();
return;
}
setDROTime(millisInput);
dro_edit_text.setText("");
imm.hideSoftInputFromWindow(getView().getWindowToken(), 0);
}
});
dro_start_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(android.view.View view) {
if (DROTimerRunning) {
pauseDROTimer();
} else {
startDROTimer();
}
}
});
dro_reset_button.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(android.view.View view) {
if (DROTimerRunning) {
resetDROTimer();
} else {
resetDROTimer();
}
}
});
return View;
}
public void setDROTime(long milliseconds) {
DROStartTimeInMillis = milliseconds;
resetDROTimer();
}
public void startDROTimer() {
DROEndTime = System.currentTimeMillis() + DROTimeLeftInMillis;
droTimer = new CountDownTimer(DROTimeLeftInMillis, 100) {
#Override
public void onTick(long millisUntilFinished) {
DROTimeLeftInMillis = millisUntilFinished;
updateDROText();
}
#Override
public void onFinish() {
ToneGenerator toneGenerator = new ToneGenerator(AudioManager.STREAM_ALARM, 400);
toneGenerator.startTone(ToneGenerator.TONE_CDMA_ALERT_CALL_GUARD, 200);
DROTimerRunning = false;
DROTimeLeftInMillis = DROStartTimeInMillis;
updateDROText();
updateDROInterface();
startDROTimer();
}
}.start();
DROTimerRunning = true;
dro_start_button.setText("Pause");
}
public void pauseDROTimer() {
droTimer.cancel();
DROTimerRunning = false;
dro_start_button.setText("Start");
updateDROText();
}
public void resetDROTimer() {
if (DROTimerRunning) {
droTimer.cancel();
DROTimeLeftInMillis = (DROStartTimeInMillis);
updateDROInterface();
startDROTimer();
} else {
DROTimeLeftInMillis = (DROStartTimeInMillis);
updateDROText();
updateDROInterface();
dro_reset_button.setVisibility(android.view.View.VISIBLE);
dro_start_button.setVisibility(android.view.View.VISIBLE);
}
}
public void updateDROText() {
int seconds = (int) (DROTimeLeftInMillis/1000)%60;
String timeLeftFormatted = String.format(Locale.getDefault(),
timeLeftFormatted = String.format(Locale.getDefault(), ":%02d", seconds));
dro_text_view.setText(timeLeftFormatted);
}
public void updateDROInterface() {
if (DROTimerRunning) {
dro_edit_text.setVisibility(android.view.View.INVISIBLE);
dro_set_button.setVisibility(android.view.View.INVISIBLE);
dro_reset_button.setVisibility(android.view.View.VISIBLE);
dro_start_button.setText("Pause");
} else {
dro_edit_text.setVisibility(android.view.View.VISIBLE);
dro_set_button.setVisibility(android.view.View.VISIBLE);
dro_reset_button.setVisibility(android.view.View.VISIBLE);
dro_start_button.setText("Start");
}
}
#Override
public void onStop() {
super.onStop();
SharedPreferences preferences = this.getActivity().getSharedPreferences("prefs", Context.MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putLong("SessionStartTimeInMillis", SessionStartTimeInMillis);
editor.putLong("DROStartTimeInMillis", DROStartTimeInMillis);
editor.putLong("MillisLeft", SessionTimeLeftInMillis);
editor.putLong("DROMillisLeft", DROTimeLeftInMillis);
editor.putBoolean("TimerRunning", SessionTimerRunning);
editor.putBoolean("DROTimerRunning", DROTimerRunning);
editor.putLong("EndTime", SessionEndTime);
editor.putLong("DROEndTime", DROEndTime);
if (sessionTimer !=null); {
sessionTimer.cancel();
}
}
#Override
public void onStart() {
super.onStart();
SharedPreferences preferences = this.getActivity().getSharedPreferences("prefs", Context.MODE_PRIVATE);
SessionStartTimeInMillis = preferences.getLong("SessionStartTimeInMillis", 0);
SessionTimeLeftInMillis = preferences.getLong("MillisLeft", SessionTimeLeftInMillis);
SessionTimerRunning = preferences.getBoolean("TimerRunning", false);
DROStartTimeInMillis = preferences.getLong("DROStartTimeInMillis", 0);
DROTimeLeftInMillis = preferences.getLong("DROMillisLeft", DROTimeLeftInMillis);
DROTimerRunning = preferences.getBoolean("DROTimerRunning", false);
updateSessionText();
updateSessionInterface();
updateDROText();
updateDROInterface();
if (SessionTimerRunning) {
SessionEndTime = preferences.getLong("EndTime", 0);
SessionTimeLeftInMillis = SessionEndTime - System.currentTimeMillis();
if (SessionTimeLeftInMillis <0) {
SessionTimeLeftInMillis = 0;
SessionTimerRunning = false;
} else {
startSessionTimer();
}
}
if (DROTimerRunning) {
DROEndTime = preferences.getLong("EndTime", 0);
DROTimeLeftInMillis = DROEndTime - System.currentTimeMillis();
if (DROTimeLeftInMillis <0) {
DROTimeLeftInMillis = 0;
DROTimerRunning = false;
} else {
startDROTimer();
}
}
}
}

How to launch a dialog when app is in onStop() state?

I'm creating a timer app that utilizes a thread. When I exit the app using the home button the timer is running fine. Usually, when the time is up a dialog is launched that asks the user for some input. This works completely fine if the app is in its onResume() state, however when the app is in its onStop() state the dialog will not launch and an error is thrown.
java.lang.IllegalStateException: Can not perform this action after onSaveInstanceState
How can I make it so that when the time is up and the app is NOT in the foreground the dialog is still launched. My initial thought was to save the time remaining in the bundle, but the time remaining is changing for every single tick. Then I thought about storing a boolean in the bundle mTimeRunning. However, when the time is up this value must also change. So now I'm drawing a blank. What can I possibly do so that the dialog is launched when the app is not in the foreground?
TimerActivity.java
public class TimerActivity extends AppCompatActivity implements TimeDialogFragment.sendMinutes,
TimeFinishDialogFragment.sendResponse, BreakFinishDialogFragment.userResponse {
// Variable to log activity state
private static final String TAG = "TimerActivity";
private static final boolean DEBUG = true;
// ^^ Variable used to log acitivty state
private Handler mHandler;
private Runnable mRunnable;
//private static final long START_TIME_MILLISECONDS = 600000;
// Below start time is for development purposes only
private static long mStartTime = 10000;
private long mTimeRemaining = mStartTime;
private boolean mTimeRunning;
private boolean mBreakTime = false;
private ProgressBar mTimeBar;
private TextView mTime;
private Button mStartPause;
private Button mSetTime;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_timer);
if(DEBUG) Log.d(TAG, "+ onCreate() +");
mHandler = new Handler();
mTimeBar = findViewById(R.id.time_bar);
mTime = findViewById(R.id.text_view_time);
mStartPause = findViewById(R.id.button_start_pause);
mSetTime = findViewById(R.id.button_set_time);
updateCountDownText();
mTimeBar.setMax((int) mTimeRemaining);
mSetTime.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
//FragmentManager manager = getSupportFragmentManager();
DialogFragment setTime = new TimeDialogFragment();
setTime.show(getFragmentManager(),"SET_TIME_DIALOG");
}
});
mStartPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(mTimeRunning){
//pauseTimer();
mTimeRunning = false;
mStartPause.setText("Start");
mHandler.removeCallbacks(mRunnable);
}else{
//startTimer();
timer();
}
}
});
}
// Using a handler + anon runnable
private void timer(){
mRunnable = new Runnable() {
#Override
public void run() {
mTimeRunning = true;
mStartPause.setText("Pause");
mTimeRemaining = mTimeRemaining - 1000;
updateCountDownText();
mTimeBar.incrementProgressBy(1000);
if(mTimeRemaining > 0) {
mHandler.postDelayed(this, 1000);
}else{
// if breaktime is false
if(!mBreakTime) {
DialogFragment dialog = new TimeFinishDialogFragment();
dialog.show(getFragmentManager(),"TIME_FINISH_DIALOG");
mTimeRunning = false;
}else{
// launch break time up dialog.
mBreakTime = false;
DialogFragment dialog = new BreakFinishDialogFragment();
dialog.show(getFragmentManager(), "BREAK_FINSIH_DIALOG");
}
}
}
};
mHandler.postDelayed(mRunnable,1000);
}
public void updateCountDownText(){
int min = (int) (mTimeRemaining / 1000) / 60;
int sec = (int) (mTimeRemaining / 1000) % 60;
String formattedString = String.format(Locale.getDefault(), "%02d:%02d", min, sec);
mTime.setText(formattedString);
}
public void setCountDownText(long time){
int min = (int) (time / 1000) / 60;
int sec = (int) (time / 1000) % 60;
String formattedString = String.format(Locale.getDefault(), "%02d:%02d", min, sec);
mTime.setText(formattedString);
}
#Override
public void userTime(int minutes) {
TimerActivity.mStartTime = (minutes * 60) * 1000;
mTimeRemaining = TimerActivity.mStartTime;
mTimeBar.setMax((int) mTimeRemaining);
setCountDownText(mTimeRemaining);
}
#Override
public void sendResponse(int val) {
if(val == -1){
mTimeRemaining = TimerActivity.mStartTime;
mTimeBar.setMax((int) mTimeRemaining);
updateCountDownText();
mTimeBar.setProgress(0);
mStartPause.setText("Start");
}else if(val == 1) {
mBreakTime = true;
mTimeRemaining = 15000;
mTimeBar.setMax((int) mTimeRemaining);
setCountDownText(mTimeRemaining);
mTimeBar.setProgress(0);
mStartPause.setVisibility(View.INVISIBLE);
timer();
}else {
mTimeRemaining = TimerActivity.mStartTime;
mTimeBar.setMax((int) mTimeRemaining);
updateCountDownText();
mTimeBar.setProgress(0);
timer();
}
}
#Override
public void userResponse(int val) {
if(val < 0) {
// user clicked cance
mTimeRemaining = TimerActivity.mStartTime;
mTimeBar.setMax((int) mTimeRemaining);
updateCountDownText();
mTimeBar.setProgress(0);
mStartPause.setText("Start");
}else {
mTimeRemaining = TimerActivity.mStartTime;
mTimeBar.setMax((int) mTimeRemaining);
updateCountDownText();
mTimeBar.setProgress(0);
timer();
}
mStartPause.setVisibility(View.VISIBLE);
}
TimeFinishedDialog.java
public class TimeFinishDialogFragment extends DialogFragment implements View.OnClickListener{
private Button mCancel;
private Button mSkip;
private Button mStartBreak;
private sendResponse mResponse;
interface sendResponse{
void sendResponse(int val);
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//return super.onCreateDialog(savedInstanceState);
View view = LayoutInflater.from(getActivity()).inflate(R.layout.time_finish_dialog_fragment, null, false);
mCancel = view.findViewById(R.id.button_cancel);
mSkip = view.findViewById(R.id.button_skip);
mStartBreak = view.findViewById(R.id.button_start_break);
mCancel.setOnClickListener(this);
mSkip.setOnClickListener(this);
mStartBreak.setOnClickListener(this);
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setView(view)
.setTitle("Start Break?");
AlertDialog dialog = builder.create();
dialog.setContentView(view);
return dialog;
}
#Override
public void onClick(View view) {
switch(view.getId()){
case R.id.button_cancel:
mResponse.sendResponse(-1);
getDialog().dismiss();
break;
case R.id.button_skip:
mResponse.sendResponse(0);
getDialog().dismiss();
break;
case R.id.button_start_break:
mResponse.sendResponse(1);
getDialog().dismiss();
break;
default:
break;
}
}
#Override
public void onAttach(Context context) {
super.onAttach(context);
try{
mResponse = (sendResponse) getActivity();
}catch (ClassCastException e){
System.out.println("Error: " + e);
}
}
}
when the time is up and the app is NOT in the foreground the dialog is still launched
You should not be doing this since this will interrupt the user from doing other work which they might be doing at that time and this can be irritating.
What can I possibly do so that the dialog is launched when the app is not in the foreground?
You can show the dialog only the user is actively using your application or you can fall back to show a notification when the user is not using the app.
And if you desperately want to show a dialog, you can try a dialog themed activity

How to calculate reaction time?

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();

Create stream from audio file in Android

The use case is this, in Android (above Kit Kat): open a stream from an audio file, get its properties, modify the memory buffer and play the result.
I would like to know how to 1) properly create the stream from the audio file; 2) get its properties (channels, encoding, length) like for the javax.sound.sampled.AudioFormat, but using methods from the android.media framework.
I know how to build a stream from binary, add audio properties to it then playing it. I would like to do the other way and extract these properties (channels, encoding) from the existing sound file header, using latest classes of the Android framework.
Thanks!
Here is full streaming class use this :
public class MainActivity extends Activity implements OnClickListener,
OnTouchListener, OnCompletionListener, OnBufferingUpdateListener {
private Button btn_play, btn_pause, btn_stop;
private SeekBar seekBar;
private MediaPlayer mediaPlayer;
private int lengthOfAudio;
private final String URL = "http://songspkcompilations.com/indian/soulfularijit/%5BSongs.PK%5D%2012%20-%20Mickey%20Virus%20-%20Tose%20Naina.mp3";
private static final int MINUTES_IN_AN_HOUR = 60;
private static final int SECONDS_IN_A_MINUTE = 60;
private final Handler handler = new Handler();
private boolean is_loading = true;
private boolean is_stopped = false;
private final Runnable r = new Runnable() {
#Override
public void run() {
updateSeekProgress();
}
};
private TextView txtTime;
private ProgressBar musicProgress;
private ImageView artistImg;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initialize_Controls();
}
private void initialize_Controls() {
btn_play = (Button) findViewById(R.id.btn_play);
btn_play.setOnClickListener(this);
btn_pause = (Button) findViewById(R.id.btn_pause);
btn_pause.setOnClickListener(this);
btn_pause.setEnabled(false);
btn_stop = (Button) findViewById(R.id.btn_stop);
btn_stop.setOnClickListener(this);
btn_stop.setEnabled(false);
musicProgress = (ProgressBar) findViewById(R.id.progress);
artistImg = (ImageView) findViewById(R.id.artistImg);
seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setOnTouchListener(this);
txtTime = (TextView) findViewById(R.id.time);
mediaPlayer = new MediaPlayer();
mediaPlayer.setOnBufferingUpdateListener(this);
mediaPlayer.setOnCompletionListener(this);
}
#Override
public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
seekBar.setSecondaryProgress(percent);
}
#Override
public void onCompletion(MediaPlayer mp) {
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mediaPlayer.isPlaying()) {
SeekBar tmpSeekBar = (SeekBar) v;
mediaPlayer
.seekTo((lengthOfAudio / 100) * tmpSeekBar.getProgress());
}
return false;
}
#Override
public void onClick(View view) {
try {
mediaPlayer.setDataSource(URL);
mediaPlayer.prepare();
lengthOfAudio = mediaPlayer.getDuration();
} catch (Exception e) {
// Log.e("Error", e.getMessage());
}
switch (view.getId()) {
case R.id.btn_play:
if (is_stopped) {
is_stopped = false;
mediaPlayer.seekTo(0);
}
playAudio();
break;
case R.id.btn_pause:
pauseAudio();
break;
case R.id.btn_stop:
stopAudio();
break;
default:
break;
}
updateSeekProgress();
}
private void updateSeekProgress() {
if (mediaPlayer.isPlaying()) {
if (is_loading) {
is_loading = false;
musicProgress.setVisibility(View.GONE);
artistImg.setVisibility(View.VISIBLE);
}
int progress = (int) (((float) mediaPlayer.getCurrentPosition() / lengthOfAudio) * 100);
int remainSec = (lengthOfAudio - mediaPlayer.getCurrentPosition()) / 1000;
seekBar.setProgress(progress);
txtTime.setText("" + timeConversion(remainSec));
handler.postDelayed(r, 1000);
}
}
private void stopAudio() {
if (mediaPlayer != null) {
mediaPlayer.pause();
is_stopped = true;
}
seekBar.setProgress(0);
seekBar.setSecondaryProgress(0);
txtTime.setText("" + timeConversion(lengthOfAudio / 1000));
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
btn_stop.setEnabled(false);
}
private void pauseAudio() {
if (mediaPlayer != null) {
mediaPlayer.pause();
}
btn_play.setEnabled(true);
btn_pause.setEnabled(false);
}
private void playAudio() {
if (mediaPlayer != null) {
mediaPlayer.start();
}
btn_play.setEnabled(false);
btn_pause.setEnabled(true);
btn_stop.setEnabled(true);
}
private static String timeConversion(int totalSeconds) {
int hours = totalSeconds / MINUTES_IN_AN_HOUR / SECONDS_IN_A_MINUTE;
int minutes = (totalSeconds - (hoursToSeconds(hours)))
/ SECONDS_IN_A_MINUTE;
int seconds = totalSeconds
- ((hoursToSeconds(hours)) + (minutesToSeconds(minutes)));
return hours + ":" + minutes + ":" + seconds;
}
private static int hoursToSeconds(int hours) {
return hours * MINUTES_IN_AN_HOUR * SECONDS_IN_A_MINUTE;
}
private static int minutesToSeconds(int minutes) {
return minutes * SECONDS_IN_A_MINUTE;
}
class PlayTask extends AsyncTask<String, Integer, String> {
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected String doInBackground(String... params) {
try {
mediaPlayer.setDataSource(URL);
mediaPlayer.prepare();
lengthOfAudio = mediaPlayer.getDuration();
} catch (Exception e) {
// Log.e("Error", e.getMessage());
}
return null;
}
#Override
protected void onPostExecute(String result) {
super.onPostExecute(result);
playAudio();
updateSeekProgress();
}
}
#Override
protected void onResume() {
super.onResume();
new PlayTask().execute();
}
#Override
public void onBackPressed() {
super.onBackPressed();
pauseAudio();
finish();
}
}

Categories