Media Controllers are not visible on the top of the surface view - android

Media Controllers are not visible on the top of the surface view .I have tried almost all the options
Surface View should disappear every time an channel is clicked from the list.
Then the Flip animation for the background Images takes place.
Then the Surface should be visible.
The above three steps happen for every click.
Every time i have tried doing the below give things. Surface View would disappear the first time But appear while the flip animation is happening and the n Never disppears
Set Visibility(inivisible ,gone )- nothing works
Changing the size of the surface view
BringToFront paired with invalidate()
Finally i tried
mSurface .setZOrderOnTop(true);
mHolder.setPixelFormat(Transparent)
That Worked But now the Problem is My Media Controllers that were attached to FrameLayout are not getting displayedand the Reason is ofcourse
mSurface.setZOrderOnTop(true);
Can Any body please please please to power of infinity tell me what should i do to get the media controllers to show up or get the whole Scenario worked out .
I am quite new to media player and surface views.
Please Help
MainActivity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initImageLoader(getApplicationContext());
setContentView(R.layout.user_main_screen);
ActionBar actionBar = getActionBar();
actionBar.show();
// // get action bar
// ActionBar actionBar = getActionBar();
//
// // Enabling Up / Back navigation
// actionBar.setDisplayHomeAsUpEnabled(true);
SetUpVariables();
getDataFromSignIn();
Categories categoriesList = new Categories(UserMainScreen.this);
try {
resultFromCategoriesAsyncTask= categoriesList.execute(AccessToken).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Language LanguagesList = new Language(UserMainScreen.this);
try {
resultFromLanguagesAsyncTask= LanguagesList.execute(AccessToken).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MainScreen mainScreen = new MainScreen(UserMainScreen.this);
try {
resultFromAsyncTask= mainScreen.execute(AccessToken).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
getChannelInfo(resultFromAsyncTask);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* changed the Thread variable policy variable -lalita */
StrictMode.ThreadPolicy policy1 = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy1);
ParentLayout = (RelativeLayout)findViewById(R.id.relativeLayout);
PreviewFrameImage = (ImageView)findViewById(R.id.previewScreenImageView);
PreviewFrameImage.setOnTouchListener(this);
Bitmap PreviewImage = BitmapFactory.decodeResource(getResources(), R.drawable.tvscreen_white);
PreviewFrameImage.setImageBitmap(Bitmap.createScaledBitmap( PreviewImage, 350 , 180 , true));
PreviewFrame = (FrameLayout)findViewById(R.id.videoSurfaceContainer);
mSurface = (SurfaceView) findViewById(R.id.surface_main);
mSurface .setZOrderOnTop(true);
// mSurface.setVisibility(View.GONE);
//PreviewFrame.removeView(mSurface);
mHolder = mSurface.getHolder();
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mHolder.setFormat(PixelFormat.TRANSPARENT);
controller = new VideoControllerView(this);
// youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
// youTubeView.setVisibility(View.INVISIBLE);
InitImgList();
Integer[] images = (Integer[])imgList.toArray(new Integer[imgList.size()]);
for( int i = 0; i <ChannelThumbnails.size() ; i++)
{
Log.e(TAG,"ResponseData----- lalita test ---- channel Image Path "+ChannelThumbnails.get(i));
}
com.ib.coverflow.FlowImageAdapter coverImageAdapter = new com.ib.coverflow.FlowImageAdapter(this,ChannelThumbnails.toArray( new String[ChannelThumbnails.size()]),180, 150);
//coverImageAdapter.createReflectedImages();
CoverFlow coverFlow = (CoverFlow) findViewById(R.id.coverflow);
coverFlow.setAdapter(coverImageAdapter);
//coverFlow.setSpacing(-20);
coverFlow.setSelection(30);
setupListeners(coverFlow);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.user_main_screen_main_actions, menu);
return super.onCreateOptionsMenu(menu);
}
/**
* On selecting action bar icons
* */
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_refresh:
// refresh
return true;
case R.id.action_user:
// help action
return true;
case R.id.action_menu:
// check for updates action
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void InitImgList() {
imgList.add(R.drawable.img01);
imgList.add(R.drawable.img02);
imgList.add(R.drawable.img03);
imgList.add(R.drawable.img04);
}
#SuppressWarnings("unchecked")
private void getChannelInfo(String ResultDataFroMsERVER) throws JSONException {
// TODO Auto-generated method stub
channelInfo = resultFromAsyncTask;
Log.e(TAG,"channel Information " +channelInfo );
/*
* Json object for parsing the data(Channel Info)
// */
try {
json = new JSONObject(channelInfo);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ResponseData= json.getJSONArray("Response Data");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i=0 ; i <ResponseData.length();i++)
{
jsonobjectresponsedata = ResponseData.getJSONObject(i);
ChannelID.add(jsonobjectresponsedata.getString("channel_id")) ;
ChannelType.add(jsonobjectresponsedata.getString("channel_type")) ;
VideoType.add(jsonobjectresponsedata.getString("video_type")) ;
ChannelName.add(jsonobjectresponsedata.getString("name")) ;
channelLink.add(jsonobjectresponsedata.getString("link")) ;
ChannelThumbnails.add( jsonobjectresponsedata.getString("img_path")) ;
}
}
private void getDataFromSignIn() {
// TODO Auto-generated method stub
Intent InfoFromSignScreen = getIntent();
UserName = InfoFromSignScreen.getCharSequenceExtra("UserName").toString();
AccessToken = InfoFromSignScreen.getCharSequenceExtra("AccessToken").toString();
Log.e (TAG, "LALITA TEST ***************** USERNAME AND aCCESS TOKEN " + UserName + " "+AccessToken);
}
private void SetUpVariables() {
// TODO Auto-generated method stub
tv = (TextView)findViewById(R.id.textView1);
}
private void FlipImageViewOnClick() {
// TODO Auto-generated method stub
ObjectAnimator animation = ObjectAnimator.ofFloat(PreviewFrameImage, "rotationY", 0.0f, 180f);
animation.setDuration(1500);
animation.setRepeatCount(0);
//animation.setRepeatCount(ObjectAnimator.RESTART);
animation.setInterpolator(new AccelerateInterpolator());
animation.start();
animation.addListener(new AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
// TODO Auto-generated method stub
//PreviewFrameImage.bringToFront();
// mSurface.invalidate();
Toast.makeText(getBaseContext(), "ANimation START ", Toast.LENGTH_SHORT).show();
}
#Override
public void onAnimationRepeat(Animator animation) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "ANimationREPEAT", Toast.LENGTH_SHORT).show();
}
#Override
public void onAnimationEnd(Animator animation) {
// TODO Auto-generated method stub
PreviewFrameImage.setRotationY(0);
// mSurface.bringToFront();
// mSurface.setVisibility(View.VISIBLE);
Toast.makeText(getBaseContext(), "ANimation Endded ", Toast.LENGTH_SHORT).show();
}
#Override
public void onAnimationCancel(Animator animation) {
// TODO Auto-generated method stub
}
});
}
/**
* Setup cover flow.
*
* #param mCoverFlow
* the m cover flow
* #param reflect
* the reflect
*/
/**
* Sets the up listeners.
*
* #param mCoverFlow
* the new up listeners
*/
private void setupListeners(final CoverFlow coverFlow) {
coverFlow.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
/*
* Hls Streams
*/
if(channelLink.get(position).endsWith("m3u8")) {
Log.e(TAG," ******* HLS*************** " +channelLink.get(position) );
if(mMediaPlayer!= null )
{
// mSurface .setZOrderOnTop(true);
mHolder.setFormat(PixelFormat.TRANSPARENT);
controller.hide();
if(mMediaPlayer.isPlaying())
{
mMediaPlayer.stop();
}
mMediaPlayer.reset();
mMediaPlayer.release();
FlipImageViewOnClick();
// mSurface .setZOrderOnTop(false);
mHolder.setFormat(PixelFormat.OPAQUE);
// mSurface.setVisibility(View.VISIBLE);
//PreviewFrame.addView(mSurface);
// mSurface .setZOrderOnTop(false);
playHlsStreams(channelLink.get(position));
}
else
{
FlipImageViewOnClick();
//mSurface .setZOrderOnTop(false);
// mSurface.setVisibility(View.VISIBLE);
// PreviewFrame.addView(mSurface);
// mSurface .setZOrderOnTop(false);
mHolder.setFormat(PixelFormat.OPAQUE);
//mHolder.setFormat(PixelFormat.OPAQUE);
playHlsStreams(channelLink.get(position));
}
}
/*
* Octoshape Streams
*/
else if (channelLink.get(position).startsWith("octoshape"))
{
Log.e(TAG," octoshape " +channelLink.get(position) );
if(mMediaPlayer != null)
{
mHolder.setFormat(PixelFormat.TRANSPARENT);
controller.hide();
if(mMediaPlayer.isPlaying())
{
mMediaPlayer.stop();
}
mMediaPlayer.reset();
mMediaPlayer.release();
FlipImageViewOnClick();
mHolder.setFormat(PixelFormat.OPAQUE);
initOctoshapeSystem(channelLink.get(position)) ;
}
else
{
FlipImageViewOnClick();
initOctoshapeSystem(channelLink.get(position)) ;
}
else
{
Toast.makeText(getBaseContext(), "Youtube Work In Progress and RTMP PLAYER NOT AVAILABLE ", Toast.LENGTH_LONG).show();
}
}
});
}
private void playHlsStreams(String OCTOLINK1) {
// TODO Auto-generated method stub
mMediaPlayer = new MediaPlayer();
controller.setMediaPlayer(this);
controller.setAnchorView(PreviewFrame);
mMediaPlayer.setDisplay(mHolder);
try {
mMediaPlayer.setDataSource(this, Uri.parse(OCTOLINK1));
mMediaPlayer.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mMediaPlayer.start();
}
public void initOctoshapeSystem(final String OCTOLINK1)
{
os = OctoshapeSystemCreator.create(this, problemListener,
new OctoshapePortListener() {
#Override
public void onPortBound(int port) {
setupStream(OCTOLINK1).requestPlay();
}
}, Locale.ENGLISH.getLanguage());
os.setProblemMessageLanguage(Locale.ENGLISH.getLanguage());
os.setProblemListener(problemListener);
os.addPlayerNameAndVersion(MediaPlayerConstants.NATIVE_PLAYER, MediaPlayerConstants.NATIVE_PLAYER,
"" + Build.VERSION.SDK_INT);
os.open();
}
public StreamPlayer setupStream(final String stream) {
Log.d(LOGTAG, "Setting up stream: " + stream);
StreamPlayer sp = os.createStreamPlayer(stream);
sp.setProblemListener(new ProblemListener() {
#Override
public void gotProblem(Problem p) {
StreamStatus="No Stream/Internet Problem";
Log.i("Stream Status ", "Not Ok");
active="yellow";
Log.e(LOGTAG, stream+": "+p.getMessage() + " " + p.toString());
}
});
sp.setListener(new StreamPlayerListener() {
private String playerId;
#Override
public void gotUrl(String url, long seekOffset,
boolean playAfterBuffer) {
Log.i(LOGTAG, "gotUrl");
if (playAfterBuffer)
urlQueue.add(Uri.parse(url));
else
playStream(Uri.parse(url), playerId);
}
#Override
public void gotNewOnDemandStreamDuration(long duration) {
}
#Override
public void resolvedNativeSeek(boolean isLive, String playerId) {
Log.i(LOGTAG, "resolvedNativeSeek");
this.playerId = playerId;
}
#Override
public void resolvedNoSeek(boolean isLive, String playerId) {
Log.i(LOGTAG, "resolvedNoSeek");
this.playerId = playerId;
}
#Override
/**
* Called when stream support OsaSeek / DVR
*/
public void resolvedOsaSeek(boolean isLive, long duration,
String playerId) {
Log.i(LOGTAG, "resolvedOsaSeek");
this.playerId = playerId;
}
});
//sp.initialize(false);
return sp;
}
protected void playStream(Uri mediaUrl, final String playerId) {
Log.d(LOGTAG, playerId + " now plays: " + mediaUrl);
try {
mMediaPlayer = new MediaPlayer();
controller.setMediaPlayer(this);
controller.setAnchorView(PreviewFrame);
mMediaPlayer.setDisplay(mHolder);
mMediaPlayer.setDataSource(this, mediaUrl);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if (!urlQueue.isEmpty())
playStream(urlQueue.removeFirst(), playerId);
}
});
mMediaPlayer.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
error("MediaPlayer Error: " + what + ":" + extra);
return true;
}
});
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (Exception e) {
Log.e(LOGTAG, "Error preparing MediaPlayer", e);
error("Error preparing MediaPlayer: " + e.getMessage());
}
}
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
FrameLayout.LayoutParams vLayout = (FrameLayout.LayoutParams) mSurface
.getLayoutParams();
mSurface.setLayoutParams(vLayout);
// dialog.dismiss();
StreamStatus="Stream Ok";
Log.i("Stream Stattus", "Stream Ok");
active="true";
long startTime = System.currentTimeMillis();
System.out.println("dddddddddddddddddddddddddddddddddddddddddddddd"+startTime);
Timer timer = new Timer();
timer.schedule(new SayHello(), 50000, 60000);
}
#Override
public void onBackPressed() {
// do nothing.
}
public void shutdown(){
if (mMediaPlayer != null)
mMediaPlayer.release();
if (os != null) {
os.close(new Runnable() {
#Override
public void run() {
UserMainScreen.this.finish();
}
});
}
}
#Override
protected void onStop()
{
super.onStop();
Log.d(LOGTAG, "MY onStop is called");
shutdown();
}
ProblemListener problemListener = new ProblemListener() {
#Override
public void gotProblem(Problem p) {
Log.e(LOGTAG, p.getMessage() + "\n" + p.toString());
error(p.getMessage());
}
};
protected void error(final String error) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
// dialog.show();
Log.i(LOGTAG, "problem dialog block");
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
}
class SayHello extends TimerTask {
public void run() {
System.out.println("Catche clear method scheduled");
clearCache();
}
}
void clearCache()
{
Log.d(LOGTAG, "clearCache() clled");
if (mClearCacheObserver == null)
{
mClearCacheObserver=new CachePackageDataObserver();
}
PackageManager mPM=getPackageManager();
#SuppressWarnings("rawtypes")
final Class[] classes= { Long.TYPE, IPackageDataObserver.class };
Long localLong=Long.valueOf(CACHE_APP);
try
{
Method localMethod=
mPM.getClass().getMethod("freeStorageAndNotify", classes);
try
{
localMethod.invoke(mPM, localLong, mClearCacheObserver);
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}
}
catch (NoSuchMethodException e1)
{
e1.printStackTrace();
}
}
private class CachePackageDataObserver extends IPackageDataObserver.Stub
{
public void onRemoveCompleted(String packageName, boolean succeeded)
{
}
}
#Override
public void surfaceCreated(SurfaceHolder mHolder) {
// TODO Auto-generated method stub
Log.e(TAG,"**************Surface created**************LOLZ ") ;
mMediaPlayer.start();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
Log.e(TAG,"Surface CHANGED **************LOLZ ") ;
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
Log.e(TAG,"Surface destroyed **************LOLZ " );
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
}
#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.e(TAG, "GET CURRENT POSITION " +mMediaPlayer.getCurrentPosition());
return mMediaPlayer.getCurrentPosition();
}
#Override
public int getDuration() {
return mMediaPlayer.getDuration();
}
#Override
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
#Override
public void pause() {
mMediaPlayer.pause();
}
#Override
public void seekTo(int i) {
mMediaPlayer.seekTo(i);
}
#Override
public void start() {
mMediaPlayer.start();
}
#Override
public boolean isFullScreen() {
return false;
}
public void toggleFullScreen() {
controller.hide();
mMediaPlayer.stop();
// intent = new Intent(UserMainScreen.this,
// MiniAndroidPlayer.class);
intent.putExtra("OCTO", OCTOLINK1);
startActivity(intent);
}
// End VideoMediaController.MediaPlayerControl
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(PreviewFrame == v )
{
controller.show();
//mSurface.invalidate();
Log.e(TAG, " Preview frame controller Show" +controller.isShown());
}
if( mSurface == v )
{
controller.show(); // do things
// mSurface.invalidate();
Log.e(TAG, " mSurface controller Show" +controller.isShown());
}
if (PreviewFrameImage == v)
{
controller.show(); // do things
Log.e(TAG, " PreviewFrameImage controller Show" +controller.isShown());
}
if ( youTubeView == v) {
controller.show(); // do things
//mSurface.invalidate();
Log.e(TAG, " youtubeView controller Show" +controller.isShown());
//
// controller.setVisibility(View.VISIBLE);
}
return false;
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult errorReason) {
// TODO Auto-generated method stub
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
String errorMessage = String.format(
getString(R.string.error_player), errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
YouTubePlayer player, boolean wasRestored) {
// TODO Auto-generated method stub
if (!wasRestored) {
// loadVideo() will auto play video
// Use cueVideo() method, if you don't want to play it automatically
// player.loadVideo(Config.YOUTUBE_VIDEO_CODE);
//
// Hiding player controls
player.setPlayerStyle(PlayerStyle.MINIMAL);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Retry initialization if user performed a recovery action
// done now getYouTubePlayerProvider().initialize(Config.DEVELOPER_KEY, this);
}
}
/*
* Uncomment again
*/
// private YouTubePlayer.Provider getYouTubePlayerProvider()
// {
// return (YouTubePlayerView) findViewById(R.id.youtube_view);
// }
#Override
public void onAnimationStart(Animator animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationEnd(Animator animation) {
// TODO Auto-generated method stub
PreviewFrameImage.setRotationY(-90);
}
#Override
public void onAnimationCancel(Animator animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationRepeat(Animator animation) {
// TODO Auto-generated method stub
}
public static void initImageLoader(Context context) {
// This configuration tuning is custom. You can tune every option, you may tune some of them,
// or you can create default configuration by
// ImageLoaderConfiguration.createDefault(this);
// method.
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.cacheInMemory(true)
.cacheOnDisc(true)
.considerExifParams(true)
.displayer(new RoundedBitmapDisplayer(20))
.build();
File cacheDir = StorageUtils.getCacheDirectory(context);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.threadPriority(Thread.NORM_PRIORITY - 2)
.denyCacheImageMultipleSizesInMemory()
.discCache(new LimitedAgeDiscCache(cacheDir, 60))
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO)
.writeDebugLogs() // Remove for release app
.defaultDisplayImageOptions(options)
.build();
// Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(config);
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
// TODO Auto-generated method stub
return false;
}
}
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relativeLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/background"
android:orientation="vertical" >
<ImageView
android:id="#+id/previewScreenImageView"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_marginBottom="190dip"
android:layout_marginTop="20dp" />
<FrameLayout
android:id="#+id/videoSurfaceContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="205dp"
android:layout_marginLeft="270dp"
android:layout_marginRight="269dp"
android:layout_marginTop="30dp"
android:text="framelayout"
>
<!-- <com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_view"
android:layout_width="match_parent"
android:layout_height="match_parent" /> -->
<SurfaceView
android:id="#+id/surface_main"
android:layout_width="484dp"
android:layout_height="235dp"
/>
</FrameLayout>
<com.ib.coverflow.CoverFlow
xmlns:coverflow ="http://schemas.android.com/apk/res/com.ib.qezyplay"
android:id ="#+id/coverflow"
android:layout_width ="fill_parent"
android:layout_height ="wrap_content"
android:layout_alignParentBottom="true"
android:paddingBottom="20dp">"
</com.ib.coverflow.CoverFlow>
</RelativeLayout>

Related

mediaplayer.prepare throws IllegalStateException in android 6

I have a code that working in every android version.
but in android 6 throws
IllegalStateException
when i am calling
mediaPlayer.prepare();.
first page is working very well, but when i scroll to another pages, some time working very well and some time it is throwing IllegalStateException and audio can't play.
it is my code:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.mp3_player);
pager = (ViewPager) findViewById(R.id.pager);
Bundle extras = getIntent().getExtras();
final int id = extras.getInt("ID");
auMp3 = id + "_1.mp3";
f = new File(DIR_DATABASE + auMp3);
Uri uri = Uri.parse(G.DIR_DATABASE + auMp3);
if (f.exists()) {
MediaPlayer mp = MediaPlayer.create(G.context, uri);
}
imgPlay.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
if (f.exists()) {
if (mp.isPlaying()) {
imgPlay.setImageResource(R.drawable.iplay);
mp.pause();
} else if ( !mp.isPlaying()) {
imgPlay.setImageResource(R.drawable.ipause);
mp.start();
}
} else {
menu.download(auMp3);
}
}
});
adapter = new AuPagerAdapter(aue);
pager.setAdapter(adapter);
pager.setCurrentItem(aue.size());
OnPageChangeListener currentit = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
int i = aue.size() - arg0;
auMp3 = id + "_" + i + ".mp3";
f = new File(DIR_DATABASE + auMp3);
imgPlay.setImageResource(R.drawable.iplay);
mp.reset();
if (f.exists()) {
try {
mp.setDataSource(G.DIR_DATABASE + auMp3);
}
catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mp.prepareAsync();
}
catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(G.context, "IllegalStateException", 1).show();
}
}
}

