Playback error on using two VideoViews - android

When starting playback of two HTTP streams in two VideoViews simultaneously, it works. When I try to stop one and start the other, it throws an error. Code used:
mVideoView1.setVideoPath(videoPath);
mVideoView2.setVideoPath(videoPath);
mVideoView1.start();
Button btn = (Button) findViewById(R.id.button);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mVideoView1.stopPlayback();
mVideoView2.start();
}
});
Any ideas what's causing this error? I get the same behaviour when I use MediaPlayer and SurfaceView (preparing second MediaPlayer in background, release() the first, then start() the second)

you can use the following code it work for me,
package com.materialexample;
import android.content.Context;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.ProgressBar;
import android.widget.VideoView;
import in.co.bhadreshtech.materialexample.R;
public class VideoViews extends AppCompatActivity {
ProgressBar progressBar = null;
VideoView videoView1 = null;
VideoView video_views2 = null;
String videoUrl = "http://www.androidbegin.com/tutorial/AndroidCommercial.3gp";
Context context = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_views);
context = null;
videoView1 = (VideoView) findViewById(R.id.video_view1);
video_views2 = (VideoView) findViewById(R.id.video_views2);
progressBar = (ProgressBar) findViewById(R.id.progressbar);
Uri videoUri = Uri.parse(videoUrl);
videoView1.setVideoURI(videoUri);
video_views2.setVideoURI(videoUri);
videoView1.start();
video_views2.start();
progressBar.setVisibility(View.VISIBLE);
videoView1.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.start();
mp.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
#Override
public void onVideoSizeChanged(MediaPlayer mp, int arg1,
int arg2) {
// TODO Auto-generated method stub
progressBar.setVisibility(View.GONE);
mp.start();
}
});
}
});
video_views2.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
mp.start();
mp.setOnVideoSizeChangedListener(new MediaPlayer.OnVideoSizeChangedListener() {
#Override
public void onVideoSizeChanged(MediaPlayer mp, int arg1,
int arg2) {
// TODO Auto-generated method stub
progressBar.setVisibility(View.GONE);
mp.start();
}
});
}
});
}
}
also don miss to add tow VideoView and one ProgressBar in layout

Related

Android MediaPlayer seekTo() function working incorrect

