Media Player - Seek bar and Time lable is not progressing - java

IDK why but after just coping the entier mainactivty.java file from this video
IDK why my seek bar and timetable are not showing any progress
there is an exception I have 2 audio files but the video show has only one so I have doubled all the methods also the onClick and a dialog which is different from it
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;
int totalTime2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// 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(1000000000);
} catch (InterruptedException e) {
}
}
}).start();
new Thread(() -> {
while (player2 != null) {
try {
Message msg = new Message();
msg.what = player2.getCurrentPosition();
handler2.sendMessage(msg);
Thread.sleep(1000000000);
} catch (InterruptedException e) {
}
}
}).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", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
dialogInterface.dismiss();
}
})
.create().show();
SharedPreferences preferences = getSharedPreferences("prefs", MODE_PRIVATE);
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("firstStart", false);
editor.apply();
}
private Handler handler1 = new Handler() {
#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);
}
};
private 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);
}
};
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);
}
}
}

So well why should threads sleep 1000000000 milliseconds.
In that case your thread does its tasks every 1000000 seconds.
1000000000 ms => 1000000 sec => 16666 min => 277 hour
So your thread does its task every 277 hours.
The param of sleep is millisecond so put st like 1000(1 second) or something like that which is a lot shorter.
If this wasn't solution let me know.

Replace Thread.sleep(1000000000) to Thread.sleep(1000) because you just need to update text and seek bar every second
new Thread(() -> {
while (player1 != null) {
try {
Message msg = new Message();
msg.what = player1.getCurrentPosition();
handler1.sendMessage(msg);
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}).start();
new Thread(() -> {
while (player2 != null) {
try {
Message msg = new Message();
msg.what = player2.getCurrentPosition();
handler2.sendMessage(msg);
Thread.sleep(1000);
} catch (InterruptedException e) {
}
}
}).start();

Related

How to show a alert dialog when app is launched first time

I have two audio files in my app. When the app is launched the first time and when the user plays the first audio for the first time, I want to show a dialog, but afterwards never show it again.
When the user clicks OK, then only the dialog will disappear.
I have only created the XML of the dialog because I don't know how to show a layout when the app is launched the first time.
MainActivity.java here the player1 (Media Player) and play1 (ImageView as the button to play the audio) is for the first audio where the dialog has to be shown.
public class MainActivity extends AppCompatActivity {
MediaPlayer player1, player2;
SeekBar seekBar1, seekBar2;
TextView currentTime1, currentTime2;
TextView remainingTime1, remainingTime2;
ImageView play1, play2;
int totalTime1, totalTime2;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// PlayButton * The ButtonClick is in the last if you want to jump directly there *
play1 = findViewById(R.id.playbtn);
play2 = findViewById(R.id.playbtn2);
// TimeLables
currentTime1 = findViewById(R.id.currentTime1);
currentTime2 = findViewById(R.id.currentTime2);
remainingTime1 = findViewById(R.id.totalTime1);
remainingTime2 = findViewById(R.id.totalTime2);
// MediaPlayer
player1 = MediaPlayer.create(this, R.raw.dog_howl);
player2 = MediaPlayer.create(this, R.raw.dog_bark);
player1.setLooping(false);
player1.seekTo(0);
totalTime1 = player1.getDuration();
player2.setLooping(false);
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 progress, boolean fromUser) {
player1.seekTo(progress);
seekBar1.setProgress(progress);
currentTime1.setText(createTimerLable1(progress));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
seekBar2.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
player2.seekTo(i);
seekBar2.setProgress(i);
currentTime2.setText(createTimerLable2(i));
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
new Thread(() -> {
while (player1 != null) {
try {
Message msg = new Message();
msg.what = player1.getCurrentPosition();
handler1.sendMessage(msg);
Thread.sleep(1000000000);
} catch (InterruptedException ignored) {
}
}
}).start();
new Thread(() -> {
while (player2 != null) {
try {
Message msg = new Message();
msg.what = player2.getCurrentPosition();
handler2.sendMessage(msg);
Thread.sleep(1000000000);
} 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);
}
#SuppressLint("HandlerLeak")
private final Handler handler1 = new Handler() {
#Override
public void handleMessage(#NonNull Message msg) {
int currentPosition1 = msg.what;
//Update SeekBar
seekBar1.setProgress(currentPosition1);
// Update Timelable
String totTime1 = createTimerLable1(player1.getDuration());
remainingTime1.setText(totTime1);
}
};
#SuppressLint("HandlerLeak")
private final Handler handler2 = new Handler() {
#Override
public void handleMessage(#NonNull Message msg) {
int currentPosition2 = msg.what;
// Update SeekBar
seekBar2.setProgress(currentPosition2);
// Update Timelable
String totTime2 = createTimerLable2(player2.getDuration());
remainingTime2.setText(totTime2);
}
};
public String createTimerLable1(int duration) {
String timerLabel = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel += min + ":";
if (sec < 10) timerLabel += "0";
timerLabel += sec;
return timerLabel;
}
public String createTimerLable2(int duration) {
String timerLabel = "";
int min = duration / 1000 / 60;
int sec = duration / 1000 % 60;
timerLabel += min + ":";
if (sec < 10) timerLabel += "0";
timerLabel += sec;
return timerLabel;
}
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);
}
}
}
As #blackapps suggested, You will save the information about the user in SharedPreferences. You will save whether you have displayed the dialog and whether user's has played audio for first time or not.
To save or get the details from SharedPreferences,
You can follow this SO answer for storing strings, int, boolean etc.
You can follow this SO answer for storing custom objects.

