How to set TextView Text as dynamically for scrolling marquee.
Please Help me Thanks Advance.
The Listview used for getting the list item to be played in the audio player is as follows.
public class Audiovediolist extends Activity implements OnItemClickListener {
private ListView audioList;
private Intent frmHome;
private ArrayList<HashMap<String, String>> dataList;
private HashMap<String, String> map;
private HashMap<String, String> data;
private int Screen_Id;
String name;
String mSign[] ={"1","2","3","4","5"};
Integer mImages[] = { R.drawable.m, R.drawable.v,
R.drawable.mm, R.drawable.k, R.drawable.s};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_RIGHT_ICON);
setContentView(R.layout.list);
frmHome = getIntent();
getIntentValues();
initUI();
setUI();
uiListener();
}
private void initUI() {
audioList = (ListView) findViewById(R.id.audiolist_listView);
dataList = new ArrayList<HashMap<String, String>>();
}
private void uiListener() {
audioList.setOnItemClickListener(this);
}
private void getIntentValues() {
String id = frmHome.getStringExtra("Activity_Id");
Screen_Id = Integer.parseInt(id);
if (Screen_Id == 1) {
getWindow().setFeatureDrawableResource(Window.FEATURE_RIGHT_ICON,
R.drawable.audioo);
this.setTitle(getResources().getString(R.string.audio));
this.setTitleColor(getResources().getColor(R.color.Beige));
} else {
this.setTitle(getResources().getString(R.string.video));
this.setTitleColor(getResources().getColor(R.color.Beige));
getWindow().setFeatureDrawableResource(Window.FEATURE_RIGHT_ICON,
R.drawable.videoo);
}
}
private void setAdapter() {
SimpleAdapter adapter = new SimpleAdapter(this, dataList,
R.layout.list_row, new String[] { "Image", "text" },
new int[] {
R.id.audiolist_row_img, R.id.audiolist_row_tv });
audioList.setAdapter(adapter);
}
private void setUI() {
for (int a = 0; a <= 11; a++) {
map = new HashMap<String, String>();
map.put("Image", "" + mImages[a]);
map.put("text", mSign[a]);
dataList.add(map);
map = null;
}
}
#Override
protected void onStart() {
super.onStart();
setAdapter();
}
#Override
public void onBackPressed() {
super.onBackPressed();
System.gc();
}
/*private class NextTask extends AsyncTask<Void,Void,Void> {
ProgressDialog progressDailog = new ProgressDialog(Audiovediolist.this);
#Override
protected void onPreExecute() {
super.onPreExecute();
progressDailog.setTitle("Please Wait");
progressDailog.setMessage("URL Data Loading ...");
progressDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
progressDailog.setCancelable(true);
progressDailog.show();
}
#SuppressWarnings("static-access")
#Override
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
progressDailog.dismiss();
}
}*/
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
data = dataList.get(position);
try {
NetWorkCheck netWork = new NetWorkCheck();
if (netWork.isNetWorkConnection(this)) {
if (Screen_Id == 1) {
// new NextTask().execute();
Intent audioInt=new Intent(getApplicationContext(),AudioView.class);
audioInt.setType(data.get("text"));
startActivity(audioInt);
} else if (Screen_Id == 2) {
Intent vedioInt = new Intent(this, VideoPlayActivity.class);
vedioInt.setType(data.get("text"));
startActivity(vedioInt);
}
} else {
netWork.alert();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "Problem while ListItemClick", Toast.LENGTH_SHORT).show();
}
}
}
The code for audio player used is
public class AudioView extends Activity implements OnClickListener {
private MediaPlayer mMediaPlayer;
private ImageView mPlay;
private ImageView mPause;
private ImageView mBack;
private ImageView mFar;
private ProgressBar myProgressBar;
// private PlayerService mService;
private boolean boolFlag = false;
private boolean isPausedInCall = false;
private String url;
private TelephonyManager mTelephoneMgr;
private NotificationManager mNotificationManager;
private int SIMPLE_NOTFICATION_ID;
private TextView tv;
// private boolean serviceRunning;
Notification notifyDetails;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.audio_main);
getIntentValues();
initUI();
uiListener();
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notifyDetails = new Notification(R.drawable.mulug_icon, url,
System.currentTimeMillis());
mTelephoneMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if (mTelephoneMgr != null) {
mTelephoneMgr.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
}
}
private void getIntentValues() {
url = getIntent().getType();
}
private void uiListener() {
mPlay.setOnClickListener(this);
mPlay.setOnClickListener(this);
mPause.setOnClickListener(this);
mPause.setVisibility(android.view.View.INVISIBLE);
mBack.setOnClickListener(this);
mFar.setOnClickListener(this);
}
private void initUI() {
tv = (TextView) findViewById(R.id.text);
mBack = (ImageView) findViewById(R.id.back);
mPlay = (ImageView) findViewById(R.id.play);
mPause = (ImageView) findViewById(R.id.pause);
mFar = (ImageView) findViewById(R.id.fwd);
myProgressBar = (ProgressBar) findViewById(R.id.progressbar_Horizontal);
myProgressBar.setProgressDrawable(getResources().getDrawable(
R.drawable.green_progress));
myProgressBar.setProgress(0);
tv.setText(url);
tv.setFocusable(true);
}
private Thread myThread = new Thread() {
public void run() {
while (mMediaPlayer.getCurrentPosition() < mMediaPlayer
.getDuration()) {
try {
myProgressBar
.setProgress(mMediaPlayer.getCurrentPosition());
} catch (Throwable t) {
}
}
}
};
#SuppressLint("NewApi")
#Override
public void onBackPressed() {
super.onBackPressed();
mMediaPlayer.stop();
// myThread.stop();
// mMediaPlayer.release();
mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
System.gc();
}
#Override
protected void onDestroy() {
super.onDestroy();
System.gc();
}
#SuppressLint("NewApi")
#Override
protected void onStart() {
super.onStart();
this.setProgressBarIndeterminateVisibility(true);
try {
if (boolFlag == false) {
System.out.println(FinalConstants.URL + "mobile-audio/" + url
+ ".mp3");
mMediaPlayer = MediaPlayer.create(
this,
Uri.parse(FinalConstants.URL + "mobile-audio/" + url
+ ".mp3"));
}
myProgressBar.setMax(mMediaPlayer.getDuration());
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Loading Problems",
Toast.LENGTH_SHORT).show();
Log.e("ERRORS", "ServerFailed to Load...");
super.onBackPressed();
e.printStackTrace();
}
}
public PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
System.out.println("ringing state");
if (mMediaPlayer != null) {
pauseMedia();
isPausedInCall = true;
}
notificationShow();
}
if (state == TelephonyManager.CALL_STATE_IDLE) {
System.out.println("callState Idle");
if (mMediaPlayer != null) {
if (isPausedInCall) {
isPausedInCall = false;
playMedia();
}
}
}
if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
}
super.onCallStateChanged(state, incomingNumber);
}
};
private void pauseMedia() {
mMediaPlayer.pause();
changePlayerIcons(false);
}
private void playMedia() {
mMediaPlayer.start();
changePlayerIcons(true);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.play:
if (!boolFlag) {
try {
notificationShow();
mMediaPlayer.setLooping(false);
// mMediaPlayer.prepareAsync();
} catch (Exception e) {
Toast.makeText(this, "preparing", Toast.LENGTH_SHORT)
.show();
}
boolFlag = true;
mMediaPlayer.start();
myThread.start();
} else {
notificationShow();
mMediaPlayer.getCurrentPosition();
mMediaPlayer.start();
}
changePlayerIcons(true);
myProgressBar.setProgress(mMediaPlayer.getCurrentPosition());
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
changePlayerIcons(false);
myProgressBar.setProgress(0);
onStart();
}
});
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
}
});
mMediaPlayer.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Toast.makeText(getApplicationContext(),
"MediaPlayer Errors", Toast.LENGTH_SHORT).show();
Log.e("ERRORS", "MediaPlayer Errors...");
return false;
}
});
break;
case R.id.pause:
mMediaPlayer.pause();
mPlay.setVisibility(android.view.View.VISIBLE);
mPause.setVisibility(android.view.View.INVISIBLE);
break;
case R.id.back:
int dur = mMediaPlayer.getCurrentPosition();
int pos = (dur > 10000 ? dur - 5000 : 0);
mMediaPlayer.seekTo(pos);
break;
case R.id.fwd:
int curpos = mMediaPlayer.getCurrentPosition();
int dur2 = mMediaPlayer.getDuration();
int pos2 = (curpos + 5000 > dur2 ? dur2 : curpos + 5000);
mMediaPlayer.seekTo(pos2);
break;
}
}
private void notificationShow() {
Context context = getApplicationContext();
CharSequence contentTitle = "Mulugu Running";
CharSequence contentText = url + " Weekly Predictions";
Intent notifyIntent = new Intent(AudioView.this, AudioView.class);
PendingIntent intent = PendingIntent.getActivity(AudioView.this, 0,
notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
notifyDetails.setLatestEventInfo(context, contentTitle, contentText,
intent);
mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
}
private void changePlayerIcons(boolean b) {
if (b) {
mPlay.setVisibility(android.view.View.INVISIBLE);
mPause.setVisibility(android.view.View.VISIBLE);
} else {
mPlay.setVisibility(android.view.View.VISIBLE);
mPause.setVisibility(android.view.View.INVISIBLE);
}
}
}
The XML used is
<?xml version="1.0" encoding="UTF-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/main_audio"
android:orientation="horizontal" >
<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:gravity="center"
android:orientation="vertical" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="0.45"
android:orientation="vertical" >
<TextView
android:id="#+id/text"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginBottom="2dp"
android:ellipsize="marquee"
android:focusable="true"
android:focusableInTouchMode="true"
android:gravity="center_horizontal"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:singleLine="true"
android:text=" for more details check on "
android:textColor="#FF0000"
android:textSize="20dp"
android:textStyle="italic" >
</TextView>
</LinearLayout>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_margin="3dp" >
<ImageView
android:id="#+id/pause"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginTop="10dp"
android:src="#drawable/audio_pause" />
<ImageView
android:id="#+id/play"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:layout_marginLeft="2dp"
android:layout_marginTop="10dp"
android:src="#drawable/audio_play" />
<ImageView
android:id="#+id/back"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/pause"
android:layout_marginRight="1dp"
android:layout_toLeftOf="#+id/pause"
android:layout_toRightOf="#drawable/audio_play"
android:src="#drawable/audio_bwd" />
<ImageView
android:id="#+id/fwd"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignTop="#+id/pause"
android:layout_marginLeft="1dp"
android:layout_toRightOf="#+id/pause"
android:src="#drawable/audio_fwd" />
</RelativeLayout>
<ProgressBar
android:id="#+id/progressbar_Horizontal"
style="?android:attr/progressBarStyleHorizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</LinearLayout>
</LinearLayout>
Here is an example:
public class TextViewMarquee extends Activity {
private TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
tv = (TextView) this.findViewById(R.id.tv);
tv.setSelected(true); // Set focus to the textview
}
}
The xml file with the textview:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/tv"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:lines="1"
android:ellipsize="marquee"
android:fadingEdge="horizontal"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:textColor="#ff4500"
android:text="Simple application that shows how to use marquee, with a long text" />
</RelativeLayout>
Related
I'm working in video view that contain title layout. I have attached the header layout in video view. what is my problem is when i touch on video view both title layou and mediacontolls should shown, After some time both(title layou and media controls) should disappear. Simply whenever the media controlls show the title layou should show , then whenever media controlls disapper the title layou should disapper.
XML CODE
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:background="#000">
<RelativeLayout
android:layout_width="fill_parent"
android:layout_height="match_parent">
<VideoView
android:id="#+id/playerview"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_alignParentRight="true"
android:layout_centerInParent="true"
android:layout_gravity="center_vertical" />
<LinearLayout
android:id="#+id/share_layout"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:color/transparent"
android:padding="10dp"
android:layout_alignParentBottom="true"
android:layout_alignParentRight="true"
android:layout_alignParentEnd="true"
android:layout_marginBottom="80dp"
android:orientation="horizontal">
<ImageButton
android:id="#+id/twitter_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/twitter"
android:paddingTop="20dp"
android:paddingRight="10dp"
android:background="#android:color/transparent" />
<ImageButton
android:id="#+id/facebook_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/facebook"
android:paddingRight="10dp"
android:layout_below="#+id/twitter_button"
android:background="#android:color/transparent"
android:paddingTop="20dp"/>
<ImageButton
android:visibility="gone"
android:id="#+id/share_Button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/share_icon"
android:background="#android:color/transparent"
android:paddingTop="20dp"
android:layout_below="#+id/facebook_button"/>
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/header_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#BF000000"
android:padding="10dp">
<ImageButton
android:id="#+id/imageBtnclose"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/close_button"
android:background="#android:color/transparent" />
<TextView
android:id="#+id/videoTitletv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_weight="1"
android:gravity="center_vertical"
android:text="video title"
android:textColor="#ffffff"
android:paddingLeft="10dp"
android:layout_centerVertical="true"
android:layout_toRightOf="#+id/imageBtnclose"
android:layout_toEndOf="#+id/imageBtnclose" />
</RelativeLayout>
JAVA CODE
public class VideoAdPlayer extends Activity {
// private boolean vbBackkeyPressed = false;
private VideoView myVideoView;
private RelativeLayout myLinearClose;
LinearLayout shareLayout;
private ProgressDialog progressDialog;
private MediaController mediaControls;
private int adshowTime = 30;
Timer mTimer = new Timer();
boolean MidrollPlayed = false;
YuMeInterface yumeInterface;
ImageButton imgCloseBtn;
boolean isPortrait = true;
ImageButton faceBookButton, twitterButton, shareButton;
public static VideoAdPlayer playerActivity = null;
public static Context playerContext = null;
public static int playedAdType = 1;
public static boolean isActivityrun = false;
boolean isPrerollAds;
boolean isPostrollAds;
boolean isMidrollAds;
boolean isShareClicked = false;
#SuppressLint("ClickableViewAccessibility")
#SuppressWarnings("deprecation")
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
String myString = android.os.Build.VERSION.RELEASE;
System.out.println(myString);
setContentView(R.layout.video);
Intent intent = getIntent();
String playVideoUrl = "";
String videoThumb = "";
getActionBar().hide();
playerActivity = this;
playerContext = this.getApplicationContext();
myLinearClose = (RelativeLayout) findViewById(R.id.header_layout);
shareLayout = (LinearLayout) findViewById(R.id.share_layout);
TextView videoTxtview = (TextView)findViewById(R.id.videoTitletv);
faceBookButton = (ImageButton) findViewById(R.id.facebook_button);
twitterButton = (ImageButton) findViewById(R.id.twitter_button);
shareButton = (ImageButton) findViewById(R.id.share_Button);
shareLayout.setOrientation(LinearLayout.HORIZONTAL);
videoTxtview.setText("DEFAULT TITLE");
if (mediaControls == null) {
mediaControls = new MediaController(VideoAdPlayer.this);
}
myVideoView = (VideoView) findViewById(R.id.playerview);
imgCloseBtn = (ImageButton) findViewById(R.id.imageBtnclose);
progressDialog = createProgressDialog(VideoAdPlayer.this);
progressDialog.show();
imgCloseBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
JSONObject msgPlayer = new JSONObject();
try {
msgPlayer.put("finished", false);
YumeIntegration.callbackContext.success(msgPlayer);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
finish();
}
});
try {
myVideoView.setVideoURI(Uri.parse(playVideoUrl));
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
myVideoView.requestFocus();
myVideoView.setZOrderOnTop(false);
playedAdType = 1;
myVideoView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if (!myLinearClose.isShown()) {
if (!isPortrait) {
myLinearClose.setVisibility(View.VISIBLE);
}
myLinearClose.postDelayed(new Runnable() {
#Override
public void run() {
if (!isPortrait) {
myLinearClose.setVisibility(View.INVISIBLE);
}
}
}, 3000);
} else {
if (myLinearClose.isShown()) {
if (!isPortrait) {
myLinearClose.setVisibility(View.INVISIBLE);
}
}
}
return false;
}
});
myVideoView.setMediaController(mediaControls);
myVideoView.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(final MediaPlayer mediaPlayer) {
progressDialog.dismiss();
myLinearClose.setVisibility(View.VISIBLE);
int duration = myVideoView.getDuration();
Log.e("total duration", String.valueOf(duration));
final int totalSeconds = duration / 1000;
final int postrollads = totalSeconds - 25;
final int MidrollAdsShows = totalSeconds / 2;
Log.e("total durationin secods", String.valueOf(totalSeconds));
try {
mTimer.scheduleAtFixedRate(new TimerTask() {
#Override
public void run() {
int currentTime = myVideoView.getCurrentPosition() / 1000;
/*
* if (currentTime > postrollads &&
* !postRolladsInit) { postRolladsInit = true; try {
* yumeInterface.updatesSdkParams(3); } catch
* (YuMeException e) { e.printStackTrace(); }
*
* } */
if (currentTime > MidrollAdsShows && !MidrollPlayed) {
adshowTime += 30;
MidrollPlayed = true;
playedAdType = 2;
if (isMidrollAds) {
if (yumeInterface.sdkIsAdAvailable()) {
myVideoView.pause();
final Intent mainIntent = new Intent(VideoAdPlayer.this, AdView.class);
startActivityForResult(mainIntent, 3);
}
}
}
}
}, 0, 2000);
if (!mediaControls.isShowing()) {
mediaControls.show();
Toast.makeText(VideoAdPlayer.this,"YES",Toast.LENGTH_SHORT).show();
}
myLinearClose.setVisibility(View.VISIBLE);
myLinearClose.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if (!isPortrait){
myLinearClose.setVisibility(View.INVISIBLE);
}
}
}, 3000);
} catch (Exception ex) {
}
}
});
myVideoView.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
mTimer.cancel();
JSONObject msgPlayer = new JSONObject();
try {
msgPlayer.put("finished", true);
YumeIntegration.callbackContext.success(msgPlayer);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
playedAdType = 3;
// finish();
if (isPostrollAds) {
if (yumeInterface.sdkIsAdAvailable()) {
final Intent mainIntent = new Intent(VideoAdPlayer.this, AdView.class);
startActivityForResult(mainIntent, 3);
} else {
finish();
}
} else {
finish();
}
}
});
public static ProgressDialog createProgressDialog(Context mContext) {
ProgressDialog dialog = new ProgressDialog(mContext);
try {
dialog.show();
} catch (BadTokenException e) {
}
dialog.setCancelable(false);
dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.setContentView(R.layout.progressdialog);
// dialog.setMessage(Message);
return dialog;
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
// check if the request code is same as what is passed here it is 3
if (requestCode == 3) {
myVideoView.requestFocus();
myVideoView.start();
myVideoView.setZOrderOnTop(false);
}
}
#Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
myLinearClose.setVisibility(View.VISIBLE);
shareLayout.setOrientation(LinearLayout.VERTICAL);
myVideoView.requestFocus();
isPortrait = false;
landscapeMode();
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT) {
shareLayout.setOrientation(LinearLayout.HORIZONTAL);
myVideoView.requestFocus();
isPortrait = true;
myLinearClose.setVisibility(View.VISIBLE);
portraitMode();
}
}
private void portraitMode() {
isPortrait = true;
faceBookButton.setVisibility(View.VISIBLE);
twitterButton.setVisibility(View.VISIBLE);
shareButton.setVisibility(View.VISIBLE);
shareButton.setVisibility(View.GONE);
if (!mediaControls.isShowing()) {
mediaControls.show();
Toast.makeText(VideoAdPlayer.this, "YES", Toast.LENGTH_SHORT).show();
}
myLinearClose.setVisibility(View.VISIBLE);
myLinearClose.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if (!isPortrait) {
myLinearClose.setVisibility(View.INVISIBLE);
}
}
}, 3000);
}
private void landscapeMode() {
isPortrait = false;
if (!mediaControls.isShowing()) {
mediaControls.show();
Toast.makeText(VideoAdPlayer.this, "YES", Toast.LENGTH_SHORT).show();
}
myLinearClose.setVisibility(View.VISIBLE);
myLinearClose.postDelayed(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
if (!isPortrait) {
myLinearClose.setVisibility(View.INVISIBLE);
}
}
}, 3000);
faceBookButton.setVisibility(View.GONE);
twitterButton.setVisibility(View.GONE);
shareButton.setVisibility(View.VISIBLE);
shareButton.setVisibility(View.VISIBLE);
shareButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!isPortrait) {
if (!isShareClicked) {
isShareClicked = true;
faceBookButton.setVisibility(View.GONE);
twitterButton.setVisibility(View.GONE);
} else {
isShareClicked = false;
faceBookButton.setVisibility(View.VISIBLE);
twitterButton.setVisibility(View.VISIBLE);
}
}
}
});
}
I am making a music player application in android. The application has
MainActivity.java (with corresponding XML File:activity_main): This Activity has a listview that displays the list of all songs available.
PlayerScreen.java (with corresponding XML File:activity_player_screen): When a song is clicked on the first activity, this activity is launched and it plays that particular song. This activity has 3 Buttons (Play/Pause, NextSong, PreviousSong) and a seekbar.
Now this is where I am facing the problem
I have created a separate class (SeekBarThread.java) for implementing seekbar of the activity_player_screen using Threading.
The Problem is that when I call the start method for my thread class from PlayerScreen.java, nothing happens. No exception is thrown. The song keeps on playing but the widgets of the activity_player_screen stop working i.e. I can't pause the song aur play the next song. The seekbar also doesn't work.
I think I am not able to link the activity_player_screen file with both PlayerScreen.java and SeekBarThread.java properly.
This is the call to the Thread class from PlayerScreen.java
mySeekBarThread = new SeekBarThread(this, mySeekBar, mediaPlayer);
myThread = new Thread(mySeekBarThread);
myThread.start();
I don't really have an idea to get rid of the anomaly so I passed the seekbar object and mediaplayer object reference and the current context reference to the SeekBarThread class. But it didn't work.
Here is the SeekBarThread.java class code:
public class SeekBarThread implements Runnable{
private PlayerScreen myPlayerScreen;
private SeekBar seekBar;
private MediaPlayer mp;
private Context context;
public SeekBarThread(Context context, SeekBar seekBar, MediaPlayer mp) {
this.context = context;
this.seekBar = seekBar;
this.mp = mp;
}
public void run() {
((Activity)context).setContentView(R.layout.activity_player_screen);
seekBar.setMax(mp.getDuration());
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mp.seekTo(seekBar.getProgress());
}
});
int totalduration = mp.getDuration();
int currentposition = 0;
while(currentposition < totalduration) {
try {
sleep(500);
currentposition = mp.getCurrentPosition();
seekBar.setProgress(currentposition);
}
catch(InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
activity_player_screen XML File:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_player_screen"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="#dimen/activity_vertical_margin"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
tools:context="prakhar.simplemusicplayer20.PlayerScreen">
<Button
android:id="#+id/play_pause"
android:layout_width="42dp"
android:layout_height="42dp"
android:layout_alignParentBottom="true"
android:layout_centerInParent="true"
android:background="#drawable/pause" />
<Button
android:id="#+id/next_song"
android:layout_height="42dp"
android:layout_width="42dp"
android:background="#drawable/next"
android:layout_marginEnd="25dp"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true" />
<Button
android:id="#+id/prev_song"
android:layout_height="42dp"
android:layout_width="42dp"
android:background="#drawable/previous"
android:layout_marginStart="25dp"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true" />
<Button
android:text="F"
android:layout_width="42dp"
android:layout_height="42dp"
android:id="#+id/forward_song"
android:layout_alignParentBottom="true"
android:layout_toStartOf="#+id/next_song"
android:layout_marginEnd="22dp" />
<Button
android:text="R"
android:layout_width="42dp"
android:layout_height="42dp"
android:id="#+id/rewind_song"
android:layout_marginEnd="23dp"
android:layout_alignParentBottom="true"
android:layout_toStartOf="#+id/play_pause" />
<SeekBar
android:id="#+id/seek_bar"
android:layout_height="wrap_content"
android:layout_width="match_parent"
android:layout_marginBottom="26dp"
android:layout_above="#+id/play_pause"
android:layout_alignParentStart="true" />
<TextView
android:text="TextView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="146dp"
android:id="#+id/details_text_view" />
</RelativeLayout>
Here is the PlayerScreen.java class:
public class PlayerScreen extends AppCompatActivity implements View.OnClickListener{
private Button playPause, nextSong, prevSong;
public SeekBar mySeekBar;
private int count = 0;
public MediaPlayer mediaPlayer;
private Bundle newBundle = new Bundle();
private Intent newIntent;
private int pos;
private ArrayList<String> name;
private ArrayList<String> path;
private SeekBarThread mySeekBarThread;
private Thread myThread;
private TextView detailsTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_player_screen);
playPause = (Button)findViewById(R.id.play_pause);
nextSong = (Button)findViewById(R.id.next_song);
prevSong = (Button)findViewById(R.id.prev_song);
mySeekBar = (SeekBar)findViewById(R.id.seek_bar);
detailsTextView = (TextView)findViewById(R.id.details_text_view);
playPause.setOnClickListener(this);
nextSong.setOnClickListener(this);
prevSong.setOnClickListener(this);
newIntent = this.getIntent();
newBundle = newIntent.getExtras();
name = newBundle.getStringArrayList("title");
path = newBundle.getStringArrayList("songpath");
pos = newBundle.getInt("post");
detailsTextView.setText(name.get(pos));
mediaPlayer = new MediaPlayer();
setMediaPlayer(pos);
}
public void setMediaPlayer(int position) {
mySeekBarThread = new SeekBarThread(this, mySeekBar, mediaPlayer);
myThread = new Thread(mySeekBarThread);
myThread.start();
File mySong = new File(path.get(pos));
mediaPlayer = new MediaPlayer();
FileInputStream is = null;
try {
is = new FileInputStream(mySong);
}
catch(FileNotFoundException ex) {
ex.printStackTrace();
}
try {
mediaPlayer.setDataSource(is.getFD());
}
catch(IOException ex) {
ex.printStackTrace();
}
try {
mediaPlayer.prepare();
}
catch(IOException ex) {
ex.printStackTrace();
}
finally {
if(is != null) {
try {
is.close();
}
catch(IOException ex) {
ex.printStackTrace();
}
}
}
mediaPlayer.start();
}
#Override
protected void onPause() {
super.onPause();
mediaPlayer.pause();
}
#Override
protected void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
}
#Override
public void onClick(View v) {
switch(v.getId()) {
case R.id.play_pause:
count++;
if(count%2 == 0) {
v.setBackgroundResource(R.drawable.pause);
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition());
mediaPlayer.start();
}
else {
v.setBackgroundResource(R.drawable.play);
mediaPlayer.pause();
}
break;
case R.id.next_song:
mediaPlayer.stop();
pos = pos + 1;
setMediaPlayer(pos);
break;
case R.id.prev_song:
mediaPlayer.stop();
pos = pos - 1;
setMediaPlayer(pos);
break;
}
}
}
Most of the onCreate() code for this is class is dealing with which song to play based on the user's choice from the previous activity. And since the song is being played, i don't think there is a problem in that part of the code.
#prakhar, Going through the code, I have found the following issues:
1) In SeekBarThread class in run() method setContentView() should not set,as it is already set in the activity class, as your are not reinitializing the click listeners.
2) Also the seekbarchangeListener should not be set in run() method and should be set in the main activity itself, as it doesn't need reinitalizing all the time.
3) The important point here is that your are initializing the SeekBarThread class before the initialization of MediaPlayer and hence there is no action even after seeking the seekbar.
A detailed code with the above modifications rectified.
public class PlayerScreen extends AppCompatActivity implements View.OnClickListener {
private Button playPause, nextSong, prevSong;
public SeekBar mySeekBar;
private int count = 0;
public MediaPlayer mediaPlayer;
private Bundle newBundle = new Bundle();
private Intent newIntent;
private int pos;
private ArrayList<String> name;
private ArrayList<String> path;
private SeekBarThread mySeekBarThread;
private Thread myThread;
private TextView detailsTextView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
playPause = (Button) findViewById(R.id.play_pause);
nextSong = (Button) findViewById(R.id.next_song);
prevSong = (Button) findViewById(R.id.prev_song);
mySeekBar = (SeekBar) findViewById(R.id.seek_bar);
detailsTextView = (TextView) findViewById(R.id.details_text_view);
playPause.setOnClickListener(this);
nextSong.setOnClickListener(this);
prevSong.setOnClickListener(this);
mySeekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
mediaPlayer.seekTo(seekBar.getProgress());
}
});
newIntent = this.getIntent();
newBundle = newIntent.getExtras();
name = newBundle.getStringArrayList("title");
pos = newBundle.getInt("post");
detailsTextView.setText(name.get(pos));
mediaPlayer = new MediaPlayer();
setMediaPlayer(pos);
}
public void setMediaPlayer(int position) {
File mySong = new File(path.get(pos));
mediaPlayer = new MediaPlayer();
FileInputStream is = null;
try {
is = new FileInputStream(mySong);
} catch (FileNotFoundException ex) {
ex.printStackTrace();
}
try {
mediaPlayer.setDataSource(is.getFD());
} catch (IOException ex) {
ex.printStackTrace();
}
try {
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.prepare();
} catch (IOException ex) {
ex.printStackTrace();
} finally {
try {
is.close();
} catch (IOException ex) {
ex.printStackTrace();
}
}
mediaPlayer.start();
mySeekBarThread = new SeekBarThread(this, mySeekBar, mediaPlayer);
myThread = new Thread(mySeekBarThread);
myThread.start();
}
#Override
protected void onPause() {
super.onPause();
mediaPlayer.pause();
}
#Override
protected void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.play_pause:
count++;
if (count % 2 == 0) {
v.setBackgroundResource(R.drawable.pause);
mediaPlayer.seekTo(mediaPlayer.getCurrentPosition());
mediaPlayer.start();
} else {
v.setBackgroundResource(R.drawable.play);
mediaPlayer.pause();
}
break;
case R.id.next_song:
mediaPlayer.stop();
pos = pos + 1;
setMediaPlayer(pos);
break;
case R.id.prev_song:
mediaPlayer.stop();
pos = pos - 1;
setMediaPlayer(pos);
break;
}
}
}
public class SeekBarThread implements Runnable{
private SeekBar seekBar;
private MediaPlayer mp;
private Context context;
public SeekBarThread(Context context, SeekBar seekBar, MediaPlayer mp) {
this.context = context;
this.seekBar = seekBar;
this.mp = mp;
}
public void run() {
seekBar.setMax(mp.getDuration());
int totalduration = mp.getDuration();
int currentposition = 0;
while(currentposition < totalduration) {
try {
sleep(500);
currentposition = mp.getCurrentPosition();
seekBar.setProgress(currentposition);
}
catch(InterruptedException ex) {
ex.printStackTrace();
}
}
}
}
I know similar questions have been asked before but none of them could solve my problem. I'm making a music player and wish to automate the Seekbarwhen a song is played. I'm using a RecyclerViewand the following snippet exists in the onBindViewHolder section.
public class ListViewPopulator extends
RecyclerView.Adapter<ListViewPopulator.ViewHolder>{
List<String> musicName;
List<String> musicAdd;
Context context;
MediaPlayer mediaPlayer;
Button media_play;
Button media_stop;
SeekBar seekBar;
final Handler mhandler=new Handler();
TextView timer;
public ListViewPopulator(Activity context, List<String> musicName, List<String> musicAdd)
{
this.context=context;
this.musicName=musicName;
this.musicAdd=musicAdd;
media_play= (Button)context.findViewById(R.id.play);
media_stop=(Button)context.findViewById(R.id.pause);
seekBar= (SeekBar) context.findViewById(R.id.seekbar);
timer=(TextView) context.findViewById(R.id.timer);
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.listview,parent,false);
return new ViewHolder(v);
}
void something(String s)
{
try{mediaPlayer.stop();}catch (NullPointerException e){e.printStackTrace();}
//To fetch the location of audio files on disk
mediaPlayer=MediaPlayer.create(context, Uri.fromFile(new File(s)));
mediaPlayer.start();
//seekBar.setProgress(0);
//seekBar.setMax(mediaPlayer.getDuration());
} int temp=0;
int i=0;
#Override
public void onBindViewHolder(ViewHolder holder, final int position) {
final String s = musicAdd.get(position);
final String v = musicName.get(position);
holder.data.setText(v);
seeker();
cont_seek();
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
temp = position + 1;
something(s);
seekBar.setProgress(0);
seekBar.setMax(mediaPlayer.getDuration());
// mediaPlayer.reset();
change();
op();
}
});
media_play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mediaPlayer.start();
Log.d("click", "Kuch bhi");
} catch (NullPointerException e) {
e.printStackTrace();
}
}
});
media_stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
try {
mediaPlayer.pause();
Log.d("click2", "Kuch bhi2");
} catch (NullPointerException e) {
e.printStackTrace();
}
}
});
}
void cont_seek(){
Log.d("auto","seek");
Runnable runnable=new Runnable() {
#Override
public void run() {
String time;
if((mediaPlayer != null) && mediaPlayer.isPlaying()){
int progress = mediaPlayer.getCurrentPosition();
int min = (progress / 1000) / 60;
Log.d("auto","seek");
int sec = (progress / 1000) % 60;
if (sec < 10)
time = "0" + sec;
else
time = "" + sec;
String elapsedTime = min + ":" + time + "";
timer.setText(elapsedTime);
seekBar.setMax(mediaPlayer.getDuration());
seekBar.setProgress(progress);
mhandler.postDelayed(this, 1000);
}
}
};
mhandler.postDelayed(runnable,1000);
}
void seeker(){
seekBar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
int seek_progress;
String time_sec;
#Override
public void onProgressChanged(final SeekBar seekBar, int progress, boolean fromUser) {
seek_progress=progress;
//seek_progress=seek_progress*1000;
new Runnable() {
#Override
public void run() {
int min=(seek_progress/1000)/60;
int sec=(seek_progress/1000)%60;
if(sec<10)
time_sec="0"+sec;
else
time_sec=""+sec;
String elapsedTime=min+":"+time_sec+"";
timer.setText(elapsedTime);
//mediaPlayer.seekTo(seek_progress);
new Handler().postDelayed(this,1000);
}
}.run();
if(fromUser) {
Log.d("blah","blah");
new Runnable() {
#Override
public void run() {
int min=(seek_progress/1000)/60;
int sec=(seek_progress/1000)%60;
if(sec<10)
time_sec="0"+sec;
else
time_sec=""+sec;
String elapsedTime=min+":"+time_sec+"";
timer.setText(elapsedTime);
//mediaPlayer.seekTo(seek_progress);
new Handler().postDelayed(this,1000);
}
}.run();
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
if(mediaPlayer!=null){mediaPlayer.seekTo(seek_progress);}
}
});
}
int h=0;
void change(){
try{mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if(temp!=musicAdd.size())
something(musicAdd.get(temp));
temp=temp+1;
seekBar.setProgress(0);
seekBar.setMax(mediaPlayer.getDuration());
change();
}
});
}catch(Throwable throwable){throwable.printStackTrace();}}
void op()
{
Sensey.getInstance().startFlipDetection(new FlipDetector.FlipListener() {
#Override
public void onFaceUp() {
if (i == 0) {
try {
mediaPlayer.start();
i = 1;
h=1;
}catch (NullPointerException e){e.printStackTrace();}
}
}
#Override
public void onFaceDown() {
if (i == 1) {
try {
mediaPlayer.pause();
i = 0;
h=0;
}catch (NullPointerException e){e.printStackTrace();}
}
}
});
Sensey.getInstance().startShakeDetection(15, new ShakeDetector.ShakeListener() {
#Override
public void onShakeDetected() {
try {
if(h==1)
something(musicAdd.get(randomG(musicAdd.size()-1,0)));
}catch (Throwable throwable)
{
throwable.printStackTrace();
}
}
});
}
int randomG(int max,int min)
{
Random random=new Random();
return random.nextInt((max-min)+1);
}
#Override
public int getItemCount() {
return musicName.size();
}
public class ViewHolder extends RecyclerView.ViewHolder
{
TextView data;
public ViewHolder(View itemView) {
super(itemView);
data=(TextView)itemView.findViewById(R.id.data);
}
}
}
I am pretty sure the logic is right and have checked the Log, the code doesn't seem to be executing. Can somebody explain why?
In your recycler view adapter you can use something like this:
#Override
public VoiceViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
return VoiceViewHolder.createVoiceViewHolder(LayoutInflater.from(parent.getContext()).inflate(R.layout.lecture_voice_item_recycler, parent, false));
}
#Override
public void onBindViewHolder(VoiceViewHolder holder, int position) {
holder.bindHolderToVoice(10000, "your path");
}
public static class VoiceViewHolder extends RecyclerView.ViewHolder {
CardView cardView;
TextView voiceDuration;
ImageView voiceView;
ImageButton mPlayButton;
MediaPlayer mPlayer;
RelativeLayout layoutVoice;
RelativeLayout layoutVoiceNotFound;
boolean isPlaying;
TextView voiceDurationPlayer;
double timeElapsed = 0, finalTime = 0;
Handler durationHandler = new Handler();
Runnable updateSeekBarTime;
SeekBar seekBarDuration;
private VoiceViewHolder(final View itemView) {
super(itemView);
}
public static VoiceViewHolder createVoiceViewHolder(View convertView) {
VoiceViewHolder holder = new VoiceViewHolder(convertView);
holder.voiceDuration = (TextView) convertView.findViewById(R.id.voice_duration);
holder.cardView = (CardView) convertView.findViewById(R.id.card_view);
holder.voiceView = (ImageView) convertView.findViewById(R.id.voiceView);
holder.mPlayButton = (ImageButton) convertView.findViewById(R.id.playButton);
holder.layoutVoice = (RelativeLayout) convertView.findViewById(R.id.layoutVoice);
holder.layoutVoiceNotFound = (RelativeLayout) convertView.findViewById(R.id.layoutVoiceNotFound);
holder.voiceDurationPlayer = (TextView) convertView.findViewById(R.id.voiceDurationPlayer);
holder.seekBarDuration = (SeekBar) convertView.findViewById(R.id.seekBarDuration);
holder.isPlaying = false;
holder.mPlayer = new MediaPlayer();
return holder;
}
public void bindHolderToVoice(final long duration, final String path) {
final Context context = itemView.getContext();
if (duration >= 60000) {
voiceDuration.setText(String.format("%d %s, %d %s", TimeUnit.MILLISECONDS.toMinutes(duration), context.getString(R.string.min),
TimeUnit.MILLISECONDS.toSeconds(duration) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration)),
context.getString(R.string.sec)));
} else {
voiceDuration.setText(String.format("%d %s",
TimeUnit.MILLISECONDS.toSeconds(duration) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes(duration)),
context.getString(R.string.sec)));
}
finalTime = duration;
seekBarDuration.setMax((int) finalTime);
seekBarDuration.setClickable(false);
seekBarDuration.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (mPlayer.isPlaying()) {
SeekBar sb = (SeekBar) v;
mPlayer.seekTo(sb.getProgress());
}
return false;
}
});
updateSeekBarTime = new Runnable() {
public void run() {
if (mPlayer != null) {
if (mPlayer.isPlaying()) {
timeElapsed = mPlayer.getCurrentPosition();
seekBarDuration.setProgress((int) timeElapsed);
voiceDurationPlayer.setText(String.format("%02d:%02d", TimeUnit.MILLISECONDS.toMinutes((long) timeElapsed), TimeUnit.MILLISECONDS.toSeconds((long) timeElapsed) - TimeUnit.MINUTES.toSeconds(TimeUnit.MILLISECONDS.toMinutes((long) timeElapsed))));
durationHandler.postDelayed(this, 100);
} else {
mPlayer.pause();
isPlaying = false;
}
}
}
};
File voiceFile = new File(path);
mPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
isPlaying = false;
}
});
mPlayButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (!isPlaying) {
isPlaying = true;
try {
mPlayer = new MediaPlayer();
mPlayer.setDataSource(path);
mPlayer.prepare();
} catch (IOException e) {
Log.e("tag", "Start playing prepare() failed");
isPlaying = false;
}
mPlayer.start();
timeElapsed = mPlayer.getCurrentPosition();
seekBarDuration.setProgress((int) timeElapsed);
durationHandler.postDelayed(updateSeekBarTime, 100);
} else {
isPlaying = false;
mPlayer.pause();
}
}
});
}
}
The layout lecture_voice_item_recycler.xml is something like this:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/lecture_voice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/lecture_voice__margin_card">
<android.support.v7.widget.CardView
android:id="#+id/card_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="#dimen/lecture_voice__margin_card"
android:clickable="true"
android:foreground="?android:attr/selectableItemBackground">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/lecture_voice__margin_card"
android:layout_marginBottom="#dimen/lecture_voice__margin_card">
<LinearLayout
android:id="#+id/layoutVoiceInfo"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/grid_annotation_margin"
android:orientation="horizontal">
<TextView
android:id="#+id/voice_duration"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center_vertical"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginRight="#dimen/activity_horizontal_margin"
android:textAppearance="?android:attr/textAppearanceMedium" />
</LinearLayout>
<RelativeLayout
android:id="#+id/layoutVoice"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/layoutVoiceInfo"
android:gravity="center_vertical"
android:layout_marginLeft="#dimen/activity_horizontal_margin">
<ImageButton
android:id="#+id/playButton"
android:layout_width="#dimen/lecture_voice_icon"
android:layout_height="#dimen/lecture_voice_icon"
android:background="#android:color/transparent"
android:scaleType="fitXY"
android:src="#drawable/ic_play" />
<LinearLayout
android:id="#+id/layoutVoiceSeekbar"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:layout_toRightOf="#+id/playButton"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginTop="#dimen/activity_horizontal_margin">
<SeekBar
android:id="#+id/seekBarDuration"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:layout_marginRight="#dimen/activity_horizontal_margin" />
<TextView
android:id="#+id/voiceDurationPlayer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="00:00"
android:layout_gravity="right"
android:layout_marginRight="#dimen/lecture_voice_text_duration_margin_right"/>
</LinearLayout>
</RelativeLayout>
<RelativeLayout
android:id="#+id/layoutVoiceNotFound"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_below="#+id/layoutVoiceInfo"
android:layout_marginLeft="#dimen/activity_horizontal_margin"
android:visibility="gone">
<ImageView
android:id="#+id/voiceView"
android:layout_width="#dimen/lecture_voice_icon"
android:layout_height="#dimen/lecture_voice_icon"
android:src="#drawable/voice_not_found"
android:scaleType="fitXY" />
<TextView
android:id="#+id/voiceNotFound"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toRightOf="#+id/voiceView"
android:layout_centerInParent="true"
android:text="#string/voice_not_found"
android:textAppearance="?android:attr/textAppearanceMedium" />
</RelativeLayout>
</RelativeLayout>
</android.support.v7.widget.CardView>
</RelativeLayout>
strings.xml
<string name="min">min</string>
<string name="sec">sec</string>
Note: some dimensions or drawables could be lost in the example. You should use your own dimension if no compile.
You need to use your Handler & Runnable as follows:
final Handler handler = new Handler();
final Runnable r = new Runnable() {
public void run() {
//YOUR CODE GOES HERE
handler.postDelayed(this, 1000);
}
};
handler.postDelayed(r, 0);
Found a solution for this.
Runnable runnable=new Runnable() {
#Override
public void run() {
String time;
Log.d(TAG, "run");
while(mediaPlayer != null && mediaPlayer.isPlaying()){
final int progress = mediaPlayer.getCurrentPosition();
int min = (progress / 1000) / 60;
Log.d("auto","seek");
int sec = (progress / 1000) % 60;
if (sec < 10)
time = "0" + sec;
else
time = "" + sec;
final String elapsedTime = min + ":" + time + "";
context.runOnUiThread(new Runnable() {
#Override
public void run() {
timer.setText(elapsedTime);
seekBar.setMax(mediaPlayer.getDuration());
seekBar.setProgress(progress);
}
});
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
};
new Thread(runnable).start();
The main problem here is that once mediaplayer.start() is called the media file begins loading in the player before that completes the cont_seek function is called which has the condition
if(mediaplayer!=null && mediaplayer.isplaying())
Since the media hasn't started playing yet, the condition fails and the function is never executed.
Fixed it by running the runnable in a different thread.
Is it possible to add text from java coding of a list view to marquee scroll in Android. If yes can you please let me know how?
If needed I shall post the code used.
This was the XML for listview used is as follows
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical" >
<LinearLayout
android:id="#+id/linearLayout1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
</LinearLayout>
<ListView
android:id="#+id/audiolist_listView"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_gravity="bottom"
android:layout_weight="1"
android:background="#drawable/backgroundimg"
android:divider="#drawable/gradient"
android:dividerHeight="1dp"
android:scrollbars="vertical" >
</ListView>
</LinearLayout>
The java class for listview is as follows
public class Audiovediolist extends Activity implements OnItemClickListener {
private ListView audioList;
private Intent frmHome;
private ArrayList<HashMap<String, String>> dataList;
private HashMap<String, String> map;
private HashMap<String, String> data;
private int Screen_Id;
private AdView adView;
String name;
String mSign[] = { "Aries-Mesam", "Taurus-Vrushabham", "Gemini-Midhunam",
"Cancer-Karkatakam", "Leo-Simham", "Virgo-Kanya", "Libra-Tula",
"Scorpio-Vruchikam", "Sagittarius-Dhanussu", "Capricorn-Makaram",
"Aquarius-Kumbham", "Pisces-Meenam" };
Integer mImages[] = { R.drawable.meshamu, R.drawable.vrushabhamu,
R.drawable.medhunam, R.drawable.karkatakam, R.drawable.simham,
R.drawable.kanya, R.drawable.tula, R.drawable.vruchikam,
R.drawable.dhanussu, R.drawable.makaramu, R.drawable.kumbhamu,
R.drawable.meenamu };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_RIGHT_ICON);
setContentView(R.layout.list);
frmHome = getIntent();
getIntentValues();
initUI();
setUI();
uiListener();
}
private void initUI() {
audioList = (ListView) findViewById(R.id.audiolist_listView);
dataList = new ArrayList<HashMap<String, String>>();
adView = new AdView(this, AdSize.SMART_BANNER, "a150b89c23af3b2");
LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout1);
layout.setGravity(Gravity.TOP);
layout.addView(adView);
adView.loadAd(new AdRequest());
}
private void uiListener() {
audioList.setOnItemClickListener(this);
}
private void getIntentValues() {
String id = frmHome.getStringExtra("Activity_Id");
Screen_Id = Integer.parseInt(id);
if (Screen_Id == 1) {
getWindow().setFeatureDrawableResource(Window.FEATURE_RIGHT_ICON,
R.drawable.audioo);
this.setTitle(getResources().getString(R.string.audio));
this.setTitleColor(getResources().getColor(R.color.Beige));
} else {
this.setTitle(getResources().getString(R.string.video));
this.setTitleColor(getResources().getColor(R.color.Beige));
getWindow().setFeatureDrawableResource(Window.FEATURE_RIGHT_ICON,
R.drawable.videoo);
}
}
private void setAdapter() {
SimpleAdapter adapter = new SimpleAdapter(this, dataList,
R.layout.list_row, new String[] { "Image", "text" }, new int[] {
R.id.audiolist_row_img, R.id.audiolist_row_tv });
audioList.setAdapter(adapter);
}
private void setUI() {
for (int a = 0; a <= 11; a++) {
map = new HashMap<String, String>();
map.put("Image", "" + mImages[a]);
map.put("text", mSign[a]);
dataList.add(map);
map = null;
}
}
#Override
protected void onStart() {
super.onStart();
setAdapter();
}
#Override
public void onBackPressed() {
super.onBackPressed();
System.gc();
}
#Override
protected void onDestroy() {
super.onDestroy();
adView.destroy();
}
/*
* private class NextTask extends AsyncTask<Void,Void,Void> { ProgressDialog
* progressDailog = new ProgressDialog(Audiovediolist.this);
*
* #Override protected void onPreExecute() { super.onPreExecute();
* progressDailog.setTitle("Please Wait");
* progressDailog.setMessage("URL Data Loading ...");
* progressDailog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
* progressDailog.setCancelable(true); progressDailog.show(); }
*
* #SuppressWarnings("static-access")
*
* #Override protected Void doInBackground(Void... params) { return null; }
*
* #Override protected void onPostExecute(Void result) {
* progressDailog.dismiss(); } }
*/
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
data = dataList.get(position);
//FinalConstants.AUDIO_VIDEO = "list";
try {
NetWorkCheck netWork = new NetWorkCheck();
if (netWork.isNetWorkConnection(this)) {
if (Screen_Id == 1) {
// new NextTask().execute();
Intent audioInt=new Intent(getApplicationContext(),AudioView.class);
audioInt.setType(data.get("text"));
startActivity(audioInt);
} else if (Screen_Id == 2) {
Intent vedioInt = new Intent(this, VideoPlayActivity.class);
vedioInt.setType(data.get("text"));
startActivity(vedioInt);
}
} else {
netWork.alert();
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, "Problem while ListItemClick",
Toast.LENGTH_SHORT).show();
}
}
}
The code for audio player where i need the text selected to scroll is as follows
public class AudioView extends Activity implements OnClickListener {
private MediaPlayer mMediaPlayer;
private ImageView mPlay;
private ImageView mPause;
private ImageView mBack;
private ImageView mFar;
private ProgressBar myProgressBar;
private boolean boolFlag = false;
private boolean isPausedInCall = false;
private String url;
private TelephonyManager mTelephoneMgr;
private NotificationManager mNotificationManager;
private int SIMPLE_NOTFICATION_ID;
private TextView tv;
// private boolean serviceRunning;
Notification notifyDetails;
private AdView adView;
#SuppressWarnings("deprecation")
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(R.layout.marquee);
Toast.makeText(this,"please wait.........",Toast.LENGTH_LONG).show();
url=getIntent().getType();
initUI();
uiListener();
mNotificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
notifyDetails = new Notification(R.drawable.mulug_icon, url,
System.currentTimeMillis());
mTelephoneMgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if (mTelephoneMgr != null) {
mTelephoneMgr.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
}
/*if(FinalConstants.AUDIO_VIDEO=="listitem"){
LoginProgress task = new LoginProgress();
task.applicationContext = AudioView.this;
task.execute();
}*/
}
private void initUI() {
tv = (TextView) findViewById(R.id.text);
mBack = (ImageView) findViewById(R.id.back);
mPlay = (ImageView) findViewById(R.id.play);
mPause = (ImageView) findViewById(R.id.pause);
mFar = (ImageView) findViewById(R.id.fwd);
myProgressBar = (ProgressBar) findViewById(R.id.progressbar_Horizontal);
myProgressBar.setProgressDrawable(getResources().getDrawable(
R.drawable.green_progress));
myProgressBar.setProgress(0);
adView = new AdView(this, AdSize.BANNER, "a150b89c23af3b2");
LinearLayout layout = (LinearLayout) findViewById(R.id.linearLayout1);
layout.setGravity(Gravity.TOP);
layout.addView(adView);
adView.loadAd(new AdRequest());
tv.setText(url + "more Deails Click on www.mulugu.com");
tv.setSelected(true);
}
private void uiListener() {
mPlay.setOnClickListener(this);
mPlay.setOnClickListener(this);
mPause.setOnClickListener(this);
mPause.setVisibility(android.view.View.INVISIBLE);
mBack.setOnClickListener(this);
mFar.setOnClickListener(this);
}
private Thread myThread = new Thread() {
public void run() {
while (mMediaPlayer.getCurrentPosition() < mMediaPlayer
.getDuration()) {
try {
myProgressBar
.setProgress(mMediaPlayer.getCurrentPosition());
} catch (Throwable t) {
}
}
}
};
#Override
protected void onStart() {
super.onStart();
this.setProgressBarIndeterminateVisibility(true);
try {
if (boolFlag == false) {
System.out.println(FinalConstants.URL + "mobile-audio/" + url+ ".mp3");
mMediaPlayer = MediaPlayer.create(
this,
Uri.parse(FinalConstants.URL + "mobile-audio/" + url
+ ".mp3"));
}
myProgressBar.setMax(mMediaPlayer.getDuration());
} catch (Exception e) {
Toast.makeText(getApplicationContext(), "Data not available",
Toast.LENGTH_SHORT).show();
Log.e("ERRORS", "Data Not Exist in that Url...");
super.onBackPressed();
e.printStackTrace();
}
}
#SuppressLint("NewApi")
#Override
public void onBackPressed() {
super.onBackPressed();
mMediaPlayer.stop();
// myThread.stop();
mNotificationManager.cancel(SIMPLE_NOTFICATION_ID);
System.gc();
}
#Override
protected void onDestroy() {
adView.destroy();
super.onDestroy();
System.gc();
}
public PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
System.out.println("ringing state");
if (mMediaPlayer != null) {
pauseMedia();
isPausedInCall = true;
}
notificationShow();
}
if (state == TelephonyManager.CALL_STATE_IDLE) {
System.out.println("callState Idle");
if (mMediaPlayer != null) {
if (isPausedInCall) {
isPausedInCall = false;
playMedia();
}
}
}
if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
}
super.onCallStateChanged(state, incomingNumber);
}
};
private void pauseMedia() {
mMediaPlayer.pause();
changePlayerIcons(false);
}
private void playMedia() {
mMediaPlayer.start();
changePlayerIcons(true);
}
public void onClick(View v) {
switch (v.getId()) {
case R.id.play:
if (!boolFlag) {
try {
notificationShow();
mMediaPlayer.setLooping(false);
mMediaPlayer.prepareAsync();
} catch (Exception e) {
Toast.makeText(this, "preparing", Toast.LENGTH_SHORT)
.show();
}
boolFlag = true;
mMediaPlayer.start();
myThread.start();
} else {
notificationShow();
mMediaPlayer.getCurrentPosition();
mMediaPlayer.start();
}
changePlayerIcons(true);
myProgressBar.setProgress(mMediaPlayer.getCurrentPosition());
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer arg0) {
changePlayerIcons(false);
myProgressBar.setProgress(0);
onStart();
}
});
mMediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
}
});
break;
case R.id.pause:
mMediaPlayer.pause();
mPlay.setVisibility(android.view.View.VISIBLE);
mPause.setVisibility(android.view.View.INVISIBLE);
break;
case R.id.back:
int dur = mMediaPlayer.getCurrentPosition();
int pos = (dur > 10000 ? dur - 5000 : 0);
mMediaPlayer.seekTo(pos);
break;
case R.id.fwd:
int curpos = mMediaPlayer.getCurrentPosition();
int dur2 = mMediaPlayer.getDuration();
int pos2 = (curpos + 5000 > dur2 ? dur2 : curpos + 5000);
mMediaPlayer.seekTo(pos2);
break;
}
}
#SuppressWarnings("deprecation")
private void notificationShow() {
Context context = getApplicationContext();
CharSequence contentTitle = "Mulugu Running";
CharSequence contentText = url + " Weekly Predictions";
Intent notifyIntent = new Intent(AudioView.this, AudioView.class);
PendingIntent intent = PendingIntent.getActivity(AudioView.this, 0,
notifyIntent, android.content.Intent.FLAG_ACTIVITY_CLEAR_TOP);
notifyDetails.setLatestEventInfo(context, contentTitle, contentText,
intent);
mNotificationManager.notify(SIMPLE_NOTFICATION_ID, notifyDetails);
}
private void changePlayerIcons(boolean b) {
if (b) {
mPlay.setVisibility(android.view.View.INVISIBLE);
mPause.setVisibility(android.view.View.VISIBLE);
} else {
mPlay.setVisibility(android.view.View.VISIBLE);
mPause.setVisibility(android.view.View.INVISIBLE);
}
}
/*public class LoginProgress extends AsyncTask<Void, Void, Void> {
private ProgressDialog dialog;
protected Context applicationContext;
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
this.dialog.dismiss();
}
#Override
protected void onPreExecute() {
this.dialog = ProgressDialog.show(applicationContext, "Data Loading",
"Loading .....", true);
}
#Override
protected Void doInBackground(Void... params) {
LoadUrl();
return null;
}
private void LoadUrl() {
mMediaPlayer = new MediaPlayer();
mMediaPlayer.reset();
try {
mMediaPlayer.setDataSource(AudioView.this,Uri.parse(FinalConstants.URL + "mobile-audio/" + getIntent().getType()+ ".mp3"));
mMediaPlayer.setLooping(false); // Set looping
mMediaPlayer.prepare();
myProgressBar.setMax(mMediaPlayer.getDuration());
} catch (Exception e) {
e.printStackTrace();
}
}
}*/
}
If you need to move text around, maybe this will help:
http://developer.android.com/guide/topics/resources/animation-resource.html#translate-element
If you have a TextView with a text that is too big and you want it to move around so people can read the whole thing, try android:ellipsize="marquee" in the .xml file, or in the Java code:
textView.setEllipsize(TextUtils.TruncateAt.MARQUEE);
If the android libraries not enough, you can always use the java via coding. Create a thread class that gets the views and change conditions over time. You can create an intent to call that class.
You can use the TextSwitcher and apply the animation on it.
Try below code:
public class TextSwitcherActivity extends Activity implements ViewSwitcher.ViewFactory,
View.OnClickListener
{
private TextSwitcher m_switcher;
private Button m_nextButton;
private int m_counter = 0;
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
m_switcher = (TextSwitcher) findViewById(R.id.tsSwitcher);
m_switcher.setFactory(this);
Animation in = AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
Animation out = AnimationUtils.loadAnimation(this, android.R.anim.fade_out);
m_switcher.setInAnimation(in);
m_switcher.setOutAnimation(out);
m_nextButton = (Button) findViewById(R.id.next);
m_nextButton.setOnClickListener(this);
updateCounter();
}
/**
* Update counter value
*/
public void onClick(View v)
{
m_counter++;
updateCounter();
}
/**
* Set text on textswitcher
*/
private void updateCounter()
{
m_switcher.setText(String.valueOf(m_counter));
}
public View makeView()
{
TextView t = new TextView(this);
t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL);
t.setTextSize(36);
return t;
}
You can define your own animations to get the marquee effect.
Here is the example
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="#+id/mywidget"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:lines="1"
android:ellipsize="marquee"
android:fadingEdge="horizontal"
android:marqueeRepeatLimit="marquee_forever"
android:scrollHorizontally="true"
android:textColor="#ff4500"
android:text="Simple application that shows how to use marquee, with a long text" />
In java (If you are using a Listview and binding an adapter, then in getview when u inflate Layout and its view component, set the selected flag to true to your TextView.)
tv = (TextView) this.findViewById(R.id.tv);
tv.setSelected(true);
By using below method you can convert your list of string values into a single string,
String listString = String.join(", ", list);
This will convert list values into string and with that you can achieve this. I know this is very late but I posted because there is no solution provided that's why.
I am using media player to stream a video. It only plays the audio but not the video. Could anyone help? My code is below.
public class VideoViewApplication extends Application {
#Override
public void onCreate() {
}
#Override
public void onTerminate() {
}
}
public class VideoViewDemo extends Activity implements
OnErrorListener,OnBufferingUpdateListener, OnCompletionListener,
MediaPlayer.OnPreparedListener, SurfaceHolder.Callback {
private static final String TAG = "VideoViewDemo";
private MediaPlayer mp;
private EditText mPath;
private SurfaceHolder holder;
private ImageButton mPlay;
private ImageButton mPause;
private ImageButton mReset;
private ImageButton mStop;
private String current;
private SurfaceView mPreview;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
mPreview = (SurfaceView) findViewById(R.id.surface);
mPath = (EditText) findViewById(R.id.path);
mPath.setText("rtsp://video2.americafree.tv/AFTVHorrorH26496.sdp");
mPlay = (ImageButton) findViewById(R.id.play);
mPause = (ImageButton) findViewById(R.id.pause);
mReset = (ImageButton) findViewById(R.id.reset);
mStop = (ImageButton) findViewById(R.id.stop);
mPlay.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
playVideo();
}
});
mPause.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (mp != null) {
mp.pause();
}
}
});
mReset.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (mp != null) {
mp.seekTo(0);
}
}
});
mStop.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (mp != null) {
current = null;
mp.stop();
mp.release();
}
}
});
// getWindow().setFormat(PixelFormat.TRANSPARENT);
holder = mPreview.getHolder();
holder.addCallback(this);
holder.setFixedSize(100, 100);
runOnUiThread(new Runnable(){
public void run(){
playVideo();
}
});
}
private void playVideo() {
try {
final String path = mPath.getText().toString();
Log.v(TAG, "path: " + path);
if (path.equals(current) && mp != null) {
mp.start();
return;
}
current = path;
mp = new MediaPlayer();
mp.setOnErrorListener(this);
mp.setOnBufferingUpdateListener(this);
mp.setOnCompletionListener(this);
mp.setOnPreparedListener(this);
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setScreenOnWhilePlaying(true);
mp.setDisplay(mPreview.getHolder());
mp.setDataSource(path);
mp.prepare();
Log.v(TAG, "Duration: ===>" + mp.getDuration());
mp.start();
} catch (Exception e) {
Log.e(TAG, "error: "+ e.getMessage(), e);
if (mp != null) {
mp.stop();
mp.release();
}
}
}
public void surfaceChanged(SurfaceHolder arg0, int arg1, int arg2, int arg3) {
Log.d(TAG, "surfaceChanged called");
}
public void surfaceCreated(SurfaceHolder arg0) {
Log.d(TAG, "surfaceCreated called");
}
public void surfaceDestroyed(SurfaceHolder arg0) {
Log.d(TAG, "surfaceDestroyed called");
}
public void onPrepared(MediaPlayer arg0) {
Log.d(TAG, "onPrepared called");
}
public void onCompletion(MediaPlayer arg0) {
Log.d(TAG, "onCompletion called");
}
public void onBufferingUpdate(MediaPlayer mediaPlayer, int percent) {
Log.d(TAG, "onBufferingUpdate called ---> percent:" + percent);
}
public boolean onError(MediaPlayer mediaPlayer, int what, int extra) {
Log.e(TAG, "onError---> what:"+what+" extra:"+extra);
if (mediaPlayer != null) {
mediaPlayer.stop();
mediaPlayer.release();
}
return true;
}
}
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<EditText android:id="#+id/path"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
/>
<SurfaceView
android:id="#+id/surface"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</SurfaceView>
<LinearLayout
android:orientation="horizontal"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
>
<ImageButton android:id="#+id/play"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="#drawable/play"/>
<ImageButton android:id="#+id/pause"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="#drawable/pause"/>
<ImageButton android:id="#+id/reset"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="#drawable/reset"/>
<ImageButton android:id="#+id/stop"
android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:src="#drawable/stop"/>
</LinearLayout>
</LinearLayout>
I had this problem and solved it by setting the type using this depreciated method.
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
Worth a try, and if it works you could investigate why the type isn't automatically set as it is supposed to be.
I had the same problem and it was due to the surface not being ready to play back video.
You should try and call playVideo() from the surfaceCreated() handler.
public void surfaceCreated(SurfaceHolder holder) {
runOnUiThread(new Runnable(){
public void run(){
playVideo();
}
});
}
I had this problem and solved it by adding in my release function visible=gone to surfaceview:
public void release() {
if (mMediaPlayer != null) {
setVisibility(View.GONE);
mMediaPlayer.reset();
mMediaPlayer.release();
mMediaPlayer = null;
mCurrentState = STATE_IDLE;}
}
and set visible=visible in onprepared function:
videoView.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
audio=false; video=false; int ty=mp.getTrackInfo().length;
for (int i=0; i<ty;i++)
{
if (mp.getAudioTrack()>-1) {audio=true;}
if (mp.getVideoTrack()>-1) {video=true;}
}
if (((audio==false)&&(skip==true))||((video==false)&&(skip2==true))||((video==true)&&(skip4==true)))
{ notifybar("...");
nexttr();} else {
if (vis==true) {
if (video==false) {
if (mVisualizerView.getVisibility()!=View.VISIBLE) {mVisualizerView.setVisibility(View.VISIBLE);}
mVisualizerView.link(videoView.getAudioSessionId());
vis2=true;
} else if (vis2==true){
mVisualizerView.release();
mVisualizerView.setVisibility(View.GONE);
vis2=false;
}}
//this
if (video==true) {
if (videoView.getVisibility()!=View.VISIBLE) {videoView.setVisibility(View.VISIBLE);}
} else {if (videoView.getVisibility()!=View.INVISIBLE) {videoView.setVisibility(View.INVISIBLE);}
}