Video stops and goes to initial stage after exiting full screen to normal screen

I am working on a video player where I have used custom play/pause, fullscreen etc control buttons for normal screen and default media controller for full screen, which I have customized by adding a control button so that the full screen can be exited and switch back to normal small screen. I am able to full screen the video, but once I click that control button in full screen mode, the video stops and goes back to initial state, though the full screen can be switched to normal screen mode. What I should I do or change in my code so that the video can continue playing? I am searching google for the past three hours still could not find an exact solution. :(
Here is my code:
VideoFragment.java
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_movies, container, false);
frame = (FrameLayout)rootView.findViewById(R.id.frame);
frame2 = (FrameLayout)rootView.findViewById(R.id.frame2);
frame3 = (FrameLayout)rootView.findViewById(R.id.frame3);
marquee = (TextView)rootView.findViewById(R.id.marquee);
marquee.setSelected(true);//focusing the marquee
video = (VideoView) rootView.findViewById(R.id.videoview1);
seekBar = (SeekBar)rootView.findViewById(R.id.seekBar1);
runtime = (TextView)rootView.findViewById(R.id.runtime);
current = (TextView)rootView.findViewById(R.id.current);
list = (ListView)rootView.findViewById(R.id.list);
//list.setTextFilterEnabled(true);
list.setChoiceMode(ListView.CHOICE_MODE_SINGLE);
// _context=this;
listTest = new ArrayList<String>( );
listSoundNames=new ArrayList<String>();
play = (ImageButton)rootView.findViewById(R.id.play);
back = (ImageButton)rootView.findViewById(R.id.prev);
next = (ImageButton)rootView.findViewById(R.id.next);
full = (ImageButton)rootView.findViewById(R.id.full);
//adding listeners
play.setOnClickListener(this);
back.setOnClickListener(this);
next.setOnClickListener(this);
seekBar.setOnSeekBarChangeListener(this);
full.setOnClickListener(this);
//action bar controls
bar = getActivity().getActionBar();
bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#DF0174")));
//bar.setIcon(new ColorDrawable(getResources().getColor(android.R.color.transparent)));
seekBar.setBackgroundColor(Color.BLACK);
seekBar.setProgressDrawable(getResources().getDrawable( R.drawable.seekbar));
seekBar.setScaleY(1f);
ShapeDrawable thumb = new ShapeDrawable(new OvalShape());
thumb.getPaint().setColor(Color.CYAN);
thumb.setIntrinsicHeight(20);
thumb.setIntrinsicWidth(20);
seekBar.setThumb(thumb);
EditText editText = new EditText(getActivity().getApplicationContext());
getActivity().getActionBar().setCustomView(editText);
Scanner("/sdcard/");//storage path
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
/////////////////////////////////////*Adding listener to songs*//////////////////////////////////////////////////
/////////////////////////////////////////////////////////////////////////////////////////////////////////////////
if(listTest.size() != 0)
{
listAdapter=new VideoListAdapter(getActivity().getApplicationContext(),listSoundNames);
list.setAdapter(listAdapter);
list.setOnItemClickListener(new OnItemClickListener()
{
public void onItemClick(AdapterView<?> parent, View view, int position, long id)
{
dm=new DisplayMetrics();
getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
//////////////////changing list item background on click///////////////////
list.setVisibility(View.GONE);
//frame = (FrameLayout)view.findViewById(R.id.frame);
//video = (VideoView) view.findViewById(R.id.videoview1);
//list.setSelection(position);
view.setSelected(true);
///////////////////PROBLEM/////////////
for(int a = 0; a < parent.getChildCount(); a++)
{
list.clearChoices();
parent.getChildAt(a).setBackgroundColor(Color.BLACK);
}
selected_item=position;
// view.setBackgroundColor(Color.RED);
////////////////////////////////////////////////////////////////////////////
//accessing song path
list.setItemChecked(position, true);
list.setSelection(position);
//accessing the song name
String name = (String) ((TextView) view).getText();
title = name;
marquee.setText(title);
//bar.setTitle(title);
//Log.e(TAG, name);
//Toast.makeText(getApplicationContext(), name, Toast.LENGTH_SHORT).show();
try{
index = position;
play.setImageResource(R.drawable.pause);
frame2.setVisibility(View.VISIBLE);
frame3.setVisibility(View.VISIBLE);
frame.setVisibility(View.VISIBLE); ///is this the problem?
video.setVideoPath(listTest.get(position));
video.requestFocus();
video.start();
video.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
play.setImageResource(R.drawable.play);
video.stopPlayback();
video.clearFocus();
list.setVisibility(View.VISIBLE);
frame.setVisibility(View.GONE);
//seekBar.refreshDrawableState();
frame2.setVisibility(View.GONE);
frame3.setVisibility(View.GONE);
}
});
}
catch(Exception e){e.printStackTrace();}
video.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
seekBar.setMax(video.getDuration());
seekBar.postDelayed(onEverySecond, 1000);
time= video.getDuration();
long sec = (time / 1000) % 60;
long min = (time / (60 * 1000))%60;
long hour = time / (60 * 60 * 1000);
String s = (sec < 10) ? "0" + sec : "" + sec;
String m = (min < 10) ? "0" + min : "" + min;
String h = "" + hour;
String time = "";
if(hour > 0) {
time = h + ":" + m + ":" + s;
} else {
time = m + ":" + s;
}
runtime.setText(""+time);
}
});
}
});
}
return rootView;
}
private Runnable onEverySecond=new Runnable() {
#Override
public void run() {
if(seekBar != null) {
seekBar.setProgress(video.getCurrentPosition());
run = video.getCurrentPosition();
long sec2 = (run / 1000) % 60;
long min2 = (run / (60 * 1000))%60;
long hour2 = run / (60 * 60 * 1000);
String s2 = (sec2 < 10) ? "0" + sec2 : "" + sec2;
String m2 = (min2 < 10) ? "0" + min2 : "" + min2;
String h2 = "" + hour2;
String run = "";
if(hour2 > 0) {
run = h2 + ":" + m2 + ":" + s2;
} else {
run = m2 + ":" + s2;
}
current.setText(""+run);
}
if(video.isPlaying()) {
seekBar.postDelayed(onEverySecond, 1000);
}
}
};
///////////////////orientation change//////////////////////
/* #Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
//Checks the orientation of the screen
if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
Toast.makeText(getActivity().getApplicationContext(), "landscape", Toast.LENGTH_SHORT).show();
video.setLayoutParams(new FrameLayout.LayoutParams(600,270));//changing layout size
} else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
Toast.makeText(getActivity().getApplicationContext(), "portait", Toast.LENGTH_SHORT).show();
video.setLayoutParams(new FrameLayout.LayoutParams(350, dm.widthPixels));//changing layout size
}
}*/
/////////////////////////////////////////////////////////////////////
private void Scanner(String path) {
// TODO Auto-generated method stub
{
try
{
File fl = new File(path);
File[] listOfFiles = fl.listFiles();
for (File listOfFile : listOfFiles)
{
String s = listOfFile.getName();
if(s.endsWith(".mp4"))
{
songpath = listOfFile.getPath();
listTest.add(songpath);//adding song names to list
//listTest.toString().replaceFirst(songpath, s);
// store file name in listSoundNames
int pos = s.lastIndexOf(".");
if (pos > 0)
{
song = s.substring(0, pos);
}
listSoundNames.add(song);
}
/////////////////////////////////
File f = new File(path+s+"/");
if (f.exists() && f.isDirectory()) {
Scanner(path+s+"/");
}
////////////////////////////////
}
}
catch (Exception e) { }
}
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (v.equals(play))
{
if(video.isPlaying())
{
video.pause();
progress=video.getCurrentPosition();
//change in button image//
play.setImageResource(R.drawable.play);
}
else
{
video.start();
seekBar.setProgress(video.getCurrentPosition());
seekBar.setMax(video.getDuration());
seekBar.postDelayed(onEverySecond, 1000);
//change in button image//
play.setImageResource(R.drawable.pause);
//
}
}
if (v.equals(back))
{
video.stopPlayback();
video.refreshDrawableState();
//bar.setTitle(song);
if(index!=0)
{
index = index -1;
selected_item=index;
listAdapter.notifyDataSetChanged();//shifting the highlight to the song played
}
else
{
index = (list.getAdapter().getCount()-1);
selected_item=index;
listAdapter.notifyDataSetChanged();
}
Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
try {
//mp.setDataSource(getActivity().getApplicationContext(), uri);//setting new data source
video.setVideoURI(uri);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
}
try {
//video.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
video.start();
title = uri.getLastPathSegment();
marquee.setText(title);
play.setImageResource(R.drawable.pause);
}
if (v.equals(next))
{
video.stopPlayback();
video.refreshDrawableState();
index = index +1;
if(index>(listSoundNames.size()-1))
{
index=0;
}
play.setImageResource(R.drawable.pause);
//index = index +1;
selected_item=index;
listAdapter.notifyDataSetChanged();
//Toast.makeText(MP3.this, ""+selected_item, Toast.LENGTH_SHORT).show();
Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
try {
//mp.setDataSource(getActivity().getApplicationContext(), uri);//setting new data source
video.setVideoURI(uri);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
Toast.makeText(getActivity().getApplicationContext(), "ERROR", Toast.LENGTH_SHORT).show();///PROBLEM:MOVING HERE AFTER CLICKING NEXT BUTTON
}
try {
//mp.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
video.start();
title = uri.getLastPathSegment();
marquee.setText(title);
}
if(v.equals(full))
{
Uri uri = Uri.parse(listTest.get(index).toString());//getting the path of next song
/*Uri uri = Uri.parse(listTest.get(index).toString());
Toast.makeText(getApplicationContext(), "full", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_VIEW );
intent.setDataAndType((uri), "video/*");
startActivity(intent);*/
Intent intent = new Intent(getActivity().getApplicationContext(),Full.class);
Bundle b2 = new Bundle();
b2.putString("path", uri.toString());
b2.putInt("progress", video.getCurrentPosition());
intent.putExtras(b2);
this.startActivity(intent);
}
}
#Override
public void onPause() {
super.onPause();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
if(fromUser) {
// this is when actually seekbar has been seeked to a new position
video.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
int progress = seekBar.getProgress();
if (video != null && video.isPlaying()) {
// Set the position of the currently playing
video.seekTo(progress);
}
}
///////////////////////////stopping the current audio/video when tab is swiped/////////////////////////////////
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
// Make sure that we are currently visible
if (this.isVisible()) {
// If we are becoming invisible, then...
///video.start();
//Log.e("MyFragment", "Visible again. Starting audio.");
//video.clearFocus();
//play.setImageResource(R.drawable.pause);
if (!isVisibleToUser) {
Log.e("MyFragment", "Not visible anymore. Stopping audio.");
// TODO stop audio playback
/* play.setImageResource(R.drawable.play);
video.stopPlayback();
video.clearFocus();
list.setVisibility(View.VISIBLE);
frame.setVisibility(View.GONE);
//seekBar.refreshDrawableState();
frame2.setVisibility(View.GONE);
*/
//video.stopPlayback();
video.pause();
//video.clearFocus();
play.setImageResource(R.drawable.play);
}
}
}
////////////////////////////////////////////////////////////////////////////////////////////////////////////////
}
Full.java// for the full screen
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fullsc);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
Bundle bundle = getIntent().getExtras();
path = bundle.getString("path");
pos = bundle.getInt("progress");
Uri uri = Uri.parse(path);
video = (VideoView) findViewById(R.id.fullv);
getActionBar().hide();
/* video.setMediaController(new MediaController(this){
public boolean dispatchKeyEvent(KeyEvent event)
{
if (event.getKeyCode() == KeyEvent.KEYCODE_BACK)
((Activity) getContext()).finish();
return super.dispatchKeyEvent(event);
}
});*/
controller = new CMediaController(this);
/* controller.setPrevNextListeners(new View.OnClickListener() {
#Override
public void onClick(View v) {
//next button clicked
Toast.makeText(getApplicationContext(), "next", Toast.LENGTH_SHORT).show();
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FORCE_NOT_FULLSCREEN);
getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
v.requestLayout();
}
}, new View.OnClickListener() {
#Override
public void onClick(View v) {
//previous button clicked
Toast.makeText(getApplicationContext(), "prev", Toast.LENGTH_SHORT).show();
}
});*/
video.setMediaController(controller);
video.setVideoURI(uri);
video.seekTo(pos);
video.requestFocus();
video.start();
}
}
fullsc.xml//layout for full screen
<?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:orientation="vertical"
android:background="#000000">
<VideoView
android:layout_gravity="center"
android:id="#+id/fullv"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:keepScreenOn="true"
/>
</LinearLayout>
CMediaController.java // for the media controller customization
public class CMediaController extends MediaController {
Context mContext;
//private OnMediaControllerInteractionListener mListener;
public CMediaController(Context context) {
super(context);
// TODO Auto-generated constructor stub
mContext = context;
}
#Override
public void setAnchorView(View view) {
super.setAnchorView(view);
ImageButton full = new ImageButton(mContext);
full.setBackgroundResource(R.id.full);
full.setOnClickListener((new View.OnClickListener() {
#Override
public void onClick(View v) {
//next button clicked
Toast.makeText(mContext, "return to small", Toast.LENGTH_SHORT).show();
((Activity) getContext()).finish();//exiting but stopping the video and setting it to initial state
/*
Intent intent = new Intent(mContext,VideoFragment.class);
//Bundle b2 = new Bundle();
b2.putString("path", uri.toString());
b2.putInt("progress", video.getCurrentPosition());
intent.putExtras(b2);
mContext.startActivity(intent);*/
}}));
/*full = (ImageButton)findViewById(R.id.full);*/
//full.setOnClickListener(this);
FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.gravity = Gravity.RIGHT;
addView(full, params);
}
/*#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(mContext, "small", Toast.LENGTH_SHORT).show();
}*/
}