How to atomatically post data when any new item add in recycler view

I am trying to post data when any new Item add in recycler view it automatically post
I have already tried on item click it working fine but i want to post automatically when any item add in recycler view
class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.MyViewHolder> {
public ArrayList<String> songNames;
Context context;
// MediaPlayer mediaPlayer = new MediaPlayer();
boolean wasPlaying = false;
Handler seekHandler = new Handler();
Runnable run;
public RecyclerViewAdapter(ArrayList<String> songNames, Context context) {
this.songNames = songNames;
this.context = context;
}
#NonNull
#Override
public RecyclerViewAdapter.MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View listItem = LayoutInflater.from(parent.getContext()).inflate(R.layout.record_card, parent, false);
return new MyViewHolder(listItem);
}
#Override
public void onBindViewHolder(#NonNull final RecyclerViewAdapter.MyViewHolder holder, final int position) {
holder.textView.setText(songNames.get(position));
holder.textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.playerCard.setVisibility(View.VISIBLE);
boolean connected = false;
ConnectivityManager connectivityManager = (ConnectivityManager)context.getSystemService(context.CONNECTIVITY_SERVICE);
if(connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED ||
connectivityManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI).getState() == NetworkInfo.State.CONNECTED) {
//we are connected to a network
Toast.makeText(context, "Internet is working", Toast.LENGTH_SHORT).show();
connected = true;
postingData(position, holder);
if (connected == true ) {
}
}
else{
connected = false;
Toast.makeText(context, "net not", Toast.LENGTH_SHORT).show();
}
}
});
holder.cardView1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
holder.playerCard.setVisibility(View.VISIBLE);
}
});
final MediaPlayer mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(CallRecoding.songs.get(position));
mediaPlayer.prepare();
} catch (IOException e) {
e.printStackTrace();
}
holder.seekBar.setMax(mediaPlayer.getDuration());
holder.seekBar.setTag(position);
holder.seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if (mediaPlayer != null && fromUser) {
mediaPlayer.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
holder.seekBarHint.setText("0:00/" + calculateDuration(mediaPlayer.getDuration()));
holder.playsong.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!mediaPlayer.isPlaying()) {
mediaPlayer.start();
holder.pauseRec.setVisibility(View.VISIBLE);
holder.playsong.setVisibility(View.INVISIBLE);
holder.playsong.setText(" Pause ");
run = new Runnable() {
#Override
public void run() {
// Updateing SeekBar every 100 miliseconds
holder.seekBar.setProgress(mediaPlayer.getCurrentPosition());
seekHandler.postDelayed(run, 100);
//For Showing time of audio(inside runnable)
int miliSeconds = mediaPlayer.getCurrentPosition();
if (miliSeconds != 0) {
//if audio is playing, showing current time;
long minutes = TimeUnit.MILLISECONDS.toMinutes(miliSeconds);
long seconds = TimeUnit.MILLISECONDS.toSeconds(miliSeconds);
if (minutes == 0) {
holder.seekBarHint.setText("0:" + seconds + "/" + calculateDuration(mediaPlayer.getDuration()));
} else {
if (seconds >= 60) {
long sec = seconds - (minutes * 60);
holder.seekBarHint.setText(minutes + ":" + sec + "/" + calculateDuration(mediaPlayer.getDuration()));
}
}
} else {
//Displaying total time if audio not playing
int totalTime = mediaPlayer.getDuration();
long minutes = TimeUnit.MILLISECONDS.toMinutes(totalTime);
long seconds = TimeUnit.MILLISECONDS.toSeconds(totalTime);
if (minutes == 0) {
holder.seekBarHint.setText("0:" + seconds);
} else {
if (seconds >= 60) {
long sec = seconds - (minutes * 60);
holder.seekBarHint.setText(minutes + ":" + sec);
}
}
}
}
};
run.run();
} else {
mediaPlayer.pause();
holder.pauseRec.setVisibility(View.INVISIBLE);
holder.playsong.setVisibility(View.VISIBLE);
holder.playsong.setText(" Play ");
}
}
});
holder.pauseRec.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.pause();
holder.playsong.setVisibility(View.VISIBLE);
holder.pauseRec.setVisibility(View.GONE);
}
});
}
private void postingData(final int position, final MyViewHolder holder) {
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
final String value = preferences.getString("user_id", "0");
String currentTime = preferences.getString("currentDate", "1");
SharedPreferences sp = context.getSharedPreferences("MyPrefs", MODE_PRIVATE);
String name = sp.getString("prospectNumber", "0");
System.out.println("pressssss"+name);
OkHttpClient client = new OkHttpClient();
RequestBody requestBody = new MultipartBody.Builder()
.setType(MultipartBody.FORM)
.addFormDataPart("file", songNames.get(position),
RequestBody.create(MediaType.parse("application/octet-stream"),
new File(CallRecoding.songs.get(position))))
.addFormDataPart("user_id", value)
.addFormDataPart("file_name", "Call Recording")
.addFormDataPart("creation_datetime", currentTime)
.addFormDataPart("prospect_number","1234567891")
.addFormDataPart("call_type","incoming")
.build();
Request request = new Request.Builder()
.url("http://159.65.145.32/api/file/upload/")
.post(requestBody)
.build();
client.newCall(request).enqueue(new Callback() {
#Override
public void onFailure(Call call, IOException e) {
e.printStackTrace();
}
#Override
public void onResponse(Call call, final Response response) throws IOException {
if (!response.isSuccessful()) {
throw new IOException("Unexpected code " + response);
} else {
String json = response.body().string();
System.out.println("FileUploading >>> " + json);
}
}
});
}
#Override
public int getItemCount() {
return songNames.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder {
TextView textView, seekBarHint;
TextView playsong, pauseRec;
public static SeekBar seekBar;
CardView playerCard, cardView1;
ImageView recdonpost,notdone;
public MyViewHolder(#NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.card_item);
playsong = itemView.findViewById(R.id.recplay);
seekBarHint = itemView.findViewById(R.id.songDur);
seekBar = itemView.findViewById(R.id.seekbar);
playerCard = itemView.findViewById(R.id.playerCard);
cardView1 = itemView.findViewById(R.id.layout1);
pauseRec = itemView.findViewById(R.id.recPause);
}
}
private String calculateDuration(int duration) {
String finalDuration = "";
long minutes = TimeUnit.MILLISECONDS.toMinutes(duration);
long seconds = TimeUnit.MILLISECONDS.toSeconds(duration);
if (minutes == 0) {
finalDuration = "0:" + seconds;
} else {
if (seconds >= 60) {
long sec = seconds - (minutes * 60);
finalDuration = minutes + ":" + sec;
}
}
return finalDuration;
}
}
Here is my Recycler view adapter code
I want to post automatically data when data will add in recycler view
When you updating songNames in your adapter just match difference and post data for items which are new in the list
You need to make a method like this in your adapter.
void addItem(String songName){
datas.add(songName); // Add new Item into the data list in your Adapter.
notifyDataSetChanged();
}
And call this on the activity like this:
adapter.addItem(name);
Then, it will automatically changes.
You need separation of concerns.
Your RecyclerView and Adapter is part of your view component. It should not have any logic regarding network callbacks.
If you want to make a request when a new item is added, please check where you are adding the item to the list and calling notifyDatasetChanged(). Ideally, your app should make the network call there (or before adding the item to the list).
When you do this, the code would have the exact items that are being added so you would make an API call for that. Depending on bind method is not reliable as it gets called multiple times when user scrolls the list.