I have a problem when using MediaPlayer to play video from url.
The follow of program : create an activity to play video -> press Home button -> back to app.
The requirement is video play from start, when press Home button video continuos play(only audio), and when back to app, video must play continuous(combine movie and audio).
The first, I created a MediaPlayer variable to play video. When Home button is pressed, MediaPlayer play continuous. But when back to app, video cannot displayed(black screen). So, I created other MediaPlayer variable to solved this issue. But when I using seekTo() function to seek second MediaPlayer to position of first MediaPlayer, this function is working incorrect.
import java.io.IOException;
import com.example.videotest.R;
import android.app.Activity;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnSeekCompleteListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.View.OnClickListener;
import android.view.ViewGroup.LayoutParams;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.Toast;
public class PlayVideoActivity extends Activity implements OnClickListener,SurfaceHolder.Callback, FGMediaController.MediaPlayerControl {
SurfaceView videoSurface,videoSurfaceFullscreen,videoSurfaceSmallsceen;
MediaPlayer player, backupPlayer;
FGMediaController controller;
LinearLayout llControllerBar;
public boolean isFullscreen = false;
int videoDuration;
int videoCurrent;
SurfaceHolder viewHolder = null;
boolean isPaused = false;
String videoUrl = "http://cdn-smatopi.tv-bank.com/movie/867/867-32/867-32-2015042306-D3/hls/hls3/867-32-2015042306-D3-HLS3.m3u8";
Button btnSeek, btnRelease;
int currentPos = 30000;
boolean videoPrepared = false;
boolean backupPrepared = false;
boolean mVideoSizeIsSet = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.playvideo);
btnSeek = (Button) findViewById(R.id.btnSeek);
btnRelease = (Button) findViewById(R.id.btnRelease);
videoSurface = (SurfaceView)findViewById(getResources().getIdentifier("vvVideo", "id", getPackageName()));
SurfaceHolder videoHolder = videoSurface.getHolder();
videoHolder.addCallback(this);
player = new MediaPlayer();
backupPlayer = new MediaPlayer();
controller = new FGMediaController(this);
try {
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setDataSource(this, Uri.parse(videoUrl));
player.prepareAsync();
//backupPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
//backupPlayer.setDataSource(this, Uri.parse(videoUrl));
//backupPlayer.prepareAsync();
} catch (Exception e) {
e.printStackTrace();
}
btnSeek.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Log.e("Huhu",currentPos + "");
backupPlayer.seekTo(currentPos);
}
});
btnRelease.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
backupPlayer.stop();
backupPlayer.release();
}
});
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
}
});
player.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
controller.setMediaPlayer(PlayVideoActivity.this);
controller.setAnchorView((FrameLayout) findViewById(PlayVideoActivity.this.getResources().getIdentifier("videoSurfaceContainer", "id", PlayVideoActivity.this.getPackageName())));
player.start();
}
});
}
#Override
public void onDestroy(){
//backupPlayer.release();
player.release();
super.onDestroy();
}
#Override
public void onResume(){
Log.e("Surface Created","OnResume");
super.onResume();
}
// Implement SurfaceHolder.Callback
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Log.e("Surface Created","Surface Created! " + holder);
if(viewHolder != null){
viewHolder = holder;
backupPlayer = new MediaPlayer();
try {
backupPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
backupPlayer.setDataSource(this, Uri.parse(videoUrl));
backupPlayer.prepareAsync();
backupPlayer.setDisplay(holder);
backupPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
backupPrepared = true;
backupPlayer.start();
}
});
backupPlayer.setOnVideoSizeChangedListener(new OnVideoSizeChangedListener() {
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
// TODO Auto-generated method stub
if (width == 0 || height == 0){
Toast.makeText(getApplicationContext(),"Width = 0 Height = 0"+ mp.getDuration(), Toast.LENGTH_LONG).show();
}else{
if(backupPrepared){
backupPrepared = false;
currentPos = player.getCurrentPosition();
player.reset();
Toast.makeText(getApplicationContext(),"Seek To "+ backupPlayer.getCurrentPosition() + " | " + backupPlayer.isPlaying() + "|" + currentPos, Toast.LENGTH_LONG).show();
Log.e("Huhu","Seek To "+ backupPlayer.getCurrentPosition() + " | " + backupPlayer.isPlaying() + "|" + currentPos);
backupPlayer.seekTo(currentPos); // If you set currentPos = 20000ms or 30000ms backupPlayer can to seek, but if you set currentPos = 10000ms backupPlayer cannot seek !
}
}
}
});
} catch (Exception e) {
e.printStackTrace();
}
}else{
player.setDisplay(holder);
}
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
Log.e("Surface Created","surfaceDestroyed! " + player.getCurrentPosition());
viewHolder = holder;
}
// End MediaPlayer.OnPreparedListener
// Implement VideoMediaController.MediaPlayerControl
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public int getCurrentPosition() {
//Log.printLog(Log.ERROR, "CURRENT :"+player.getCurrentPosition());
int current = 0;
try{
current = player.getCurrentPosition();
}catch(Exception e){
e.printStackTrace();
}
return current;
}
#Override
public int getDuration() {
int duration = 0;
try{
duration = player.getDuration();
}catch(Exception e){
e.printStackTrace();
}
return duration;
}
#Override
public boolean isPlaying() {
boolean isPlaying = false;
try{
isPlaying = player.isPlaying();
}catch(Exception e){
e.printStackTrace();
}
return isPlaying;
}
#Override
public void pause() {
player.pause();
}
#Override
public void seekTo(int i) {
player.seekTo(i);
}
#Override
public void start() {
player.start();
}
#Override
public boolean isFullScreen() {
return isFullscreen;
}
#Override
public void toggleFullScreen() {
// TODO Auto-generated method stub
}
#Override
public void doBackPressed() {
// TODO Auto-generated method stub
}
#Override
public void onClick(View v) {
}
}