Playing music even after the UI has been closed

Well I am a bit confused with the following.
I have a class (Main Player UI) that has the mediaplayer object.
Now the problem is that I want the music to played even after the UI has been disposed, hence I have to depend on the service.
But then if I move the MediaPlayer to the Service class
How am I going to control the onCompletion(MediaPlayer arg0) when the player UI is shown up, which also needs to show the change in the song? But then the method has to be included in the Service method.
How do I make the Play buttons on the UI to start the song that is available in the Service method?
Please guide me. The current player class that holds the UI as well as the mediaplayer is as follows:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_boombastic_player);
//INITIALIZATIONS
mMediaPlayer=new MediaPlayer();
utils = new Utilities();
songProgressBar=(SeekBar)findViewById(R.string.seeker);
play=(Button)findViewById(R.string.play);
next=(Button)findViewById(R.string.next);
previous=(Button)findViewById(R.string.previous);
playlist=(Button)findViewById(R.string.Playlist);
search=(Button)findViewById(R.string.search);
repeat=(Button)findViewById(R.string.repeat);
shuffle=(Button)findViewById(R.string.shuffle);
starttime=(TextView)findViewById(R.string.startTime);
endtime=(TextView)findViewById(R.string.endTime);
ObjectIntermediate=new Intermediate();
srvMplayer=new ServiceMan();
//Preparation
if(!Searched)
{
GetAllSongs();
Searched=true;
ShowToast("Finished Search");
}
songProgressBar.setOnSeekBarChangeListener(this); // Important
mMediaPlayer.setOnCompletionListener(this);
play.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
// check for already playing
if(mMediaPlayer.isPlaying())
{
if(mMediaPlayer!=null)
{
mMediaPlayer.pause();
/* Release Service*/
// Changing button image to play button
play.setBackgroundResource(R.drawable.playback_play);
}
}
else
{
// Resume song
if(mMediaPlayer!=null)
{
mMediaPlayer.start();
/* Starting Service*/
// Changing button image to pause button
play.setBackgroundResource(R.drawable.pause);
}
}
}
});
next.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
// check if next song is there or not
if(isRepeat)
{
playSong(currentSongIndex);
}
else if(isShuffle)
{
ShuffleSong();
playSong(currentSongIndex);
}
else if(currentSongIndex < (BoombasticPlayer.Songslist.size() - 1))
{
try
{
ShowToast(Integer.toString(currentSongIndex));
playSong(currentSongIndex + 1);
}
catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
Log.e("~~IllegalArgumentException~~",e.toString());
android.util.Log.e("->>" , "~~stacktrace~~", e);
}
catch (IllegalStateException e)
{
// TODO Auto-generated catch block
Log.e("~~IllegalStateException~~",e.toString());
android.util.Log.e("->>" , "~~stacktrace~~", e);
}
currentSongIndex = currentSongIndex + 1;
}
else
{
// play first song
try
{
playSong(0);
}
catch (IllegalArgumentException e)
{
// TODO Auto-generated catch block
Log.e("~~IllegalArgumentException~~",e.toString());
android.util.Log.e("->>" , "~~stacktrace~~", e);
}
catch (IllegalStateException e)
{
// TODO Auto-generated catch block
Log.e("~~IllegalStateException~~",e.toString());
android.util.Log.e("->>" , "~~stacktrace~~", e);
}
currentSongIndex = 0;
}
}
});
previous.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(isRepeat)
{
playSong(currentSongIndex);
}
else if(currentSongIndex > 0)
{
try {
playSong(currentSongIndex - 1);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
currentSongIndex = currentSongIndex - 1;
}
else
{
// play last song
try {
playSong(BoombasticPlayer.Songslist.size() - 1);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
currentSongIndex = BoombasticPlayer.Songslist.size() - 1;
}
}
});
playlist.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
Intent playlistIntent= new Intent(arg0.getContext(), Playlist.class);
startActivityForResult(playlistIntent, MODE_APPEND);
}
});
repeat.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(isRepeat==true)
{
isRepeat=false;
ShowToast("Repeat OFF");
}
else
{
isRepeat=true;
ShowToast("Repeat ON");
}
}
});
shuffle.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View arg0)
{
// TODO Auto-generated method stub
if(isShuffle==true)
{
isShuffle=false;
ShowToast("Shuffle OFF");
}
else
{
isShuffle=true;
ShowToast("Shuffle ON");
}
}
});
}