CountDownTimer is not stopping on BackPressed running in background,may be handler.postDelayed() is the issue. How to fix it in this code?

My Countdown timer is working fine but when I use back press during running state of the time, my countdown timer did not stop. I have tried everything as follows but none of them is able to stop the countdown timer from running in the background. After searching the forum an applying the results from it to my project I am unable to figure out whats fault in my code. Please anyone help me out and I shall be very thankful.
public class QuizActivity extends AppCompatActivity {
private static final long COUNTDOWN_IN_MILLIS = 30000 ;
List<Questions> mQuestions;
int score = 0;
int qid = 0;
Questions currentQ;
TextView txtQuestions, textViewCountDown;
RadioButton rda, rdb, rdc;
Button btnNext;
private QuestionsViewModel questionsViewModel;
private RelativeLayout relativeLayout;
private LinearLayout linearLayout;
private ColorStateList textColorDefaultCd;
private CountDownTimer countDownTimer;
private long timeLeftInMillis;
private Handler handler;
private Runnable runnable = new Runnable() {
#Override
public void run() {
takeAction();
}
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
textViewCountDown = findViewById(R.id.text_view_countdown);
relativeLayout = (RelativeLayout)findViewById(R.id.profileLoadingScreen);
linearLayout = (LinearLayout) findViewById(R.id.linearView);
textColorDefaultCd = textViewCountDown.getTextColors();
fetchQuestions();
questionsViewModel = ViewModelProviders.of(QuizActivity.this).get(QuestionsViewModel.class);
questionsViewModel.getAllQuestions().observe(this, new Observer<List<Questions>>() {
#Override
public void onChanged(#Nullable final List<Questions> words) {
// Update the cached copy of the words in the adapter.
mQuestions = words;
//Collections.shuffle(mQuestions);
Collections.addAll(mQuestions);
}
});
}
private void fetchQuestions() {
DataServiceGenerator dataServiceGenerator = new DataServiceGenerator();
Service service = DataServiceGenerator.createService(Service.class);
Call<List<QuestionsModel>> call = service.getQuestions();
call.enqueue(new Callback<List<QuestionsModel>>() {
#Override
public void onResponse(Call<List<QuestionsModel>> call, Response<List<QuestionsModel>> response) {
if (response.isSuccessful()){
if (response != null){
List<QuestionsModel> questionsModelList = response.body();
for (int i = 0; i < questionsModelList.size(); i++){
String question = questionsModelList.get(i).getQuestion();
String answer = questionsModelList.get(i).getAnswer();
String opta = questionsModelList.get(i).getOpta();
String optb = questionsModelList.get(i).getOptb();
String optc = questionsModelList.get(i).getOptc();
Questions questions = new Questions(question, answer, opta, optb, optc);
questionsViewModel.insert(questions);
}
handler = new Handler();//add this
handler.postDelayed(runnable,3000);
/* Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
takeAction();
}
}, 3000); */
}
}else{
}
}
#Override
public void onFailure(Call<List<QuestionsModel>> call, Throwable t) {
}
});
}
private void setQuestionView()
{
txtQuestions.setText(currentQ.getQuestion());
rda.setText(currentQ.getOptA());
rdb.setText(currentQ.getOptB());
rdc.setText(currentQ.getOptC());
qid++;
}
private void startCountDown() {
countDownTimer = new CountDownTimer(timeLeftInMillis, 1000) {
#Override
public void onTick(long millisUntilFinished) {
timeLeftInMillis = millisUntilFinished;
updateCountDownText();
}
#Override
public void onFinish() {
timeLeftInMillis = 0;
updateCountDownText();
Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}.start();
}
private void updateCountDownText() {
int minutes = (int) (timeLeftInMillis / 1000) / 60;
int seconds = (int) (timeLeftInMillis / 1000) % 60;
String timeFormatted = String.format(Locale.getDefault(), "%02d:%02d", minutes, seconds);
textViewCountDown.setText(timeFormatted);
if (timeLeftInMillis < 10000) {
textViewCountDown.setTextColor(Color.RED);
} else {
textViewCountDown.setTextColor(textColorDefaultCd);
}
}
private void takeAction() {
relativeLayout.setVisibility(View.GONE);
linearLayout.setVisibility(View.VISIBLE);
textViewCountDown.setVisibility(View.VISIBLE);
timeLeftInMillis = COUNTDOWN_IN_MILLIS;
startCountDown();
currentQ = mQuestions.get(qid);
txtQuestions = (TextView)findViewById(R.id.textView1);
rda=(RadioButton)findViewById(R.id.radio0);
rdb=(RadioButton)findViewById(R.id.radio1);
rdc=(RadioButton)findViewById(R.id.radio2);
btnNext=(Button)findViewById(R.id.button1);
setQuestionView();
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
RadioGroup grp=(RadioGroup)findViewById(R.id.radioGroup1);
if (grp.getCheckedRadioButtonId() == -1){
Toast.makeText(getApplicationContext(),
"Please Select an Answer",
Toast.LENGTH_SHORT)
.show();
return;
}else{
// countDownTimer.cancel();
}
RadioButton answer=(RadioButton)findViewById(grp.getCheckedRadioButtonId());
grp.clearCheck();
//Log.d("yourans", currentQ.getANSWER()+" "+answer.getText());
if(currentQ.getAnswer().equals(answer.getText()))
{
score++;
Log.d("score", "Your score"+score);
}else{
}
if(qid<10){
currentQ=mQuestions.get(qid);
setQuestionView();
}else{
Intent intent = new Intent(QuizActivity.this, ResultActivity.class);
Bundle b = new Bundle();
b.putInt("score", score); //Your score
intent.putExtras(b); //Put your score to your next Intent
startActivity(intent);
finish();
}
}
});
}
#Override
protected void onDestroy() {
super.onDestroy();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer != null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
protected void onPause() {
super.onPause();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
protected void onStop() {
super.onStop();
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
#Override
public void onBackPressed() {
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}
}
Try this code
#Override
public void onBackPressed() {
if(handler!=null){
handler.removeCallbacks(runnable);
}
if (countDownTimer!=null) {
countDownTimer.cancel();
countDownTimer = null;
}
finish();
}

Android MediaPlayer seekBar not working correctly

Currently, I'm developing a media player and I need seekBar to work together, at the moment, it's everything okay! but, when I touch at determinated position of the seekbar, the mediaplayer must follow and set the song to this determinated position, but the song and seekBar back to the start and I don't know why it's happening.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private Handler mHandler = new Handler();
public TextView song_detail;
public TextView time1;
public TextView time2;
private String player_status = "playing";
private ImageButton player_img;
public static SeekBar seekBar;
private static MediaPlayer mediaPlayer;
#SuppressLint("RestrictedApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
song_detail = findViewById(R.id.song_detail);
song_detail.setVisibility(View.GONE);
time1 = findViewById(R.id.time_1);
time2 = findViewById(R.id.time_2);
seekBar = findViewById(R.id.seekBar);
final Runnable mRunnable = new Runnable() {
#Override
public void run() {
if(mediaPlayer != null){
int CurrentPosition = mediaPlayer.getCurrentPosition();
String m_1;
String s_1;
seekBar.setProgress(CurrentPosition/1000);
final int minutes_1 = (CurrentPosition/1000)/60;
final int seconds_1 = ((CurrentPosition/1000)%60);
if (minutes_1 < 10) {
m_1 = "0" + minutes_1;
} else {
m_1 = "" + minutes_1;
}
if (seconds_1 < 10) {
s_1 = "0" + seconds_1;
} else {
s_1 = "" + seconds_1;
}
time1.setText(m_1 + ":" + s_1);
int Duration = mediaPlayer.getDuration();
String m_2;
String s_2;
final int minutes_2 = (Duration/1000)/60;
final int seconds_2 = ((Duration/1000)%60);
if (minutes_2 < 10) {
m_2 = "0" + minutes_2;
} else {
m_2 = "" + minutes_2;
}
if (seconds_2 < 10) {
s_2 = "0" + seconds_2;
} else {
s_2 = "" + seconds_2;
}
time2.setText(m_2 + ":" + s_2);
}
mHandler.postDelayed(this, 1000);
}
};
mRunnable.run();
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(mediaPlayer != null && fromUser){
Toast.makeText(getApplicationContext(), String.valueOf(progress), Toast.LENGTH_LONG).show();
mediaPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) { }
#Override
public void onStopTrackingTouch(SeekBar seekBar) { }
});
}
public void initAudio(final Context context, final String url) {
if (mediaPlayer == null) {
mediaPlayer = MediaPlayer.create(context, Uri.parse(url));
}
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
//Toast.makeText(context, "TEST", Toast.LENGTH_LONG).show();
killMediaPlayer();
}
});
seekBar.setMax(mediaPlayer.getDuration()/1000);
mediaPlayer.start();
}
public void killMediaPlayer() {
if (mediaPlayer != null) {
try {
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer = null;
} catch (Exception e) {
e.printStackTrace();
}
}
}
public static void pauseAudio() {
if (!(mediaPlayer == null)) {
mediaPlayer.pause();
}
}
public static void startAudio() {
if (!(mediaPlayer == null)) {
mediaPlayer.start();
}
}
}
This is the part of code that I'm using to work with mediaPlayer and seekBar
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
if(mediaPlayer != null && fromUser){
Toast.makeText(getApplicationContext(), String.valueOf(progress), Toast.LENGTH_LONG).show();
mediaPlayer.seekTo(progress);
seekBar.setProgress(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) { }
#Override
public void onStopTrackingTouch(SeekBar seekBar) { }
});
}
But as I have said, instead of mediaPlayer seek and continue the audio from the position that I've clicked, the audio simply back to the start. What I'm doing wrong?
Thank you.
The max value for progress is 100. The seekTo function takes time in milliseconds. This is why it seeks to the start (almost) of the audio.
So instead of mediaPlayer.seekTo(progress);, you need to do:
long newTime = (progress/100.0) * total_audio_duration_in_millisecond;
mediaPlayer.seekTo(newTime);

