Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 6 years ago.
Improve this question
I want to create a progress barProgressBar screenshot like given image where the star image should reduce based on time(every second). So,Please guide me how to do? I am using the handler for countdown timer
timeString* we are getting it from different class
String timestring = getIntent().getStringExtra("ageintent");
timereceived = Integer.parseInt(timestring);
seekbar.setMax(timereceived);
seekbar.setClickable(false);
timereceived--;
time.setText(String.valueOf(timereceived));
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
handler = new Handler();
run = new Runnable() {
#Override
public void run() {
int seconds = Integer.parseInt(timeseconds.getText().toString());
int timechange = Integer.parseInt(time.getText().toString());
seekbar.setProgress(seconds);
seconds--;
timeseconds.setText(String.valueOf(seconds));
if (seconds == 0 && timechange == 0) {
Toast.makeText(Naughty_Step.this, "Your punishment is completed", Toast.LENGTH_SHORT).show();
soundplayer.start();
timereceived--;
} else if (seconds == 0) {
timeseconds.setText("59");
timechange--;
seekbar.setProgress(seconds);
time.setText(String.valueOf(timechange));
// int min= Integer.parseInt(time.getText().toString());
// seekbar.setProgress(min);
handler.postDelayed(this, 1000);
} else {
handler.postDelayed(this, 1000);
}
}
};
handler.postDelayed(run, 1000);
}
Try below -
SeekBar seekBar1 = (SeekBar)findViewById(R.id.seekBar1);
drw = getResources().getDrawable(R.drawable.ic_launcher);
seekBar1.setOnSeekBarChangeListener(new yourListener());
private class yourListener implements SeekBar.OnSeekBarChangeListener {
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
iSize = 100 - progress;
tv.setText(String.valueOf(new Integer(progress)));
drw = resize(drw);
seekBar.setThumb(drw);
}
public void onStartTrackingTouch(SeekBar seekBar) {}
public void onStopTrackingTouch(SeekBar seekBar) {}
}
//Reduce size of seekbar
private Drawable resize(Drawable image) {
Bitmap b = ((BitmapDrawable)image).getBitmap();
Bitmap bitmapResized = Bitmap.createScaledBitmap(b, iSize, iSize, false);
return new BitmapDrawable(getResources(), bitmapResized);
}
Add this as inner class of your activity or fragment need progressbar reduce.
class CounterClass extends CountDownTimer {
int totalDuration;
public CounterClass(long millisInFeature, long countDownInterval) {
// TODO Auto-generated constructor stub
super(millisInFeature , countDownInterval);
this.totalDuration =millisInFeature
}
#Override
public void onTick(long millisUntilFinished) {
// TODO Auto-generated method stub
int progress =((millisUntilFinished * 100 / totalDuration))
progressbar.setProgress(progress);
}
#Override
public void onFinish() {
// TODO Auto-generated method stub
}
oncreate() or event start
(new CounterClass(30000,1000)).start();
Related
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.
In my app i have to apply resize using seekbar to selected image onclick but problem is that only last applied stickerview can be resized and if i want to resize the previous stickerview then also last sticker is being resized.
Can anyone help me with this problem
holder.icon.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (a == 1) {
canvas.setBackgroundResource(mThumbIds[position]);
dialog.dismiss();
a = 0;
}
if (a1 == 1) {
Gallery gallery = (Gallery) findViewById(R.id.gallery);
gallery.setSpacing(1);
final GalleryImageAdapter galleryImageAdapter= new GalleryImageAdapter(getApplicationContext(),position);
gallery.setAdapter(galleryImageAdapter);
gallery.setOnItemClickListener(new AdapterView.OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
iv_sticker1 = new StickerImageView(MainActivity2.this);
if(x ==1)
iv_sticker1.setImageResource(galleryImageAdapter.mImageIds[position]);
if(x ==2)
iv_sticker1.setImageResource(galleryImageAdapter.mImageIds1[position]);
if(x ==3)
iv_sticker1.setImageResource(galleryImageAdapter.mImageIds2[position]);
canvas.addView(iv_sticker1);
}
});
a1 = 0;
}
if (a2 == 1) {
iv_sticker1 = new StickerImageView(MainActivity2.this);
iv_sticker1.setImageDrawable(getResources().getDrawable(mThumbIds2[position]));
canvas.addView(iv_sticker1);
iv_sticker1.setOwnerId(2);
dialog.dismiss();
a2 = 0;
}
if (a3 == 1) {
iv_sticker1 = new StickerImageView(MainActivity2.this);
iv_sticker1.setImageDrawable(getResources().getDrawable(mThumbIds3[position]));
canvas.addView(iv_sticker1);
dialog.dismiss();
a3 = 0;
}
}
});
And this is my resize program
final SeekBar sk1 = (SeekBar) findViewById(R.id.seekBar1);
sk1.setMax(500);
sk1.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
iv_sticker1.getMainView();
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(progress, progress);
iv_sticker1.setLayoutParams(params);
iv_sticker1.setMinimumWidth(progress);
iv_sticker1.setMinimumHeight(progress);
}
});
Now whenever i do this only last iv_sticker1 get selected.How can i apply resize to selected image on click?
I want to add a new feature to my app: I created a progress bar and every time the progress changes, the flash will blink with a delay equal to the value of the progress in milliseconds.
When I modify the progress, the flash begins to blink but I can't do anything until it reaches the number of blinks (20). I want to be able to modify the delay even if the flash is still blinking.
private void blink(int sleepMS) throws Exception{
//int sleepMS=(1/10)*50;
int flashCount=20;
getCamera();
camera.setPreviewTexture(new SurfaceTexture(0));
camera.startPreview();
Thread thr = new Thread();
thr.start();
for(int i=0;i<flashCount;i++) {
flipFlash();
thr.sleep(sleepMS);
flipFlash();
thr.sleep(sleepMS);
}
camera.stopPreview();
//camera.release();
}
private void flipFlash(){
if (isFlashOn) {
params.setFlashMode(Camera.Parameters.FLASH_MODE_OFF);
camera.setParameters(params);
isFlashOn = false;
} else{
params.setFlashMode(Camera.Parameters.FLASH_MODE_TORCH);
camera.setParameters(params);
isFlashOn = true;
}
}
Where getCamera() gets camera parameters. And the code for the SeekBar listener:
volumeControl = (SeekBar) findViewById(R.id.volume_bar);
volumeControl.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int progressChanged = 0;
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
progressChanged = progress;
}
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
public void onStopTrackingTouch(SeekBar seekBar) {
try {
blink(100 - progressChanged);
} catch (Exception e) {
}
}
});
Because your for loop is on you main thread it is blocking all other operations. From you code, it seems like you meant to do something like this:
Thread thr = new Thread(new Runnable() {
#Override
public void run() {
for(int i=0;i<flashCount;i++) {
flipFlash();
thr.sleep(sleepMS);
flipFlash();
thr.sleep(sleepMS);
}
}
});
thr.start();
I have a problem with canceling this timer out of this method.
public void nezablokovat() {
int secondsToRun = 9999999;
final ValueAnimator timern = ValueAnimator.ofInt(secondsToRun);
timern.setDuration(secondsToRun * 1000).setInterpolator(new LinearInterpolator());
timern.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
int elapsedSeconds = (int) animation.getAnimatedValue();
int minutes = elapsedSeconds / 60;
int seconds = elapsedSeconds % 60;
if (seconds%10 == 1) {
Pis("$$$");
}
}
});
timern.start();
}
I want to put timern.cancel(); to an other method in the onClick Listener for the Button.
Please Do you have some ideas?
If I put timern.cancel() here:
void teplotahore() {
STup.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
timern.cancel();
}
}
}
);
}
The compiler doesn't know timern.
I don't know how you're whole class is structured, but I believe you may be able to just move the "timern" "variable" outside the constructor (above it) that way making it a field.
A field is like a variable, however it is visible to all methods in the class.
For example:
final ValueAnimator timern = ValueAnimator.ofInt(secondsToRun);
public void nezablokovat() {
int secondsToRun = 9999999;
timern.setDuration(secondsToRun * 1000).setInterpolator(new LinearInterpolator());
timern.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
int elapsedSeconds = (int) animation.getAnimatedValue();
int minutes = elapsedSeconds / 60;
int seconds = elapsedSeconds % 60;
if (seconds%10 == 1) {
Pis("$$$");
}
}
});
timern.start();
}
void teplotahore() {
STup.setOnClickListener(
new View.OnClickListener() {
#Override
public void onClick(View view) {
timern.cancel();
}
}
});
}
I've created a simple music player in Android which has a seekbar which displays the current position in the song playing. The forward, rewind, play and pause functions work correctly. What I am trying to do is have the seekbar actually move the position within the song. (at present the seekbar does not change the position within the song. Heres my code
public class MusicPlayerA extends Activity {
private MediaPlayer mediaPlayer;
public TextView songName, duration;
private double timeElapsed = 0, finalTime = 0;
private int forwardTime = 2500, backwardTime = 2500;
private Handler durationHandler = new Handler();
private SeekBar seekbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//set the layout of the Activity
setContentView(R.layout.musicplayerview);
//initialize views
initializeViews();
}
#Override
protected void onPause() {
super.onPause();
if (mediaPlayer != null) {
mediaPlayer.pause();
if (isFinishing()) {
mediaPlayer.stop();
mediaPlayer.release();
}
}
}
public void initializeViews(){
songName = (TextView) findViewById(R.id.songName);
mediaPlayer = MediaPlayer.create(this, R.raw.druidsad);
finalTime = mediaPlayer.getDuration();
duration = (TextView) findViewById(R.id.songDuration);
seekbar = (SeekBar) findViewById(R.id.seekBar);
songName.setText("Druids Ad");
seekbar.setMax((int) finalTime);
seekbar.setClickable(true);
}
// play mp3 song
public void play(View view) {
mediaPlayer.start();
timeElapsed = mediaPlayer.getCurrentPosition();
seekbar.setProgress((int) timeElapsed);
durationHandler.postDelayed(updateSeekBarTime, 100);
}
//handler to change seekBarTime
private Runnable updateSeekBarTime = new Runnable() {
public void run() {
//get current position
timeElapsed = mediaPlayer.getCurrentPosition();
//set seekbar progress
seekbar.setProgress((int) timeElapsed);
//set time remaining
double timeRemaining = finalTime - timeElapsed;
duration.setText(String.format("%d min, %d sec", TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining), TimeUnit.MILLISECONDS.toSeconds((long) timeRemaining) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeRemaining))));
//repeat yourself that again in 100 miliseconds
durationHandler.postDelayed(this, 100);
}
};
// pause mp3 song
public void pause(View view) {
mediaPlayer.pause();
}
// go forward at forwardTime seconds
public void forward(View view) {
//check if we can go forward at forwardTime seconds before song endes
if ((timeElapsed + forwardTime) <= finalTime) {
timeElapsed = timeElapsed + forwardTime;
//seek to the exact second of the track
mediaPlayer.seekTo((int) timeElapsed);
}
}
// go backwards at backwardTime seconds
public void rewind(View view) {
//check if we can go back at backwardTime seconds after song starts
if ((timeElapsed - backwardTime) > 0) {
timeElapsed = timeElapsed - backwardTime;
//seek to the exact second of the track
mediaPlayer.seekTo((int) timeElapsed);
}
}
// handler for back button used on music player screen
public void BackButton2 (View view) {
MediaPlayer mMediaPlayer = MediaPlayer.create(this, R.raw.soundbackbutton) ;
mMediaPlayer.start();
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(200);
Intent mus = new Intent (this, Music.class);
startActivity(mus);
}
// handler for home button used on all screens
public void BackButton (View view) {
MediaPlayer mMediaPlayer = MediaPlayer.create(this, R.raw.soundbackbutton) ;
mMediaPlayer.start();
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(200);
Intent mn = new Intent (this, Music.class);
startActivity(mn);
}
}
Its easy. Follow these steps :-
Add a seek bar change Listener.
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int seeked_progess;
#Override
public void onProgressChanged(final SeekBar seekBar, int progress, boolean fromUser) {
seeked_progess = progress;
seeked_progess = seeked_progess * 1000;
if (fromUser) {
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
Now in if(fromUser), U need to add the implementation.
if (fromUser) {
Runnable mRunnable = new Runnable() {
#Override
public void run() {
int min, sec;
if (mediaPlayer != null /*Checking if the
music player is null or not otherwise it
may throw an exception*/) {
int mCurrentPosition = seekBar.getProgress();
min = mCurrentPosition / 60;
sec = mCurrentPosition % 60;
Log.e("Music Player Activity", "Minutes : "+min +" Seconds : " + sec);
/*currentime_mm.setText("" + min);
currentime_ss.setText("" + sec);*/
}
mHandler.postDelayed(this, 1000);
}
};
mRunnable.run();}
At last add this in onStopTrackingTouch()
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mediaPlayer.seekTo(seeked_progess);
}
});
Note :-
mHandler in a global variable.
Initialize it as follows.
Handler mHandler = new Handler();
Secondly currentime_mm and currentime_ss are text views which display the current seek time of the seek bar.
and most Important,
dont forgot to add these when a song starts
seekBar.setProgress(0);// To set initial progress, i.e zero in starting of the song
seekBar.setMax(mediaDuration);// To set the max progress, i.e duration of the song
Put this code inside onCreate() method
seekbar.setMax(mediaPlayer.getDuration());
seekbar.setProgress(mediaPlayer.getCurrentPosition());
new Timer().scheduleAtFixedRate(new TimerTask() {
#Override
public void run()
{
seekbar.setProgress(mediaPlayer.getCurrentPosition());
}
},0,1000);
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b)
{
mediaPlayer.seekTo(i);
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
});
What Punam did is good but add a condition in your "onProgressChanged" function like this:
#Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b)
{
if(b)
mediaPlayer.seekTo(i);
}