mediaplayer.prepare throws IllegalStateException in android 6 - android

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();
}
}
}

Related

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

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>

Android Media Player Next Song

I have a listview in MainActivity from hehe i passing my listview position using this
Intent intent = new Intent(MainActivity.this, Linkview.class);
intent.putExtra("position", position);
startActivity(intent);
And I have a Linkview class here i received my position using this
final Bundle bundle = getIntent().getExtras();
position = bundle.getInt("position");
And i have a linkArray list.
link = getResources().getStringArray(R.array.lin
My player play well and i can stop it.
But I have a next button
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
uri = Uri.parse(link[position+1]);
}
});
When I pressed my next button nothing is happened. I want that when I pressed the next button from my array next link will be play but nothing is play.
How i can solve this issue.
My hole code is here.
public class Linkview extends Activity {
Button play, stop, next;
MediaPlayer mediaPlayer;
private String currentSongIndex;
RowItem rowItem;
MainActivity mainActivity;
Uri uri;
public String link[];
int position;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, 0);
setContentView(R.layout.activity_linkview);
stop = (Button) findViewById(R.id.stopbutton);
play = (Button) findViewById(R.id.playbutton);
next = (Button) findViewById(R.id.nextbutton1);
link = getResources().getStringArray(R.array.link);
// String itemString = MainActivity.link[position];
final Bundle bundle = getIntent().getExtras();
// String link = bundle.getString("link");
// position = bundle.getInt("position");
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
if (position <= 2) {
uri = Uri.parse(link[position + 1]);
}
}
});
position = bundle.getInt("position");
uri = Uri.parse(link[position]);
// .parse("android.resource://com.prgguru.example/"
// + R.raw.hosannatamil);");
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource(getApplicationContext(), 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();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
stop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if (mediaPlayer != null && mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
}
});
play.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mediaPlayer.start();
}
});
}
protected void onDestroy() {
super.onDestroy();
// TODO Auto-generated method stub
if (mediaPlayer != null) {
mediaPlayer.release();
mediaPlayer = null;
}
}
}
Maybe this will work:
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mediaPlayer.stop();
uri = Uri.parse(link[position + 1]);
mediaPlayer.setDataSource(getApplicationContext(), uri);
mediaPlayer.prepare();
mediaPlayer.start();
}
});

Get mediaplayer service screen from service

I have a media player service that plays a music in background, and this service is called from an activity. Now when i ex. exit from that activity, and get back to it again, i want to see what is the status, what song is played etc.
Here is the code from my service:
public class MediaPlayerService extends Service implements
OnCompletionListener, OnClickListener {
MediaPlayer mediaPlayer;
String url;
int mediaPos, mediaMax, position;
boolean isShufle;
WeakReference<SeekBar> seekbar;
WeakReference<TextView> reciter, songTitle, songPos;
private WeakReference<ImageView> play, forward, backward;
ArrayList<Songs> songs;
Handler handler;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
// mediaPlayer = MediaPlayer.create(this,url);// raw/s.mp3
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
}
private void play(final int position) throws IllegalArgumentException,
SecurityException, IllegalStateException, IOException {
/*
* dialog = ProgressDialog.show(AlbumDetails.this, "",
* getString(com.darkovski.quran.R.string.buffering), true);
* dialog.setCancelable(true); dialog.show();
*/
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setDataSource(songs.get(position).getLink());
// prepare track
mediaPlayer.prepare();
mediaPlayer.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
play.get().setImageResource(R.drawable.pause);
// play.setImageResource(R.drawable.pause);
// this is new
mediaPos = mp.getCurrentPosition();
mediaMax = mp.getDuration();
reciter.get().setText(songs.get(position).getRecitorName());
songTitle.get().setText(songs.get(position).getTitle());
songPos.get().setText((position + 1) + " of 114");
seekbar.get().setMax(mediaMax);
seekbar.get().setProgress(mediaPos);
handler.removeCallbacks(moveSeekBarThread);
handler.postDelayed(moveSeekBarThread, 100);
mp.start();
// dialog.dismiss();
}
});
// when truck finishes
mediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
// if(shuffle)
try {
if (isShufle) {
play(new Random().nextInt(songs.size()));
} else {
if (position == songs.size())
play(0);
else
play(position + 1);
}
AlbumDetails.position += 1;
} 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();
}
}
});
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
url = intent.getStringExtra("url");
handler = new Handler();
position = intent.getIntExtra("position", -1);
forward = new WeakReference<ImageView>(AlbumDetails.forward);
backward = new WeakReference<ImageView>(AlbumDetails.backward);
play = new WeakReference<ImageView>(AlbumDetails.play);
play.get().setOnClickListener(this);
forward.get().setOnClickListener(this);
backward.get().setOnClickListener(this);
seekbar = new WeakReference<SeekBar>(AlbumDetails.seekbar);
reciter = new WeakReference<TextView>(AlbumDetails.reciter);
songTitle = new WeakReference<TextView>(AlbumDetails.songTitle);
songPos = new WeakReference<TextView>(AlbumDetails.songPos);
songs = AlbumDetails.songs;
seekbar.get().setOnSeekBarChangeListener(new OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
#Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
#Override
public void onProgressChanged(SeekBar seekBar, int progress,
boolean fromUser) {
if (fromUser && mediaPlayer.isPlaying()) {
mediaPlayer.seekTo(progress);
}
}
});
/*
* try { mediaPlayer.setDataSource(url); mediaPlayer.prepare();
* mediaPlayer.setOnCompletionListener(this); } 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(); } if (!mediaPlayer.isPlaying()) {
* mediaPlayer.start(); }
*/
try {
play(position);
} 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();
}
return START_STICKY;
}
public void onDestroy() {
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.release();
}
public void onCompletion(MediaPlayer _mediaPlayer) {
stopSelf();
}
private Runnable moveSeekBarThread = new Runnable() {
public void run() {
if (mediaPlayer.isPlaying()) {
int mediaPos_new = mediaPlayer.getCurrentPosition();
int mediaMax_new = mediaPlayer.getDuration();
seekbar.get().setMax(mediaMax_new);
seekbar.get().setProgress(mediaPos_new);
handler.postDelayed(this, 100);
}
}
};
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.playeer_back:
try {
if (mediaPlayer != null)
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
if (position - 1 < 0) {
play(songs.size());
position = songs.size();
} else
play(position - 1);
} catch (IllegalArgumentException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (SecurityException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IllegalStateException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
} catch (IOException e2) {
// TODO Auto-generated catch block
e2.printStackTrace();
}
break;
case R.id.playeer_forward:
try {
if (mediaPlayer != null)
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
mediaPlayer.release();
}
play(position + 1);
position += 1;
} 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();
}
break;
case R.id.playeer_play:
if (mediaPlayer == null) {
try {
play(position);
} 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();
}
} else if (mediaPlayer.isPlaying()) {
mediaPlayer.pause();
play.get().setImageResource(R.drawable.pause);
} else if (mediaPlayer != null) {
mediaPlayer.start();
play.get().setImageResource(R.drawable.play_play);
}
// playFunction();
break;
}
}
}
And my activity code - onClick:
case R.id.playeer_play:
playbackServiceIntent
.putExtra("url", songs.get(position).getLink());
playbackServiceIntent
.putExtra("position", position);
startService(playbackServiceIntent);
break;
There are different methods to realize it.
Using LocalBroadcastManager
Using an application to track the status of your service, i.e Song name, length, ...
Using SharedPreferences
IMHO, I think using a LocalBroadcastManager is more cleaner.
- Send a broadcast message to the service
- When the service receives the message, let it broadcast its status.

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");
}
}
});
}