play Video in VideoView

In my activity I am trying to play a video which is stored in raw folder. below is my activity.
In the first button I am not getting error also like can't play this video, but only black screen appears. while clicking the second button I am getting a message that can't play this video. below is my activity
package com.example.college;
import android.app.Activity;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.MediaController;
import android.widget.VideoView;
public class FirstYear extends Activity {
Button cse,it,ece,eee;
VideoView vv;
MediaController mc;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.first_year);
cse=(Button)findViewById(R.id.button1);
it=(Button)findViewById(R.id.button2);
ece=(Button)findViewById(R.id.button3);
eee=(Button)findViewById(R.id.button4);
vv=(VideoView)findViewById(R.id.videoView1);
mc=new MediaController(this);
mc.setAnchorView(vv);
cse.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
vv.setVideoURI(Uri.parse("android.resource://com.example.college/"+R.raw.c));
vv.start();
}
});
it.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
vv.setVideoURI(Uri.parse("android.resource://com.example.college/"+R.raw.k));
vv.start();
}
});
ece.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
vv.setVideoURI(Uri.parse("android.resource://com.example.college/"+R.raw.a));
vv.start();
}
});
eee.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
vv.setVideoURI(Uri.parse("android.resource://com.example.college/"+R.raw.s));
vv.start();
}
});
}
}
The code is correct. All the errors are related to video resolution.
I have replaced video with different resolution , and it is working

Android MediaPlayer - onBackPressed() not working

I have an app which just plays the same video in loop. Everything works as expected, except for one thing:
I want to stop the playback if I press the back button, but I am not able to get it to work. My activity simply ignore that I press it and instead I get an ANR. I thought that using onBackPressed() should handle this case.
Can anyone tell me, what I am doing wrong???
Here is my code:
package dk.test.videoplayer;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.media.MediaPlayer.OnVideoSizeChangedListener;
import android.net.Uri;
import android.os.Bundle;
import android.app.Activity;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;
public class MainActivity extends Activity implements
OnBufferingUpdateListener, OnCompletionListener, OnPreparedListener, OnVideoSizeChangedListener, SurfaceHolder.Callback, OnClickListener {
private SurfaceView mSurfaceView = null;
private SurfaceHolder mSurfaceHolder = null;
private String videoPath;
private MediaPlayer mMediaPlayer = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
System.out.println("onCreate called");
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN |
WindowManager.LayoutParams.TYPE_APPLICATION_PANEL |
WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON |
WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD |
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
mSurfaceView = new SurfaceView(this);
setContentView(mSurfaceView);
mSurfaceView.setOnClickListener(this);
mSurfaceHolder = mSurfaceView.getHolder();
mSurfaceHolder.addCallback(this);
videoPath = "android.resource://dk.beatpro.videoplayer/raw/demo_video";
try {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.setOnBufferingUpdateListener(this);
mMediaPlayer.setOnCompletionListener(this);
mMediaPlayer.setOnPreparedListener(this);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setScreenOnWhilePlaying(true);
}
catch (Exception e) {
System.out.println(e.toString());
}
}
#Override
protected void onResume() {
super.onResume();
System.out.println("onResume called");
}
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
}
#Override
public void onPrepared(MediaPlayer mp) {
System.out.println("onPrepared called");
if (!mMediaPlayer.isPlaying())
mMediaPlayer.start();
}
#Override
public void onCompletion(MediaPlayer mp) {
System.out.println("onCompletion() called");
playVideo();
}
#Override
public void onBufferingUpdate(MediaPlayer mp, int percent) {
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
System.out.println("onPause() called");
releaseMediaPlayer();
}
#Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
releaseMediaPlayer();
}
public void surfaceCreated(SurfaceHolder holder) {
System.out.println("surfaceCreated() called");
mMediaPlayer.setDisplay(mSurfaceHolder);
playVideo();
}
private void playVideo() {
System.out.println("playVideo() called");
try {
mMediaPlayer.reset();
mMediaPlayer.setDataSource(this, Uri.parse(videoPath));
mMediaPlayer.setDisplay(mSurfaceHolder);
mMediaPlayer.prepareAsync();
}
catch (Exception e) {
System.out.println(e.toString());
}
}
private void releaseMediaPlayer() {
if (mMediaPlayer != null) {
if (mMediaPlayer.isPlaying())
mMediaPlayer.stop();
mMediaPlayer.release();
mMediaPlayer = null;
}
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
System.out.println("surfaceChanged() called");
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
System.out.println("surfaceDestroyed() called");
}
#Override
public void onBackPressed() {
System.out.println("onBackPressed() called");
releaseMediaPlayer();
super.onBackPressed();
}
#Override
public boolean onTouchEvent(MotionEvent event) {
// TODO Auto-generated method stub
Toast.makeText(this, "Touch event", Toast.LENGTH_SHORT).show();
return super.onTouchEvent(event);
}
#Override
public void onClick(View v) {
System.out.println("onClick() called");
Toast.makeText(this, "Click click", Toast.LENGTH_SHORT).show();
}
}
Call super.onBackPressed(); before your code in onBackPressed(..)
#Override
public void onBackPressed() {
super.onBackPressed();
System.out.println("onBackPressed() called");
releaseMediaPlayer();
}
Just call super.onBackPressed before releasing media player.
EDIT:
Also try removing the
mMediaPlayer=null;
statement in your releaseMediaPlayer() method.