I Want to detect Screen Resolution

I have an android application with a country map divided into Districts...
and in the database.xml file i put the XY coordinates positions for each District in the map...
But, when I run the application on a device with a different screen size,
the positions change and Didn't fit the positions that I need!
So, Please I Want to know how to detect the screen size, and create a separate XY database for each screen resolution!
Thank you in Advance,
here is the MainActivity.java Code, if you want anything else I will post it,
please I need your help! :(
private final Context appContext = MainActivity.this;
RelativeLayout relativeLayoutMap;
ProgressDialog xyProgressDialog;
Dialog dialog;
Spinner spinner;
MediaPlayer mediaPlayer;
static String extStorageDirectory = Environment
.getExternalStorageDirectory().toString();
final static String TARGET_BASE_PATH = extStorageDirectory + "/";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relativeLayoutMap = (RelativeLayout) findViewById(R.id.mapContainer);
checklanguage();
clickRadioButton();
playMusicOnCoordinatesClick();
new saveFoldertoSDCard().execute("MyApp");
**//Display myDisplay = getWindowManager().getDefaultDisplay();
//Point point = new Point();
//myDisplay.getSize(point);
//int width = point.x;
//int height = point.y;**
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void clickRadioButton() {
RadioButton rdbtnEnglish = (RadioButton) findViewById(R.id.rdBtnEnglish);
if(rdbtnEnglish.isChecked()){
saveLanguageSelection(true);
}else{
saveLanguageSelection(false);
}
rdbtnEnglish.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
saveLanguageSelection(isChecked);
}
});
}
public void elabirate() {
int coordinates = Coordinates.sCoordinatesList.size();
int i;
for (i = 0; i < coordinates; i++) {
final Button btnclick = new Button(appContext);
btnclick.setId(i);
RadioButton rdbtnEnglish = (RadioButton) findViewById(R.id.rdBtnEnglish);
if(rdbtnEnglish.isChecked()){
btnclick.setText("" + Coordinates.sCoordinatesList.get(i).getName());
}else{
btnclick.setText("" + Coordinates.sCoordinatesList.get(i).getArabicCityName());
}
btnclick.setBackgroundResource(R.drawable.round_button_selector);
btnclick.setTextColor(Color.CYAN);
LayoutParams lp = new LayoutParams(
android.app.ActionBar.LayoutParams.WRAP_CONTENT,
android.app.ActionBar.LayoutParams.WRAP_CONTENT);
lp.topMargin = Coordinates.sCoordinatesList.get(i).getX();
lp.leftMargin = Coordinates.sCoordinatesList.get(i).getY();
relativeLayoutMap.addView(btnclick, lp);
btnclick.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Integer id = btnclick.getId();
Intent intent = new Intent();
intent.setClass(appContext, CityActivity.class);
intent.putExtra("btnid", id.toString());
startActivity(intent);
}
});
}
}
public void changeCoordinatesLanguage(View view){
RadioButton rdbtnEnglish = (RadioButton) findViewById(R.id.rdBtnEnglish);
int coordinates = Coordinates.sCoordinatesList.size();
int i;
for (i = 0; i < coordinates; i++) {
final Button btnCoordinates = (Button) findViewById(i);
if(rdbtnEnglish.isChecked()){
btnCoordinates.setText("" + Coordinates.sCoordinatesList.get(i).getName());
loadCityList();
}else{
btnCoordinates.setText("" + Coordinates.sCoordinatesList.get(i).getArabicCityName());
loadCityList();
}
}
}
public class GetCoordinates extends AsyncTask<String, Integer, Boolean> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
xyProgressDialog = new ProgressDialog(appContext);
xyProgressDialog.setMessage("Loading...");
xyProgressDialog.setCancelable(false);
xyProgressDialog.show();
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
return Coordinates.getCity();
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
try {
xyProgressDialog.dismiss();
if (result) {
elabirate();
loadCityList();
} else {
Toast.makeText(appContext, "Unable to load City list",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO: handle exception
}
super.onPostExecute(result);
}
}
public void loadImage(){
dialog = new Dialog(appContext);
dialog.setContentView(R.layout.progress_dialog);
dialog.setTitle("Load Progress");
dialog.show();
}
public class saveFoldertoSDCard extends AsyncTask<String, Integer, Boolean> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog = new Dialog(appContext);
dialog.setContentView(R.layout.progress_dialog);
dialog.setTitle("My App");
dialog.setCancelable(false);
dialog.show();
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
return copyFileOrDir(params[0]);
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
try {
//xyProgressDialog.dismiss();
dialog.dismiss();
if (result) {
String path = Environment.getExternalStorageDirectory()
.toString()
+ "/MyApp/MyAppdata.xml";
new GetCoordinates().execute(path);
}
} catch (Exception e) {
// TODO: handle exception
}
super.onPostExecute(result);
}
}
private Boolean copyFileOrDir(String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = TARGET_BASE_PATH + path;
Log.i("tag", "path=" + fullPath);
File dir = new File(fullPath);
if (!dir.exists())
if (!dir.mkdirs())
;
Log.i("tag", "could not create dir " + fullPath);
for (int i = 0; i < assets.length; ++i) {
String p;
if (path.equals(""))
p = "";
else
p = path + "/";
copyFileOrDir(p + assets[i]);
}
}
return true;
} catch (IOException ex) {
return false;
}
}
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
String newFileName = null;
try {
in = assetManager.open(filename);
if (filename.endsWith(".png")) // extension was added to avoid
// compression on APK file
newFileName = TARGET_BASE_PATH
+ filename.substring(0, filename.length() - 4);
else
newFileName = TARGET_BASE_PATH + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
}
}
public void saveLanguageSelection(boolean value) {
SharedPreferences Shared_preferences = PreferenceManager
.getDefaultSharedPreferences(appContext);
SharedPreferences.Editor editor = Shared_preferences.edit();
if (value) {
editor.putString("lang", "english");
} else {
editor.putString("lang", "arabic");
}
editor.commit();
}
public void checklanguage() {
RadioButton rdbtnEnglish = (RadioButton) findViewById(R.id.rdBtnEnglish);
RadioButton rdbtnArabic = (RadioButton) findViewById(R.id.rdBtnArabic);
SharedPreferences Shared_preferences = PreferenceManager
.getDefaultSharedPreferences(appContext);
String txtlanguage = Shared_preferences.getString("lang", "null");
if (txtlanguage != "null") {
if (txtlanguage.equals("english")) {
rdbtnEnglish.setChecked(true);
rdbtnArabic.setChecked(false);
} else {
rdbtnEnglish.setChecked(false);
rdbtnArabic.setChecked(true);
}
} else {
rdbtnEnglish.setChecked(true);
rdbtnArabic.setChecked(false);
saveLanguageSelection(true);
}
}
public void showWeather(View view) {
String url = "http://m.accuweather.com/";
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//parse: to check the availability of the url, ex: 123?
startActivity(browserIntent);
}
public void aboutApp(View view) {
openAboutDialog();
}
#SuppressWarnings("deprecation")
private void openAboutDialog() {
final AlertDialog alertDialog = new AlertDialog.Builder(
MainActivity.this).create();
alertDialog.setTitle("About");
alertDialog.setMessage("MyApp");
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
public void loadCityList(){
Integer type=0;
RadioButton rdbtnEnglish = (RadioButton) findViewById(R.id.rdBtnEnglish);
if(rdbtnEnglish.isChecked()){
type=0;
}else{
type=1;
}
CityList.getAllCityList(type);
CityListAdapter cityAdapter = new CityListAdapter(appContext, CityList.sCityList);
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setAdapter(cityAdapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View view,
int arg2, long arg3) {
// TODO Auto-generated method stub
if(arg2 > 0){
TextView txtcityId = (TextView) view.findViewById(R.id.txtCityId);
TextView txtXyId = (TextView) view.findViewById(R.id.txtxyId);
Intent intent = new Intent();
intent.setClass(appContext, CityImagesActivity.class);
intent.putExtra("xyid", txtXyId.getText().toString());
intent.putExtra("cityid", txtcityId.getText().toString());
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
public void playMusicOnCoordinatesClick() {
mediaPlayer = new MediaPlayer();
mediaPlayer.reset();
try {
AssetFileDescriptor afd = getAssets().openFd("Intro.mp3");
mediaPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.setVolume(100, 100);
mediaPlayer.start();
}
public void calledSearch(View view){
Intent intent = new Intent();
intent.setClass(appContext, SearchActivity.class);
startActivity(intent);
}
You can use something like:
Display myDisplay = getWindowManager().getDefaultDisplay();
Point point = new Point();
myDisplay.getSize(point);
int width = point.x;
int height = point.y;
as per this awesome answer.
If your map view is not full screen then I suggest using percentages to set the size of the map. This way you can use a percentage offset with your coordinates to alleviate the varying screen size issue. You definitely don't want to store different sets of XML co-ordinates for different screen resolutions.

Android SeekBar: When setProgress then SeekBar progress is jumping to the beginning/middle/end

I have a problem of that how to setup seekbar to work correctly when I setProgress upon click. Progress is jumping to the beginning/middle/end depends on where I click on it. How is it possible to solve?
That my attemps:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
videoPath = getIntent().getExtras().getString("videoPath");
videoView = (VideoView) findViewById(R.id.vvPlayer);
seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(this);
....
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
seekBar.setMax(mp.getDuration());
System.out.println("curpos" + mp.getCurrentPosition());
new Thread(new Runnable() {
public void run() {
try {
while (mPlayer != null && mPlayer.getCurrentPosition() < mPlayer.getDuration()) {
seekBar.setProgress(mPlayer.getCurrentPosition());
Message msg = new Message();
int millis = mPlayer.getCurrentPosition();
msg.obj = millis / 1000;
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
System.out.println("interrupt exeption" + e);
}
}
} catch (Exception e) {
e.printStackTrace();
System.out.println("my Exception" + e);
}
}
}).start();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
Log.e("onProgressChanged: ", Integer.toString(progress));
mPlayer.seekTo(progress);
}
}
Full Code:
public class VideoPlayerActivity extends Activity implements Callback, OnSeekBarChangeListener, OnTouchListener, OnErrorListener, OnCompletionListener, OnPreparedListener {
MediaPlayer mPlayer;
AssetFileDescriptor afd;
VideoView videoView;
SurfaceHolder holder;
MediaController mController;
String videoPath;
SeekBar seekBar;
ImageButton mPlay, mStop, mPause;
TextView mCurDuration, mDuration;
int position = 0;
Handler handler = new Handler();
Runnable r;
boolean controlsVisibility = true;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_video_player);
getWindow().setFormat(PixelFormat.TRANSLUCENT);
mDuration = (TextView) findViewById(R.id.tvDuration);
mCurDuration = (TextView) findViewById(R.id.tvCurDuration);
videoPath = getIntent().getExtras().getString("videoPath");
videoView = (VideoView) findViewById(R.id.vvPlayer);
seekBar = (SeekBar) findViewById(R.id.seekBar);
seekBar.setOnSeekBarChangeListener(this);
seekBar.setFocusable(false);
videoView.setOnTouchListener(this);
mPlay = (ImageButton) findViewById(R.id.play);
mPause = (ImageButton) findViewById(R.id.pause);
mStop = (ImageButton) findViewById(R.id.stop);
mController = new MediaController(this);
videoView.setMediaController(mController);
holder = videoView.getHolder();
holder.addCallback(this);
holder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mPlay.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Log.e("Play:", " is Pressed!");
if (mPlayer == null)
playVideo();
mPlayer.start();
}
});
mPause.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Log.e("Pause:", " is Pressed!");
if (mPlayer != null) {
handler.removeCallbacks(r);
controlsVisibility=true;
AutoHideControls();
Log.e("mPlayer status: ", "Not Null");
if (mPlayer.isPlaying())
Log.e("mPlayer status: ", "Not Null");
mPlayer.pause();
}
}
});
mStop.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
Log.e("Stop:", " is Pressed!");
if (mPlayer != null) {
handler.removeCallbacks(r);
controlsVisibility=true;
AutoHideControls();
seekBar.setProgress(0);
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
}
});
}
private void playVideo() {
try {
if (afd != null && mPlayer != null) {
mPlayer.start();
return;
}
Log.e("VideoPath:", videoPath);
if (videoPath != "") {
afd = getAssets().openFd(videoPath);
// "videos/start.mp4"
mPlayer = new MediaPlayer();
mPlayer.setOnErrorListener(this);
mPlayer.setOnCompletionListener(this);
mPlayer.setOnPreparedListener(this);
mPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mPlayer.setScreenOnWhilePlaying(true);
mPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mPlayer.setDisplay(holder);
mPlayer.setDataSource(afd.getFileDescriptor(), afd.getStartOffset(), afd.getLength());
mPlayer.prepare();
mPlayer.start();
handler.removeCallbacks(r);
controlsVisibility=true;
AutoHideControls();
}
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void surfaceCreated(SurfaceHolder holder) {
runOnUiThread(new Runnable() {
public void run() {
playVideo();
}
});
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width, int height) {
// TODO Auto-generated method stub
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
Log.e("Debug:", "onError---> what:" + what + " extra:" + extra);
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
mPlayer = null;
}
return true;
}
#Override
public void onCompletion(MediaPlayer mp) {
mPlayer.release();
finish();
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
if (mPlayer != null) {
mPlayer.stop();
mPlayer.release();
}
finish();
return true;
}
return super.onKeyDown(keyCode, event);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if (controlsVisibility) {
controlsVisibility = false;
mPlay.setVisibility(View.GONE);
mPause.setVisibility(View.GONE);
mStop.setVisibility(View.GONE);
seekBar.setVisibility(View.GONE);
handler.removeCallbacks(r);
} else {
controlsVisibility = true;
mPlay.setVisibility(View.VISIBLE);
mPause.setVisibility(View.VISIBLE);
mStop.setVisibility(View.VISIBLE);
seekBar.setVisibility(View.VISIBLE);
AutoHideControls();
}
return false;
}
public void AutoHideControls() {
r = new Runnable() {
public void run() {
controlsVisibility = false;
mPlay.setVisibility(View.GONE);
mPause.setVisibility(View.GONE);
mStop.setVisibility(View.GONE);
seekBar.setVisibility(View.GONE);
}
};
handler.removeCallbacks(r);
handler.postDelayed(r, 4000);
}
#Override
public void onPrepared(MediaPlayer mp) {
seekBar.setMax(mp.getDuration());
new Thread(new Runnable() {
public void run() {
int currentPosition = 0;
int total = mPlayer.getDuration();
seekBar.setMax(total);
while (mPlayer != null && currentPosition < total) {
try {
Thread.sleep(1000);
currentPosition = mPlayer.getCurrentPosition();
} catch (InterruptedException e) {
return;
} catch (Exception e) {
return;
}
seekBar.setProgress(currentPosition);
}
}
}).start();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
Log.e("onProgressChanged: ", Integer.toString(progress));
mPlayer.seekTo(progress);
}
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
// TODO Auto-generated method stub
}
}
The same but throughtout AsyncTask (but the same result - still jumping):
#Override
public void onPrepared(MediaPlayer mp) {
seekBar.setMax(mp.getDuration());
new Async().execute();
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromUser) {
// TODO Auto-generated method stub
if (fromUser) {
Log.e("onProgressChanged: ", Integer.toString(progress));
mPlayer.seekTo(progress);
seekBar.setProgress(progress);
Log.e("SeekedProgressTime: ", Integer.toString(mPlayer.getCurrentPosition()));
Log.e("SeekedProgressTime: ", Integer.toString(seekBar.getProgress()));
}
}
class Async extends AsyncTask<Void, Integer, Void> {
#Override
protected Void doInBackground(Void... params) {
// TODO Auto-generated method stub
int currentPosition = 0;
int total = mPlayer.getDuration();
seekBar.setMax(total);
while (mPlayer != null && currentPosition < total) {
Log.e("Current mPlayer time in Thread: ", Integer.toString(mPlayer.getCurrentPosition()));
Log.e("Current seekBar time in Thread: ", Integer.toString(seekBar.getProgress()));
try {
Thread.sleep(1000);
currentPosition = mPlayer.getCurrentPosition();
} catch (InterruptedException e) {
} catch (Exception e) {
}
seekBar.setProgress(currentPosition);
}
return null;
}
}
Maybe, I did something wrong inside the AsyncTask, I cannot understand what is the problem with this seekBar. Check what real position it takes when you click somewhere on the seekbar, everything correct but in one moment its position value overrides somehow.

Categories

Resources