integrate yahoo messenger with android app

i surfed net to find some code snippet or some help to integrate yahoo messenger in android application. i could not find some thing helpful.
Please Help me by providing some link, tutorial or code sample so that i could integrate the yahoo messenger.
Thanks
Finally got solution for yahoo messenger integration i used openymsg a library and using below link
http://edwin.baculsoft.com/2011/11/creating-a-simple-yahoo-messenger-auto-response-with-java-and-openymsg-library/
changed my code in activity as below worked like a charm :)
public class SimpleYahoo extends Activity implements SessionListener{
/** Called when the activity is first created. */
private Logger logger = Logger.getAnonymousLogger();
private Session session = new Session();
Button sendButton;
boolean isLoginsuccess;
ListView resultTextView;
EditText editText;
Handler handler;
ArrayList<String> replymessage;
String reply;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
replymessage=new ArrayList<String>();
try {
session.login("yahooid", "password");
} catch (AccountLockedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (LoginRefusedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (FailedLoginException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
session.addSessionListener(this);
sendButton=(Button) findViewById(R.id.button);
resultTextView=(ListView) findViewById(R.id.result);
editText=(EditText) findViewById(R.id.input);
sendButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
doLogin();
}
});
handler=new Handler()
{
#Override
public void handleMessage(Message msg) {
// TODO Auto-generated method stub
super.handleMessage(msg);
if(msg.what==0)
{
replymessage.add(reply);
setListAdapter();
}
}
};
}
private void doLogin() {
try {
// insert your yahoo id
// as for this example, im using my yahoo ID "dombaganas"
session.sendMessage("targetyahooid", editText.getText().toString());
} catch (Exception e) {
Log.e(e.getMessage(), e.getMessage());
}
}
#Override
public void dispatch(FireEvent fe) {
// TODO Auto-generated method stub
ServiceType type = fe.getType();
SessionEvent sessionEvent = fe.getEvent();
if (type == ServiceType.MESSAGE) {
try {
// log request message
reply=sessionEvent.getMessage();
Log.i("message","message from " + sessionEvent.getFrom() + " \nmessage " + sessionEvent.getMessage() );
// give an automatic response
// session.sendMessage(sessionEvent.getFrom(), "hi, you are sending " + sessionEvent.getMessage());
// session.
handler.sendEmptyMessage(0);
} catch (Exception e) {
Log.e(e.getMessage(), e.getMessage());
}
}
}
public void setListAdapter()
{
ArrayAdapter<String> arrayAdapter=new ArrayAdapter<String>(this,R.layout.multi_line_list_item,replymessage);
resultTextView.setAdapter(arrayAdapter);
resultTextView.setSelection(replymessage.size()-1);
}
}

Categories

Resources