Animate weapon ontouch

Hello everyone I would like to implement a method to touch on my image of a ak47, I have written the code but the method does not work on touch as it should. I would like that if you touch the gun that starts the repetition in my code. Thanks in advance
package org.realgunshot;
import android.app.Activity;
import android.app.ActionBar.LayoutParams;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
public class B2 extends Activity {
ImageView bulletshot,bulletempty ;
Boolean click=true;
TextView Display;
Button b1;
int counter = 15 ;
Object mediaPlayerspara,mediaPlayersload;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.b2);
bulletshot=(ImageView)findViewById(R.id.bulletshot);
bulletempty=(ImageView)findViewById(R.id.bulletempty);
b1 = (Button)findViewById(R.id.b1);
Display = (TextView)findViewById(R.id.counter);
final Animation animRotate = AnimationUtils.loadAnimation(this, R.anim.gun);
final Animation animgunshot = AnimationUtils.loadAnimation(this, R.anim.gunshot);
final Animation animbulletempty = AnimationUtils.loadAnimation(this, R.anim.bulletempty);
b1.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
counter --;
Display.setText(""+counter);
if(counter <= 0)
{
counter=1;
mediaPlayerspara = null;
mediaPlayersload = MediaPlayer.create(getBaseContext(),R.raw.sload);
((MediaPlayer) mediaPlayersload).setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayersload) {
// TODO Auto-generated method stub
mediaPlayersload.start();
mediaPlayersload.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayersload) {
mediaPlayersload.release();
};
});
}
});
}
else{
bulletshot.setVisibility(View.VISIBLE);
bulletshot.startAnimation(animgunshot);
Handler handlers = new Handler();
handlers.postDelayed(new Runnable() {
public void run() {
bulletshot.setVisibility(View.GONE);
bulletempty.setVisibility(View.GONE);
}
}, 300);
bulletempty.setVisibility(View.VISIBLE);
bulletempty.startAnimation(animbulletempty);
Handler handlers2 = new Handler();
handlers2.postDelayed(new Runnable() {
public void run() {
bulletshot.setVisibility(View.GONE);
bulletempty.setVisibility(View.GONE);
}
}, 2000);
v.startAnimation(animRotate);
final Button button1 = (Button)findViewById(R.id.b1);
button1.setBackgroundResource(R.drawable.ak47_1);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
button1.setBackgroundResource(R.drawable.ak47_0);
}
}, 100);
mediaPlayerspara = MediaPlayer.create(getBaseContext(),R.raw.ak47);
((MediaPlayer) mediaPlayerspara).setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayerspara) {
// TODO Auto-generated method stub
mediaPlayerspara.start();
mediaPlayerspara.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayerspara) {
mediaPlayerspara.release();
};
});
}
});}
if(event.getAction() == MotionEvent.ACTION_UP){
return true;
}
return false;
}
});
Button apri = (Button)findViewById(R.id.loadoadd);
apri.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
LayoutInflater layoutInflater= (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
final View popupView = layoutInflater.inflate(R.layout.loadoadd, null);
final PopupWindow popupWindow = new PopupWindow(popupView,LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
popupWindow.setAnimationStyle(R.style.Animation);
Button chiudi1 = (Button)popupView.findViewById(R.id.dismiss);
chiudi1.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
popupWindow.dismiss();
}});
Button load = (Button)popupView.findViewById(R.id.load);
load.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter = 15;
Display.setText(""+counter);
}});
Button add = (Button)popupView.findViewById(R.id.add);
add.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
counter = 1015;
Display.setText(""+counter);
}});
if (click){
popupWindow.showAtLocation(chiudi1, Gravity.CENTER, 0, 0);
click=false;
}else{
popupWindow.dismiss();
click=true;
}
}});
}
}
I don't think anyone can help you - unless you post your code fully. There are so many things missing...Your OnTouchListener doesn't even check for touch events such as ACTION_DOWN, ACTION_MOVE or anything else.
I would suggest that you take the action when user taps i.e.
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
// Do your firing even
break;
case MotionEvent.ACTION_UP:
//action when user removes finger.
break;
default:
return false;
} // end of switch case
return true;
}
Also, just add a break point in onTouch() and debug to know what is happening and what part is not executing and fix it accordingly.
package org.realgunshot;
import android.app.Activity;
import android.app.ActionBar.LayoutParams;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.os.Handler;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.PopupWindow;
import android.widget.TextView;
public class B2 extends Activity {
ImageView proiettilesparo,proiettilevuoto ;
Boolean click=true;
TextView Display;
Button b1;
int contatore = 15 ;
Object mediaPlayerspara,mediaPlayerscarica;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.b2);
proiettilesparo=(ImageView)findViewById(R.id.proiettilesparo);
proiettilevuoto=(ImageView)findViewById(R.id.proiettilecade);
b1 = (Button)findViewById(R.id.b1);
Display = (TextView)findViewById(R.id.contatore);
final Animation animRotate = AnimationUtils.loadAnimation(this, R.anim.pistola);
final Animation animsparoproiettile = AnimationUtils.loadAnimation(this, R.anim.sparoproiettile);
final Animation animproiettilecade = AnimationUtils.loadAnimation(this, R.anim.proiettilecade);
b1.setOnTouchListener(new OnTouchListener() {
private Handler mHandler;
#Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()) {
case MotionEvent.ACTION_DOWN:
if (mHandler != null) return true;
mHandler = new Handler();
mHandler.postDelayed(mAction, 1);
break;
case MotionEvent.ACTION_UP:
if (mHandler == null) return true;
mHandler.removeCallbacks(mAction);
mHandler = null;
break;
}
return false;
}
Runnable mAction = new Runnable() {
#Override public void run() {
contatore --;
Display.setText(""+contatore);
if(contatore <= 0)
{
contatore=1;
mediaPlayerspara = null;
mediaPlayerscarica = MediaPlayer.create(getBaseContext(),R.raw.scarica);
((MediaPlayer) mediaPlayerscarica).setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayerscarica) {
// TODO Auto-generated method stub
mediaPlayerscarica.start();
mediaPlayerscarica.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayerscarica) {
mediaPlayerscarica.release();
};
});
}
});
}
else{
proiettilesparo.setVisibility(View.VISIBLE);
proiettilesparo.startAnimation(animsparoproiettile);
Handler handlers = new Handler();
handlers.postDelayed(new Runnable() {
public void run() {
proiettilesparo.setVisibility(View.GONE);
proiettilevuoto.setVisibility(View.GONE);
}
}, 300);
proiettilevuoto.setVisibility(View.VISIBLE);
proiettilevuoto.startAnimation(animproiettilecade);
Handler handlers2 = new Handler();
handlers2.postDelayed(new Runnable() {
public void run() {
proiettilesparo.setVisibility(View.GONE);
proiettilevuoto.setVisibility(View.GONE);
}
}, 2000);
b1.startAnimation(animRotate);
final Button button1 = (Button)findViewById(R.id.b1);
button1.setBackgroundResource(R.drawable.ak47_1);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
button1.setBackgroundResource(R.drawable.ak47_0);
}
}, 100);
mediaPlayerspara = MediaPlayer.create(getBaseContext(),R.raw.ak47);
((MediaPlayer) mediaPlayerspara).setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayerspara) {
// TODO Auto-generated method stub
mediaPlayerspara.start();
mediaPlayerspara.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer mediaPlayerspara) {
mediaPlayerspara.release();
};
});
}
});}
mHandler.postDelayed(this, 100);
}
};
});
Button apri = (Button)findViewById(R.id.caricaoaggiungi);
apri.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
LayoutInflater layoutInflater= (LayoutInflater)getBaseContext().getSystemService(LAYOUT_INFLATER_SERVICE);
final View popupView = layoutInflater.inflate(R.layout.caricaoaggiungi, null);
final PopupWindow popupWindow = new PopupWindow(popupView,LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT);
popupWindow.setAnimationStyle(R.style.Animation);
Button chiudi1 = (Button)popupView.findViewById(R.id.dismiss);
chiudi1.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
popupWindow.dismiss();
}});
Button carica = (Button)popupView.findViewById(R.id.carica);
carica.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
contatore = 15;
Display.setText(""+contatore);
}});
Button aggiungi = (Button)popupView.findViewById(R.id.aggiungi);
aggiungi.setOnClickListener(new Button.OnClickListener(){
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
contatore = 1015;
Display.setText(""+contatore);
}});
if (click){
popupWindow.showAtLocation(chiudi1, Gravity.CENTER, 0, 0);
click=false;
}else{
popupWindow.dismiss();
click=true;
}
}});
}
I changed it this way, but every time the animation starts from 0, there is a way to continue an action and does not stop and start it again?

