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);
Related
So I made a media Player that works fine but I have one big problem, after pressing play, if I close the activity or app, the music continues to play, if I click again, the music plays on the other one, and I don't know how to fix it. I just want the music to stop after closing the activity or app without any problem.
Here is the full code:
public class m1 extends AppCompatActivity {
ImageView backm1, replay, forward, btPlay, btPause;
TextView playerPosition, playerDuration;
CircularSeekBar seekBar;
MediaPlayer mediaPlayer;
Handler handler = new Handler();
Runnable runnable;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_m1);
backm1 = (ImageView) findViewById(R.id.backm1);
backm1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
m1.super.onBackPressed();
}
});
playerPosition = findViewById(R.id.playerPosition);
playerDuration = findViewById(R.id.playerDuration);
replay = findViewById(R.id.replay);
forward = findViewById(R.id.forward);
seekBar = findViewById(R.id.seekBar);
btPause = findViewById(R.id.btPause);
btPlay = findViewById(R.id.btPlay);
mediaPlayer = MediaPlayer.create(this,R.raw.ding_dong);
runnable = new Runnable() {
#Override
public void run() {
seekBar.setProgress(mediaPlayer.getCurrentPosition());
handler.postDelayed(this,500);
}
};
int duration = mediaPlayer.getDuration();
String sDuration = convertFormat(duration);
playerDuration.setText(sDuration);
btPlay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btPlay.setVisibility(View.GONE);
btPause.setVisibility(View.VISIBLE);
mediaPlayer.start();
seekBar.setMax(mediaPlayer.getDuration());
handler.postDelayed(runnable, 0);
}
});
btPause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
btPause.setVisibility(View.GONE);
btPlay.setVisibility(View.VISIBLE);
mediaPlayer.pause();
handler.removeCallbacks(runnable);
}
});
forward.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int currentPosition = mediaPlayer.getCurrentPosition();
int duration = mediaPlayer.getDuration();
if(mediaPlayer.isPlaying() && duration != currentPosition){
currentPosition = currentPosition + 10000;
playerPosition.setText(convertFormat(currentPosition));
mediaPlayer.seekTo(currentPosition);
}
}
});
replay.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int currentPosition = mediaPlayer.getCurrentPosition();
if (mediaPlayer.isPlaying() && currentPosition > 10000){
currentPosition = currentPosition - 10000;
playerPosition.setText(convertFormat(currentPosition));
mediaPlayer.seekTo(currentPosition);
}
}
});
seekBar.setOnSeekBarChangeListener(new CircularSeekBar.OnCircularSeekBarChangeListener() {
#Override
public void onProgressChanged(CircularSeekBar circularSeekBar, float v, boolean b) {
if (b) {
mediaPlayer.seekTo((int) v);
}
playerPosition.setText(convertFormat(mediaPlayer.getCurrentPosition()));
}
#Override
public void onStopTrackingTouch(CircularSeekBar circularSeekBar) {
}
#Override
public void onStartTrackingTouch(CircularSeekBar circularSeekBar) {
}
});
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
btPause.setVisibility((View.GONE));
btPlay.setVisibility(View.VISIBLE);
mediaPlayer.seekTo(0);
}
});
}
#SuppressLint("DefaultLocale")
private String convertFormat(int duration) {
return String.format("%02d:%02d"
,TimeUnit.MILLISECONDS.toMinutes(duration)
,TimeUnit.MILLISECONDS.toSeconds(duration) -
TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration)));
}
#Override
protected void onDestroy() {
super.onDestroy();
if(mediaPlayer !=null){
mediaPlayer.stop();
mediaPlayer.release();
}
}
}
I added onDestroy but I think in a wrong way and this error came out:
2021-03-08 10:13:40.843 419-4716/? E/AudioSystem: invalid attributes { Content type: AUDIO_CONTENT_TYPE_UNKNOWN Usage: AUDIO_USAGE_UNKNOWN Source: -1 Flags: 0x800 Tags: } when converting to stream
2021-03-08 10:13:40.906 28868-28868/com.example.diligent E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.diligent, PID: 28868
java.lang.IllegalStateException
at android.media.MediaPlayer.getCurrentPosition(Native Method)
I added this:
private void stopPlayer() {
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
Toast.makeText(this, "MediaPlayer released", Toast.LENGTH_SHORT).show();
}
}
#Override
protected void onStop() {
super.onStop();
stopPlayer();
}
And the following error:
java.lang.NullPointerException: Attempt to invoke virtual method 'int android.media.MediaPlayer.getCurrentPosition()' on a null object reference
Any other suggestions are welcome.
Thank you in advance.
Stop and release media resources on onDestroy of activity.
#Override
protected void onDestroy() {
super.onDestroy();
if(mediaPlayer !=null){
mediaPlayer.stop();
mediaPlayer.release();
}
}
MediaPlayer player; //MediaPlayer object
*Function to stop media Player *
private void stopPlayer() {
if (player != null) {
player.release();
player = null;
Toast.makeText(this, "MediaPlayer released", Toast.LENGTH_SHORT).show();
}
}
Call the function in onStop() callback
#Override
protected void onStop() {
super.onStop();
stopPlayer();
}
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.
i want to reset the seekbar to start position once the music is played and button showing "play"...The problem with the code is that the seek bar stays at the end position after its done playing the music and button still shows "pause"...
Here's my code
ekdanta.java
public class ekdanta extends AppCompatActivity implements Runnable, View.OnClickListener,SeekBar.OnSeekBarChangeListener {
TextView tv4;
Button b9, b10,but19;
int count = 0;
MediaPlayer play;
SeekBar seek_bar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_ekdanta);
tv4 = (TextView) findViewById(R.id.textView9);
tv4.setTextSize((float)21.5);
tv4.setText(Html.fromHtml(getString(R.string.thirteen)));
b9 = (Button) findViewById(R.id.b9);
b10 = (Button) findViewById(R.id.b10);
seek_bar = (SeekBar) findViewById(R.id.seekBar);
seek_bar.setOnSeekBarChangeListener(this);
seek_bar.setEnabled(false);
but19 = (Button) findViewById(R.id.button19);
but19.setOnClickListener(this);
}
public void run() {
int currentPosition= play.getCurrentPosition();
int total = play.getDuration();
while (play!=null && currentPosition<total) {
try {
Thread.sleep(1000);
currentPosition= play.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seek_bar.setProgress(currentPosition);
}
}
public void onClick(View v) {
if (v.equals(but19)) {
if (play == null) {
play = MediaPlayer.create(getApplicationContext(), R.raw.ekadanta);
seek_bar.setEnabled(true);
}
if (play.isPlaying()) {
play.pause();
but19.setText("Play");
} else {
play.start();
but19.setText("Pause");
seek_bar.setMax(play.getDuration());
new Thread(this).start();
}
}
}
#Override
protected void onPause() {
if(play!=null){
play.stop();
}
super.onPause();
}
public void increase(View inc) {
count++;
if (count == 1) {
tv4.setTextSize(25);
} else if (count == 2) {
tv4.setTextSize(30);
} else if (count >= 3) {
count = 3;
tv4.setTextSize(40);
}
}
public void decrease(View dec) {
count--;
if (count <= 0) {
tv4.setTextSize((float)21.5);
count = 0;
}
if (count == 1) {
tv4.setTextSize(25);
} else if (count == 2) {
tv4.setTextSize(30);
} else if (count == 3) {
tv4.setTextSize(40);
}
}
#Override
public void onProgressChanged(SeekBar seek_bar, int progress, boolean fromUser) {
try{
if(play.isPlaying()||play!=null){
if (fromUser)
play.seekTo(progress);
}
else if(play==null){
Toast.makeText(getApplicationContext(),"First Play", Toast.LENGTH_SHORT).show();
seek_bar.setProgress(0);
}
}
catch(Exception e){
Log.e("seek bar",""+e);
seek_bar.setEnabled(false);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
}
MediaPlayer has got onCompletionListener(), you can use that. Your code with handlers is not too reliable, it would be better to refactor it.
mMediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// do whatever you want
}
});
I'm trying play an audio file with the mediacontroler in my android application. When playing audio the seekbar does not move.I looked mediacontroler function. But I could not find a function for updating seekbar.
please advice.
public class Show_subject_Activity extends Activity
implements MediaController.MediaPlayerControl, MediaPlayer.OnBufferingUpdateListener {
private RatingBar box_litner;
private MediaController mController;
private MediaPlayer mPlayer;
private Cursor cur;
int bufferPercent = 0;
DB_Nabege_helper db_nabege = new DB_Nabege_helper(this);
private String voicefileName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_show_subject);
box_litner = (RatingBar) findViewById(R.id.ratingBar1);
mController = (MediaController) findViewById(R.id.mediaController_voice);
mController.setAnchorView(null);
db_nabege.open();
cur = db_nabege.getSubject(Intent_values.id_subject);
voicefileName = getVoiceFileName();
db_nabege.close();
}
#Override
public void onResume() {
super.onResume();
mPlayer = new MediaPlayer();
// Set the audio data source
try {
mPlayer.setDataSource(this, getUriVoice());
mPlayer.prepare();
} catch (Exception e) {
e.printStackTrace();
}
// Set an image for the album cover
// coverImage.setImageResource(R.drawable.icon);
mController.setMediaPlayer(this);
mController.setEnabled(true);
}
private Uri getUriVoice() {
File voiceFile = null;
try {
voiceFile = new File(Environment.getExternalStorageDirectory().getPath() + "/nabege" + File.separator
+ "audio" + File.separator + voicefileName);
} catch (Exception e) {
Log.d("log", e.toString());
}
Uri voiceUri = Uri.fromFile(voiceFile);
return voiceUri;
}
#Override
public void onPause() {
super.onPause();
mPlayer.release();
mPlayer = null;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
mController.show();
return super.onTouchEvent(event);
}
// MediaPlayerControl Methods
#Override
public int getBufferPercentage() {
return bufferPercent;
}
#Override
public int getCurrentPosition() {
return mPlayer.getCurrentPosition();
}
#Override
public int getDuration() {
return mPlayer.getDuration();
}
#Override
public boolean isPlaying() {
return mPlayer.isPlaying();
}
#Override
public void pause() {
mPlayer.pause();
}
#Override
public void seekTo(int pos) {
mPlayer.seekTo(pos);
}
#Override
public void start() {
mPlayer.start();
}
// BufferUpdateListener Methods
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
bufferPercent = percent;
}
public boolean canPause() {
return true;
}
public boolean canSeekBackward() {
return true;
}
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
}
You can update the seekbar yourself, e.g.:
final Handler mHandler = new Handler();
final Runnable mUpdateSeekbar = new Runnable() {
public void run() {
mSeekBar.setProgress(mMediaPlayer.getCurrentPosition());
mSeekBar.setMax(mMediaPlayer.getDuration());
mHandler.postDelayed(this, 1000);
}
};
Post the runnable in onResume and mHandler.removeCallbacks(mUpdateSeekbar) in onPause.
I have added a timer to my game but by doing so i keep getting the error "The method setOnTouchListener(View.OnTouchListener) in the type View is not applicable for the arguments (scene5.MyCountDownTimer)" I can not seem to fix it. This might just be me making a simple mistake but any solutions would be great. The error is about halfway down my code, I have tagged it with //THIS IS MY PROBLEM AREA!! Cheers guys
public class scene5 extends Activity implements OnClickListener {
private CountDownTimer countDownTimer;
private boolean timerHasStarted = false;
private Button startB;
public TextView text;
private final long startTime = 20 * 1000;
private final long interval = 1 * 1000;
#Override
public void onBackPressed() {
new AlertDialog.Builder(this)
.setIcon(android.R.drawable.ic_dialog_alert)
.setTitle("FindIt")
.setMessage("Exit to main menu?")
.setPositiveButton("Yes", new DialogInterface.OnClickListener()
{
#Override
public void onClick(DialogInterface dialog, int which) {
finish();
}
})
.setNegativeButton("No", null)
.show();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.level5);
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
startB = (Button) this.findViewById(R.id.button);
startB.setOnClickListener(this);
text = (TextView) this.findViewById(R.id.timer);
countDownTimer = new MyCountDownTimer(startTime, interval);
text.setText(text.getText() + String.valueOf(startTime/1000));
}
#Override
public void onClick(View v) {
startB.setVisibility(View.INVISIBLE);
if (!timerHasStarted) {
countDownTimer.start();
timerHasStarted = true;
startB.setText("STOP");
} else {
countDownTimer.cancel();
timerHasStarted = false;
startB.setText("RESTART");
}
}
public class MyCountDownTimer extends CountDownTimer {
public MyCountDownTimer(long startTime, long interval) {
super(startTime, interval);
}
#Override
public void onFinish() {
Intent intent = new Intent(scene5.this, timeUp.class);
scene5.this.startActivity(intent);
finish();
}
#Override
public void onTick(long millisUntilFinished) {
text.setText("" + millisUntilFinished/1000);
}
{
ImageView iv = (ImageView) findViewById (R.id.image);
if (iv != null) {
iv.setOnTouchListener (this); //THIS IS MY PROBLEM AREA!!
}
toast ("20 seconds to find IT!");}
}
public boolean onTouch (View v, MotionEvent ev)
{
boolean handledHere = false;
final int action = ev.getAction();
final int evX = (int) ev.getX();
final int evY = (int) ev.getY();
int nextImage = -1;
ImageView imageView = (ImageView) v.findViewById (R.id.image);
if (imageView == null) return false;
Integer tagNum = (Integer) imageView.getTag ();
int currentResource = (tagNum == null) ? R.drawable.levels : tagNum.intValue ();
switch (action) {
case MotionEvent.ACTION_DOWN :
if (currentResource == R.drawable.levels) {
nextImage = R.drawable.wrong5;
handledHere = true;
} else handledHere = true;
break;
case MotionEvent.ACTION_UP :
int touchColor = getHotspotColor (R.id.image_areas, evX, evY);
ColorTool ct = new ColorTool ();
int tolerance = 25;
nextImage = R.drawable.levels;
if (ct.closeMatch (Color.RED, touchColor, tolerance)){
Intent intent = new Intent(scene5.this, LevelComplete.class);
scene5.this.startActivity(intent);
}
if (currentResource == nextImage) {
nextImage = R.drawable.levels;
}
handledHere = true;
break;
default:
handledHere = false;
}
if (handledHere) {
if (nextImage > 0) {
imageView.setImageResource (nextImage);
imageView.setTag (nextImage);
}
}
return handledHere;
}
public int getHotspotColor (int hotspotId, int x, int y) {
ImageView img = (ImageView) findViewById (hotspotId);
if (img == null) {
Log.d ("ImageAreasActivity", "Hot spot image not found");
return 0;
} else {
img.setDrawingCacheEnabled(true);
Bitmap hotspots = Bitmap.createBitmap(img.getDrawingCache());
if (hotspots == null) {
Log.d ("ImageAreasActivity", "Hot spot bitmap was not created");
return 0;
} else {
img.setDrawingCacheEnabled(false);
return hotspots.getPixel(x, y);
}
}
}
public void toast (String msg)
{
Toast.makeText (getApplicationContext(), msg, Toast.LENGTH_LONG).show ();
}
}
Your problem is here:
public class scene5 extends Activity implements OnClickListener, OnTouchListener {
...
#Override
public boolean onTouch(View v, MotionEvent event) {
...
}
}
You have to implements also OnTouchListener.
Use
scene5.this
instead of this
the problem is iv.setOnTouchListener (this);
the this context you are passing belongs to the timer task, You need to use iv.setOnTouchListener (scene5.this);
Also, I think you need to find the ImageView reference in the onCreate itself. What you are doing currently ImageView iv = (ImageView) findViewById (R.id.image); won't work.