splash screen getting value from the service

I have splash screen which has count down time. I am assigning time value manually in my example time = 10000.
1)How can I assign value which I am getting from the service to the time variable.
2) How can I compare both the time and then assign the service time to the splash screen activity.
Activity
TextView text1, text2, text3;
// int time= 3600000*8;
int time = 10000;
public int Main_time ;
private UsbService usbService;
private EditText editText;
private MyHandler mHandler;
StringBuilder stringBuilder = new StringBuilder();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
mHandler = new MyHandler(splash_screen.this);
splashScreenUseAsyncTask();
int mUIFlag = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
| View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
| View.SYSTEM_UI_FLAG_LAYOUT_STABLE
| View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_FULLSCREEN
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
getWindow().getDecorView().setSystemUiVisibility(mUIFlag);
text1 = (TextView) findViewById(R.id.tv_hour);
text2 = (TextView) findViewById(R.id.tv_minute);
text3 = (TextView) findViewById(R.id.tv_second);
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case UsbService.ACTION_USB_PERMISSION_GRANTED: // USB PERMISSION GRANTED
Toast.makeText(context, "USB Ready", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_PERMISSION_NOT_GRANTED: // USB PERMISSION NOT GRANTED
Toast.makeText(context, "USB Permission not granted", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_NO_USB: // NO USB CONNECTED
Toast.makeText(context, "No USB connected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_DISCONNECTED: // USB DISCONNECTED
Toast.makeText(context, "USB disconnected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_NOT_SUPPORTED: // USB NOT SUPPORTED
Toast.makeText(context, "USB device not supported", Toast.LENGTH_SHORT).show();
break;
}
}
};
private final ServiceConnection usbConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
usbService = ((UsbService.UsbBinder) arg1).getService();
usbService.setHandler(mHandler);
//usbService.sendATGetESN();
//usbService.sendATGetSTART();
//usbService.sendATGetPC();
//usbService.sendATGetSTOP();
usbService.sendATGetACC();
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
usbService = null;
}
};
#Override
public void onResume() {
super.onResume();
setFilters(); // Start listening notifications from UsbService
startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
}
#Override
public void onPause() {
try {
unregisterReceiver(mUsbReceiver);
unbindService(usbConnection);
} catch (IllegalArgumentException ex) {
}
super.onPause();
}
#Override
public void onDestroy() {
try{
if(mUsbReceiver!=null)
unregisterReceiver(mUsbReceiver);
}catch(Exception e){}
super.onDestroy();
}
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
Intent serviceIntent = new Intent(this, splash_screen.class);
this.startService(serviceIntent);
startService(serviceIntent);
if (!UsbService.SERVICE_CONNECTED) {
Intent startService = new Intent(this, splash_screen.class);
if (extras != null && !extras.isEmpty()) {
Set<String> keys = extras.keySet();
for (String key : keys) {
String extra = extras.getString(key);
startService.putExtra(key, extra);
}
}
startService(startService);
}
Intent bindingIntent = new Intent(this, service);
bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private void setFilters() {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbService.ACTION_USB_PERMISSION_GRANTED);
filter.addAction(UsbService.ACTION_NO_USB);
filter.addAction(UsbService.ACTION_USB_DISCONNECTED);
filter.addAction(UsbService.ACTION_USB_NOT_SUPPORTED);
filter.addAction(UsbService.ACTION_USB_PERMISSION_NOT_GRANTED);
registerReceiver(mUsbReceiver, filter);
}
public class MyHandler extends Handler {
private final WeakReference<splash_screen> mActivity;
public MyHandler(splash_screen activity) {
mActivity = new WeakReference<>(activity);
}
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UsbService.MESSAGE_FROM_SERIAL_PORT:
String data = (String) msg.obj;
StringBuilder main= mActivity.get().stringBuilder.append(data);
Main_time = Integer.parseInt(main.toString());
Log.d("REPLY", "Processing Accumulator List Command22"+Main_time);
break;
}
}
}
private void splashScreenUseAsyncTask() {
// Create a AsyncTask object.
final RetrieveDateTask retrieveDateTask = new RetrieveDateTask();
retrieveDateTask.execute("", "", "");
// Get splash image view object.
final ImageView splashImageView = (ImageView) findViewById(R.id.logo_id);
//for 5 Hours
CountDownTimer countDownTimer = new CountDownTimer(time, 1000) {
#Override
public void onTick(long l) {
//long Days = l / (24 * 60 * 60 * 1000);
long Hours = l / (60 * 60 * 1000) % 24;
long Minutes = l / (60 * 1000) % 60;
long Seconds = l / 1000 % 60;
// tv_days.setText(String.format("%02d", Days));
text1.setText(String.format("%02d", Hours));
text2.setText(String.format("%02d", Minutes));
text3.setText(String.format("%02d", Seconds));
AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
anim.setDuration(500);
anim.setRepeatCount(anim.INFINITE);
anim.setRepeatMode(Animation.REVERSE);
splashImageView.startAnimation(anim);
}
#Override
public void onFinish() {
// When count down complete, set the image to invisible.
//imageAplha = 0;
//splashImageView.setAlpha(imageAplha);
// If AsyncTask is not complete, restart the counter to count again.
if (!retrieveDateTask.isAsyncTaskComplete()) {
this.start();
}
}
};
// Start the count down timer.
countDownTimer.start();
}
// This is the async task class that get data from network.
private class RetrieveDateTask extends AsyncTask<String, String, String> {
// Indicate whether AsyncTask complete or not.
private boolean asyncTaskComplete = false;
public boolean isAsyncTaskComplete() {
return asyncTaskComplete;
}
public void setAsyncTaskComplete(boolean asyncTaskComplete) {
this.asyncTaskComplete = asyncTaskComplete;
}
// This method will be called before AsyncTask run.
#Override
protected void onPreExecute() {
this.asyncTaskComplete = false;
}
// This method will be called when AsyncTask run.
#Override
protected String doInBackground(String... strings) {
try {
// Simulate a network operation which will last for 10 seconds.
Thread currTread = Thread.currentThread();
currTread.sleep(time);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
return null;
}
}
// This method will be called after AsyncTask run.
#Override
protected void onPostExecute(String s) {
// Start SplashScreenMainActivity.
Intent mainIntent = new Intent(splash_screen.this,
MainActivity.class);
splash_screen.this.startActivity(mainIntent);
// Close SplashScreenActivity.
splash_screen.this.finish();
this.asyncTaskComplete = true;
}
}
Service
long sec = Integer.parseInt(value9);
long result = TimeUnit.SECONDS.toMillis(sec);
Log.d("REPLY","Milli"+ result);
String s = String.valueOf(result);
if (mHandler != null) {
mHandler.obtainMessage(MESSAGE_FROM_SERIAL_PORT, s).sendToTarget();
}
new MyTask().execute();
private class MyTask extends AsyncTask<Void,Void,Long>{
#Override
protected Long doInBackground(Void... voids) {
//after downloading or after getting time from service that time for example 3000 we received
return 3000l;
}
#Override
protected void onPostExecute(Long aLong) {
super.onPostExecute(aLong);
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
startActivity(new Intent(SplashScreen.this,MainActivity.class));
}
},timeinMs);
}
}
public class splash_screen extends AppCompatActivity {
TextView text1, text2, text3,display;
// int time= 3600000*8;
public String data;
private UsbService usbService;
private EditText editText;
private MyHandler mHandler;
public StringBuilder stringBuilder = new StringBuilder();
long time = 60000;
private long result ;
private long result2 ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
mHandler = new MyHandler(splash_screen.this);
int mUIFlag = View.SYSTEM_UI_FLAG_LOW_PROFILE
| View.SYSTEM_UI_FLAG_HIDE_NAVIGATION;
getWindow().getDecorView().setSystemUiVisibility(mUIFlag);
text1 = (TextView) findViewById(R.id.tv_hour);
text2 = (TextView) findViewById(R.id.tv_minute);
text3 = (TextView) findViewById(R.id.tv_second);
}
private final BroadcastReceiver mUsbReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
switch (intent.getAction()) {
case UsbService.ACTION_USB_PERMISSION_GRANTED: // USB PERMISSION GRANTED
Toast.makeText(context, "USB Ready", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_PERMISSION_NOT_GRANTED: // USB PERMISSION NOT GRANTED
Toast.makeText(context, "USB Permission not granted", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_NO_USB: // NO USB CONNECTED
Toast.makeText(context, "No USB connected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_DISCONNECTED: // USB DISCONNECTED
Toast.makeText(context, "USB disconnected", Toast.LENGTH_SHORT).show();
break;
case UsbService.ACTION_USB_NOT_SUPPORTED: // USB NOT SUPPORTED
Toast.makeText(context, "USB device not supported", Toast.LENGTH_SHORT).show();
break;
}
}
};
private final ServiceConnection usbConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName arg0, IBinder arg1) {
usbService = ((UsbService.UsbBinder) arg1).getService();
usbService.setHandler(mHandler);
usbService.sendATGetACC();
}
#Override
public void onServiceDisconnected(ComponentName arg0) {
usbService = null;
}
};
#Override
public void onResume() {
super.onResume();
setFilters(); // Start listening notifications from UsbService
startService(UsbService.class, usbConnection, null); // Start UsbService(if it was not started before) and Bind it
}
#Override
public void onPause() {
try {
unregisterReceiver(mUsbReceiver);
unbindService(usbConnection);
} catch (IllegalArgumentException ex) {
}
super.onPause();
}
#Override
public void onDestroy() {
try{
if(mUsbReceiver!=null)
unregisterReceiver(mUsbReceiver);
}catch(Exception e){}
super.onDestroy();
}
private void startService(Class<?> service, ServiceConnection serviceConnection, Bundle extras) {
Intent serviceIntent = new Intent(this, splash_screen.class);
this.startService(serviceIntent);
startService(serviceIntent);
if (!UsbService.SERVICE_CONNECTED) {
Intent startService = new Intent(this, splash_screen.class);
if (extras != null && !extras.isEmpty()) {
Set<String> keys = extras.keySet();
for (String key : keys) {
String extra = extras.getString(key);
startService.putExtra(key, extra);
}
}
startService(startService);
}
Intent bindingIntent = new Intent(this, service);
bindService(bindingIntent, serviceConnection, Context.BIND_AUTO_CREATE);
}
private void setFilters() {
IntentFilter filter = new IntentFilter();
filter.addAction(UsbService.ACTION_USB_PERMISSION_GRANTED);
filter.addAction(UsbService.ACTION_NO_USB);
filter.addAction(UsbService.ACTION_USB_DISCONNECTED);
filter.addAction(UsbService.ACTION_USB_NOT_SUPPORTED);
filter.addAction(UsbService.ACTION_USB_PERMISSION_NOT_GRANTED);
registerReceiver(mUsbReceiver, filter);
}
public class MyHandler extends Handler {
private final WeakReference<splash_screen> mActivity;
public MyHandler(splash_screen activity) {
mActivity = new WeakReference<>(activity);
}
#Override
public void handleMessage(Message msg) {
switch (msg.what) {
case UsbService.MESSAGE_FROM_SERIAL_PORT:
String data = (String) msg.obj;
mActivity.get().time(data);
break;
}
}
}
public void time(String data) {
long sec = Integer.parseInt(data);
result = TimeUnit.SECONDS.toMillis(sec);
Log.d("REPLY", "Result value"+result);
result2 = time - result;
Log.d("REPLY", "Result2 value"+result2);
Log.d("REPLY", "Time value"+time);
if(result>=time) {
//usbService.sendATGetSTOP();
Intent mainIntent = new Intent(splash_screen.this,
MainActivity.class);
splash_screen.this.startActivity(mainIntent);
// Close SplashScreenActivity.
splash_screen.this.finish();
}
else{
if (result >= time) {
// usbService.sendATGetSTOP();
Intent mainIntent = new Intent(splash_screen.this,
MainActivity.class);
splash_screen.this.startActivity(mainIntent);
// Close SplashScreenActivity.
splash_screen.this.finish();
} else {
// Log.d("REPLY", "result2 value " + result2);
splashScreenUseAsyncTask();
} }
}
private void splashScreenUseAsyncTask() {
// Create a AsyncTask object.
final RetrieveDateTask retrieveDateTask = new RetrieveDateTask();
retrieveDateTask.execute("", "", "");
// Get splash image view object.
final ImageView splashImageView = (ImageView) findViewById(R.id.logo_id);
//for 5 Hours
CountDownTimer countDownTimer = new CountDownTimer(result2, 1000) {
#SuppressLint("DefaultLocale")
#Override
public void onTick(long l) {
long Hours = l / (60 * 60 * 1000) % 24;
long Minutes = l / (60 * 1000) % 60;
long Seconds = l / 1000 % 60;
// tv_days.setText(String.format("%02d", Days));
text1.setText(String.format("%02d", Hours));
text2.setText(String.format("%02d", Minutes));
text3.setText(String.format("%02d", Seconds));
AlphaAnimation anim = new AlphaAnimation(1.0f, 0.0f);
anim.setDuration(500);
anim.setRepeatCount(anim.INFINITE);
anim.setRepeatMode(Animation.REVERSE);
splashImageView.startAnimation(anim);
}
#Override
public void onFinish() {
if (!retrieveDateTask.isAsyncTaskComplete()) {
this.start();
}
}
};
// Start the count down timer.
countDownTimer.start();
}
// This is the async task class that get data from network.
#SuppressLint("StaticFieldLeak")
private class RetrieveDateTask extends AsyncTask<String, String, String> {
// Indicate whether AsyncTask complete or not.
private boolean asyncTaskComplete = false;
public boolean isAsyncTaskComplete() {
return asyncTaskComplete;
}
public void setAsyncTaskComplete(boolean asyncTaskComplete) {
this.asyncTaskComplete = asyncTaskComplete;
}
// This method will be called before AsyncTask run.
#Override
protected void onPreExecute() {
this.asyncTaskComplete = false;
}
// This method will be called when AsyncTask run.
#Override
protected String doInBackground(String... strings) {
try {
// Simulate a network operation which will last for 10 seconds.
Thread currTread = Thread.currentThread();
currTread.sleep(result2);
} catch (Exception ex) {
ex.printStackTrace();
} finally {
return null;
}
}
// This method will be called after AsyncTask run.
#Override
protected void onPostExecute(String s) {
//usbService.sendATGetSTOP();
// Start SplashScreenMainActivity.
Intent mainIntent = new Intent(splash_screen.this,
MainActivity.class);
splash_screen.this.startActivity(mainIntent);
// Close SplashScreenActivity.
splash_screen.this.finish();
this.asyncTaskComplete = true;
usbService.sendATGetACC();
}
}
}

Categories

Resources