setBackgroundResource of TextView in listitem

I've got an activity that presents a listview of tracks of songs. When an item is clicked, it streams the appropriate media file. I have a textview in each row that displays the length of the track. When the track is playing, I switch the backgroundresource of the textview in the row to a pause button drawable. In other words, when it's ready to play, it displays a play button and when its currently playing it displays a pause button. Simple enough....
Currently, I'm doing something like this to set the drawable to pause button if the mediaplayer is playing:
if(mp.isPlaying()) {
_player.setBackgroundResource(R.drawable.pausebtn);
_player.setText(" :" + String.valueOf(mp.getDuration()/1000));
I'm doing this in my Runnable which has the mediaplayer callback of onPrepared.
Problem is that I need the drawable to be set in THAT list item, i.e. the one which was clicked and whose track is being played. How can I grab hold of which one was clicked and set ITS textview to the new drawable?
Here's the full code:
package com.me.player
import java.net.URL;
import java.util.ArrayList;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import android.content.Context;
import android.graphics.Color;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.media.MediaPlayer.OnErrorListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.view.Gravity;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
import com.mtv.datahandler.Artist;
import com.mtv.datahandler.DataBaseHelper;
import com.mtv.datahandler.Track;
import com.mycompany.http.HttpRequest;
public class ArtistAudio extends ControllerActivity implements OnCompletionListener, OnPreparedListener, OnErrorListener{
private int METHOD_TYPE = 0;
private static final int GET_AUDIO = 1;
int CURRENT_POSITION = 0;
int DURATION = 0;
public static final String AUDIO_FEED_URL = "http://direct.rhapsody.com/metadata/data/getTopTracksForArtist.xml?blabla";
public static final int MAX_TRACKS = 200;
ArrayList<Track> tracks = new ArrayList<Track>();
Artist artist;
private MediaPlayer mp;
private int mSongPlaying = 0;
TextView _player;
#Override
protected void progressRunnableComplete() {
if(isFinishing()){
return;
}
if(METHOD_TYPE == GET_AUDIO){
setList();
}
}
public void setList(){
ListView listview = (ListView)findViewById(R.id.ListView01);
// ListView listview = (ListView)findViewById(R.id.ListView01);
if(listview == null){
setContent(R.layout.artistaudio);
listview = (ListView)findViewById(R.id.ListView01);
}
// listview.addHeaderView();
listview.setCacheColorHint(0);
listview.setAdapter(new TrackListAdapter());
listview.setSelector(R.drawable.listbackground);
listview.setDividerHeight(1);
listview.setDivider(getResources().getDrawable(R.drawable.img_dotted_line_horz));
listview.setOnItemClickListener(new OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> arg0, View arg1,
int arg2, long arg3) {
// TODO Auto-generated method stub
TrackClicked(arg2);
}
});
}
public void TrackClicked(int arg2){
mSongPlaying = arg2;
Track track = tracks.get(arg2);
String url = track.requestInfo("previewURL");
mHandler.post(new PlaySong(url));
// mHandler.post(new PlaySong("http://dc237.4shared.com/img/315443275/33f14ef2/dlink__2Fdownload_2F9y5VGjVt_3Ftsid_3D20100705-131850-40aa0b87/preview.mp3"));
}
public void setDuration(int n) {
DURATION = n;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setTitle("Audio Clips");
setContent(R.layout.artistaudio);
Object o = getIntent().getParcelableExtra("artist");
if(o!=null){
artist = (Artist)o;
}
progressRunnable(new Runnable(){
public void run(){
getTracks();
}
}, "Loading. Please Wait...",false);
}
protected void getTracks() {
METHOD_TYPE = GET_AUDIO;
if(!DataBaseHelper.isOnline(this)){
RUNNABLE_STATE = RUNNABLE_FAILED;
return;
}
HttpRequest req;
try {
req = new HttpRequest(new URL(AUDIO_FEED_URL+artist.requestInfo("rhapsodyID")));
Document doc = req.AutoXMLNoWrite();
NodeList items = doc.getElementsByTagName("e");
tracks= new ArrayList<Track>();
for(int i=0; i<items.getLength(); i++){
Track newsitem = new Track(items.item(i));
tracks.add(newsitem);
}
RUNNABLE_STATE = RUNNABLE_SUCCESS;
} catch (Throwable e) {
RUNNABLE_STATE = RUNNABLE_FAILED;
e.printStackTrace();
}
}
public void onPause(){
super.onPause();
try{mp.stop();}catch(Exception e){e.printStackTrace();}
try{mp.reset();}catch(Exception e){e.printStackTrace();}
try{mp.release();}catch(Exception e){e.printStackTrace();}
mp = null;
}
private class TrackListAdapter extends BaseAdapter{
#Override
public int getCount() {
// TODO Auto-generated method stub
return tracks.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return tracks.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
AudioCell blogView = null;
if (convertView != null) {
if(convertView.getClass() == TextView.class){
convertView = null;
}
}
if (convertView == null) {
blogView = new AudioCell(parent.getContext());
}
else {
blogView = (AudioCell) convertView;
}
blogView.display(position);
return blogView;
}
}
/** this class is responsible for rendering the data in the model, given the selection state */
class AudioCell extends RelativeLayout {
TextView _title;
int currentPosition;
public AudioCell(Context mContext) {
super(mContext);
_createUI(mContext);
}
/** create the ui components */
private void _createUI(Context m) {
RelativeLayout.LayoutParams params;
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
_player = new TextView(m);
_player.setId(2);
_player.setBackgroundResource(R.drawable.playbtn);
_player.setText(":30");
addView(_player);
params.addRule(RelativeLayout.CENTER_VERTICAL,1);
_player.setLayoutParams(params);
_title = new TextView(m);
_title.setTextColor(Color.BLACK);
params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,(int)(44*metrics.density));
params.addRule(RelativeLayout.CENTER_VERTICAL,1);
params.addRule(RelativeLayout.RIGHT_OF, _player.getId());
params.setMargins(0, 10, 0, 10);
_title.setGravity(Gravity.CENTER_VERTICAL);
_title.setLayoutParams(params);
_title.setId(102);
addView(_title);
params = new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT,(int)(44*metrics.density));
// _player.setOnClickListener(new View.OnClickListener() {
//
// #Override
// public void onClick(View v) {
// PlaySong.PlaySong("http://http://www.noiseaddicts.com/samples/2544.mp3");
//
// }
// });
//
}
/** update the views with the data corresponding to selection index */
public void display(int index) {
_title.setText(tracks.get(index).requestInfo("name"));
}
}
private class PlaySong implements Runnable{
String songURL;
public PlaySong(String url){
songURL = url;
}
public void run(){
try{mp.stop();}catch(Exception e){e.printStackTrace();}
try{mp.reset();}catch(Exception e){e.printStackTrace();}
if(mp==null){
createPlayer();
}
try{mp.reset();}catch(Exception e){e.printStackTrace();}
try{mp.setAudioStreamType(AudioManager.STREAM_MUSIC);}catch(Exception e){e.printStackTrace();}
try{mp.setDataSource(songURL);}catch(Exception e){e.printStackTrace();}
try{mp.prepareAsync();}catch(Exception e){e.printStackTrace();}
}
}
public void createPlayer(){
mp = new MediaPlayer();
mp.setOnCompletionListener(this);
mp.setOnPreparedListener(this);
mp.setOnErrorListener(this);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
#Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
try{mp.reset();}catch(Exception e){e.printStackTrace();}
// if(mSongPlaying<tracks.size()-1)
// {
// TrackClicked(mSongPlaying+1);
// }
_player.setBackgroundResource(R.drawable.playbtn);
}
#Override
public void onPrepared(MediaPlayer inMP) {
// TODO Auto-generated method stub
mp.start();
if(mp.isPlaying()) {
_player.setBackgroundResource(R.drawable.pausebtn);
_player.setText(" :" + String.valueOf(mp.getDuration()/1000));
}
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
// TODO Auto-generated method stub
return false;
}
}
As you can see, my inner class AudioCell which extends RelativeLayout is what I'm using for the rows of my ListView....
Any thoughts? Where should I be setting the drawable and how can I make sure it does it only for the row that was clicked (i.e. for the track that's actually being played).
change the TrackClicked method's siggnature. pass both arg1 and arg3 from onItemClick and in the TrackClicked method do this arg1.setBackgroundResource(R.drawable.thebackground);
Inside your TrackClicked method, add this:
getAdapter().getChildAt(arg2).setBackgroundResource(R.drawable.thebackground);

Categories

Resources