Android: Back click exists from app when using YouTube API - java

I am using Youtube API for android. Below is the code
MainActivity.java
public class MainActivity extends AppCompatActivity implements YouTubePlayer.OnInitializedListener {
private static final int RECOVERY_REQUEST = 1;
private YouTubePlayerView youTubeView;
private YouTubePlayerFragment youTubePlayerFragment;
private YouTubePlayer player;
private boolean isFullScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
// youTubeView.initialize(Config.YOUTUBE_API_KEY, this);
youTubePlayerFragment = (YouTubePlayerFragment) getFragmentManager()
.findFragmentById(R.id.youtube_fragment);
youTubePlayerFragment.initialize(Config.YOUTUBE_API_KEY, this);
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
this.player = player;
this.player.cueVideo("fhWaJi1Hsfo"); // Plays https://www.youtube.com/watch?v=fhWaJi1Hsfo
// player.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
player.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
#Override
public void onFullscreen(boolean b) {
isFullScreen = true;
}
});
}
}
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_REQUEST).show();
} else {
String error = String.format(getString(R.string.player_error), errorReason.toString());
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(Config.YOUTUBE_API_KEY, this);
}
}
protected Provider getYouTubePlayerProvider() {
return youTubeView;
}
#Override
public void onBackPressed() {
Toast.makeText(this,"Back pressed",Toast.LENGTH_LONG).show();
if(isFullScreen)
{
player.setFullscreen(false);
}
else
{
super.onBackPressed();
}
}
}
activity_main.xml
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<!--<com.google.android.youtube.player.YouTubePlayerView-->
<!--android:id="#+id/youtube_view"-->
<!--android:layout_width="match_parent"-->
<!--android:layout_height="wrap_content"/>-->
<fragment
android:id="#+id/youtube_fragment"
android:name="com.google.android.youtube.player.YouTubePlayerFragment"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
</RelativeLayout>
When the Full Screen is visible and if the user clicked back, I want my Activity to be displayed. Instead what is happening now is the back button exists from the app.
How can I fix this?
UPDATE
I Identified the error, inside the setOnFullScreenListener it was never identified the app is in Full screen, even though it is. I tried forcing the boolean into true, but it ended up crashing saying the player is null

I'm not sure but in your onFullScreen() override method, you have set
isFullScreen = true;
Rather, use
isFullScreen = b;
Hope this helps.

I found the answer, just remove the if condition in onInitializationSuccess. Below is the code.
public class MainActivity extends AppCompatActivity implements YouTubePlayer.OnInitializedListener {
private static final int RECOVERY_REQUEST = 1;
private YouTubePlayerView youTubeView;
private YouTubePlayerFragment youTubePlayerFragment;
private YouTubePlayer player;
private boolean isFullScreen;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
// youTubeView.initialize(Config.YOUTUBE_API_KEY, this);
youTubePlayerFragment = (YouTubePlayerFragment) getFragmentManager()
.findFragmentById(R.id.youtube_fragment);
youTubePlayerFragment.initialize(Config.YOUTUBE_API_KEY, this);
}
#Override
public void onInitializationSuccess(Provider provider, YouTubePlayer player, boolean wasRestored) {
this.player = player;
this.player.cueVideo("fhWaJi1Hsfo"); // Plays https://www.youtube.com/watch?v=fhWaJi1Hsfo
// player.setPlayerStyle(YouTubePlayer.PlayerStyle.CHROMELESS);
this.player.setOnFullscreenListener(new YouTubePlayer.OnFullscreenListener() {
#Override
public void onFullscreen(boolean b) {
isFullScreen = b;
}
});
}
#Override
public void onInitializationFailure(Provider provider, YouTubeInitializationResult errorReason) {
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_REQUEST).show();
} else {
String error = String.format(getString(R.string.player_error), errorReason.toString());
Toast.makeText(this, error, Toast.LENGTH_LONG).show();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(Config.YOUTUBE_API_KEY, this);
}
}
protected Provider getYouTubePlayerProvider() {
return youTubeView;
}
#Override
public void onBackPressed() {
if(isFullScreen)
{
Toast.makeText(this,"Full Screen",Toast.LENGTH_LONG).show();
player.setFullscreen(false);
}
else
{
Toast.makeText(this,"Not Full Screen",Toast.LENGTH_LONG).show();
super.onBackPressed();
}
}
}

Related

How can i reload youtube video in mainactivity?

I have been working on an android project. My project has a YoutubePlayer api. The video of EditText's video is taken and the video is shown. the following code works. But when I enter another id in the EditTex, the previous video is not replaced. The previous one looks the same. How can I fix this?
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//find views by ID
youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
urlText = (EditText) findViewById(R.id.url);
btnGo = (View) findViewById(R.id.btn_go);
btnGo.setOnClickListener(onClickListener());
}
private YouTubePlayer.OnInitializedListener onInitialization() {
return new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
if (!wasRestored) {
// loadVideo() will auto play video
// Use cueVideo() method, if you don't want to play it automatically
youTubePlayer.loadVideo(urlText.getText().toString().trim());
// Showing player controls with default mode
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.DEFAULT);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
Toast.makeText(getApplicationContext(),
"onInitializationFailure()",
Toast.LENGTH_SHORT).show();
}
};
}
private View.OnClickListener onClickListener() {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
// Initializing video player with developer key
youTubeView.initialize(API_KEY, onInitialization());
}
};
}
Don't call initialize() again - once you get your success callback, retain a reference to the YouTubePlayer and use that to load subsequent videos:
private YouTubePlayer player = null;
//...
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//find views by ID
youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
urlText = (EditText) findViewById(R.id.url);
btnGo = (View) findViewById(R.id.btn_go);
btnGo.setOnClickListener(onClickListener());
}
private YouTubePlayer.OnInitializedListener onInitialization() {
return new YouTubePlayer.OnInitializedListener() {
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean wasRestored) {
if (!wasRestored) {
//Keep doing what you're doing, and when finished...
this.player = youTubePlayer;
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
//...
}
};
}
private View.OnClickListener onClickListener() {
return new View.OnClickListener() {
#Override
public void onClick(View v) {
if(player == null) {
youTubeView.initialize(API_KEY, onInitialization());
} else {
player.loadVideo(urlText.getText().toString().trim());
player.play();
}
}
};

mediaplayer starts a new instance when i return to the app

Im making a simple radio streaming app. Everything works great but having a few buggy issues.
When i press the home screen of my device i want the radio to carry on playing. which it does, But as soon as i go to my app history and re-open the app. It starts a new session. this make for a very Un-Pleasurble piece of music lol.
The app is very simple in the way it works i have a media player and a media controller which is attached to a surfaceView in my xml.
Can some one please tell me the correct way to fix this issue as this is the first time making an app that contains a live stream.
Thanks as always guys
my code for the media player and controller
public class radiostation extends AppCompatActivity implements SurfaceHolder.Callback, MediaPlayer.OnPreparedListener,
MediaController.MediaPlayerControl {
private SurfaceView surfaceView;
private SurfaceHolder surfaceHolder;
private MediaPlayer mediaPlayer;
private MediaController mediaController;
private Handler handler = new Handler();
String videoSource =
"my radio station source address";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_radiostation);
surfaceView = (SurfaceView)findViewById(R.id.surface);
surfaceHolder = surfaceView.getHolder();
surfaceHolder.addCallback(this);
surfaceView.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(mediaController != null){
mediaController.show();
}
return false;
}
});
}
#Override
public void surfaceCreated(SurfaceHolder holder) {
Toast.makeText(radiostation.this,
"Media Controls active lets mash it up", Toast.LENGTH_LONG).show();
mediaPlayer = new MediaPlayer();
mediaPlayer.setDisplay(surfaceHolder);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
mediaPlayer.setOnPreparedListener(this);
try {
mediaPlayer.setDataSource(videoSource);
mediaPlayer.prepare();
mediaController = new MediaController(this);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(radiostation.this,
"Radio Station off Air or no internet connection!\n" + e.toString(),
Toast.LENGTH_LONG).show();
}
}
#Override
public void surfaceChanged(SurfaceHolder holder,
int format, int width, int height) {
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
}
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
Toast.makeText(radiostation.this,
"You are now connected ", Toast.LENGTH_LONG).show();
mediaController.setMediaPlayer(this);
mediaController.setAnchorView(surfaceView);
handler.post(new Runnable() {
public void run() {
mediaController.setEnabled(true);
mediaController.show();
}
});
}
#Override
public void start() {
mediaPlayer.start();
}
#Override
public void pause() {
mediaPlayer.pause();
}
#Override
public int getDuration() {
return mediaPlayer.getDuration();
}
#Override
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
#Override
public void seekTo(int pos) {
mediaPlayer.seekTo(pos);
}
#Override
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return false;
}
#Override
public boolean canSeekForward() {
return false;
}
#Override
public int getAudioSessionId() {
return mediaPlayer.getAudioSessionId();
}
#Override
public void onBackPressed() {
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer=null;
finish();
}

Play a YouTube Video in Your android app

hello there i have created an app for playing Youtube videos i works fine but i want when i click on next button the next videos plays. how i will create an array for it which contain the youtube videos link. i m new to Android programming plz help.
public class TutorialsActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener {
public static final String DEVELOPER_KEY = "AIzaSyAIeerJ_5ClQHLtIpXtk5DH2S4mZ9lwGKs";
private static final String VIDEO_ID = "eQW4R5gLlUk";
private static final String VIDEO_ID1 = "H2c_x4YWx7I";
private static final int RECOVERY_DIALOG_REQUEST = 1;
YouTubePlayerFragment myYouTubePlayerFragment;
Button btnNext;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tutorials);
myYouTubePlayerFragment = (YouTubePlayerFragment)getFragmentManager().findFragmentById(R.id.youtubeplayerfragment);
myYouTubePlayerFragment.initialize(DEVELOPER_KEY, this);
btnNext = (Button) findViewById(R.id.btnNext);
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, final YouTubePlayer player, boolean wasRestored) {
if (!wasRestored) {
player.cueVideo(VIDEO_ID);
}
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
player.cueVideo(VIDEO_ID1);
}
});
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Retry initialization if user performed a recovery action
getYouTubePlayerProvider().initialize(DEVELOPER_KEY, this);
}
}
protected YouTubePlayer.Provider getYouTubePlayerProvider() {
return (YouTubePlayerView)findViewById(R.id.youtubeplayerfragment);
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
}
just i shared my working source of your requirement.
SampleActivity.java
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import com.google.android.youtube.player.YouTubeBaseActivity;
import com.google.android.youtube.player.YouTubeInitializationResult;
import com.google.android.youtube.player.YouTubePlayer;
import com.google.android.youtube.player.YouTubePlayerView;
import java.util.ArrayList;
import www.ns7.tv.R;
import www.ns7.tv.controller.YoutubeManager;
public class SampleActivity extends YouTubeBaseActivity implements YouTubePlayer.OnInitializedListener, View.OnClickListener {
private static final String TAG = "YoutubeLiveTvActivity";
private Button mBtnNext;
private YouTubePlayerView mYouTubePlayerView = null;
private YouTubePlayer mLiveTvPlayer = null;
private ArrayList<String> mVideoIdList = new ArrayList<>();
private int mOffset = 0;
private String mCurrentVideoId;
#Override
protected void onCreate(Bundle bundle) {
super.onCreate(bundle);
setContentView(R.layout.sample);
mBtnNext = (Button) findViewById(R.id.btnNext);
mYouTubePlayerView = (YouTubePlayerView) findViewById(R.id.youtube_view);
mYouTubePlayerView.initialize(YoutubeManager.YOUTUBE_API_KEY, this);
mBtnNext.setOnClickListener(this);
updateVideoIdList();//add all video id in list
updateVideoId();//set current video id to mCurrentVideoId string
}
private void updateVideoId() {
if (mOffset >= mVideoIdList.size())
mOffset = 0;
mCurrentVideoId = mVideoIdList.get(mOffset);
}
private void updateVideoIdList() {
mVideoIdList.clear();
mVideoIdList.add("p0JcLbXfYXA");
mVideoIdList.add("63pKwVE4Uog");
mVideoIdList.add("QJXsurYoJ10");
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider, YouTubePlayer youTubePlayer, boolean b) {
try {
youTubePlayer.setPlayerStyle(YouTubePlayer.PlayerStyle.MINIMAL);
mLiveTvPlayer = youTubePlayer;
// mLiveTvPlayer.setOnFullscreenListener(YoutubeLiveTvActivity.this);
if (!b) {
mYouTubePlayerView.setVisibility(View.VISIBLE);
youTubePlayer.loadVideo(mCurrentVideoId);
}
} catch (Exception e) {
Log.e(TAG, " error : ", e);
}
}
#Override
protected void onResume() {
super.onResume();
if (mLiveTvPlayer == null) {
mYouTubePlayerView.initialize(YoutubeManager.YOUTUBE_API_KEY, this);
} else {
mLiveTvPlayer.loadVideo(mCurrentVideoId);
}
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider, YouTubeInitializationResult youTubeInitializationResult) {
}
#Override
protected void onDestroy() {
if (mLiveTvPlayer != null) {
mLiveTvPlayer.release();
}
if (mYouTubePlayerView != null) {
mYouTubePlayerView.removeAllViews();
}
super.onDestroy();
}
#Override
protected void onPause() {
super.onPause();
}
#Override
public void onClick(View view) {
switch (view.getId())
{
case R.id.btnNext:
{
mOffset++;// move the mOffset to next video id
updateVideoId();
mLiveTvPlayer.loadVideo(mCurrentVideoId);//load next video
}
break;
}
}
}
sample.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:background="#android:color/black"
>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/btnNext"
android:background="#android:color/black"
>
<com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:visibility="gone"
/>
</RelativeLayout>
<Button
android:id="#+id/btnNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:padding="10dp"
android:text="Next"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
/>
</RelativeLayout>
Above code youtube video play at 0 position when you click next button , next video will be play. if list last item reached then it will again move to 0 position.
Output :

Setting up MediaController

Im trying to set up the MediaController so I can have controls when playing back audio but when I try to declare it the "this" is coming up as an error. What am I doing wrong?
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
public class MainActivity extends AppCompatActivity implements MediaRecorder.OnInfoListener {
private boolean cont;
private MediaRecorder mediaRecorder;
private MediaPlayer mediaPlayer;
private String OUTPUT_FILE;
private MediaController mediaController;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
OUTPUT_FILE = Environment.getExternalStorageDirectory()+"/androidaudio1.3gpp";
cont=true;
}
public void buttonClicked(View view){
switch (view.getId()){
case R.id.startRec:
beginRecord();
break;
case R.id.stopRec:
stopRecord();
break;
case R.id.startPlay:
try {
begginPlaying();
} catch (IOException e) {
e.printStackTrace();
}
break;
case R.id.stopPlay:
stopPlaying();
break;
}
}
#TargetApi(Build.VERSION_CODES.LOLLIPOP)
private void begginPlaying() throws IOException {
if (mediaPlayer != null)
mediaPlayer.release();
mediaPlayer = new MediaPlayer();
mediaPlayer.setDataSource(OUTPUT_FILE);
mediaController = new MediaController(this);
mediaController.setMediaPlayer(this);
mediaController.show();
mediaPlayer.prepare();
mediaPlayer.start();
}
private void stopPlaying(){
if (mediaPlayer!= null){
mediaPlayer.stop();
mediaPlayer.reset();
mediaPlayer.release();
mediaPlayer=null;
}
#Override
public void start() {
mediaPlayer.start();
}
#Override
public void pause() {
mediaPlayer.pause();
}
#Override
public int getDuration() {
return mediaPlayer.getDuration();
}
#Override
public int getCurrentPosition() {
return mediaPlayer.getCurrentPosition();
}
#Override
public void seekTo(int pos) {
mediaPlayer.seekTo(pos);
}
#Override
public boolean isPlaying() {
return mediaPlayer.isPlaying();
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getAudioSessionId() {
return 0;
}
}
MediaController requires the context to be passed to the constructor. Without anymore code or knowing where you declared the MediaController, my best guess is that you don't have access to the context in the place where you declared the MediaController. Either pass the context from the activity where you would like to use the MediaController, or put this code in that activity.
https://developer.android.com/reference/android/widget/MediaController.html
EDIT:
I tried your code, check your imports & ensure you have, import android.widget.MediaController & not import android.media.session.MediaController.
Try this
if you are using in Activity then you can pass this
if you are using in Fragment then use getActivity() or context
and to set MediaController
use this code
video.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.setOnVideoSizeChangedListener(new OnVideoSizeChangedListener() {
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
/*
* add media controller
*/
mc = new MediaController(YourActivity.this);
video.setMediaController(mc);
/*
* and set its position on screen
*/
mc.setAnchorView(video);
}
});
}
});

Android Media Player App services

I am developing a media player app that has a bound service to an activity.It works fine when i press the home button or the app switcher and then come back to the app from the recent app, but as i press the back button the activity also ends the Music Service. Please guide me the exact steps that can solve these minor issues, so that i can give media controls to the app.My App has 2 main classes
MyActivity
AudioService
My code is given below.
AudioService.java
public class AudioService extends Service implements
MediaPlayer.OnPreparedListener, MediaPlayer.OnErrorListener,
MediaPlayer.OnCompletionListener{
// -----------------------------------------Attributes--------------------------------------------------------
private ArrayList<File> songs;
private ArrayList<File> audio;
private MediaPlayer player;
private int songPosn;
private String name="";
private final IBinder musicBind = new AudioBinder();
private Uri trackUri;
private int NOTIFY_ID=1;
// -----------------------------------------------------------------------------------------------------------
// !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
public void onCreate(){
//create the service
//create the service
super.onCreate();
//initialize position
songPosn=0;
//create player
player = new MediaPlayer();
initMusicPlayer();
}
// to initialize the media class
public void initMusicPlayer(){
//set player properties
player.setWakeMode(getApplicationContext(),
PowerManager.PARTIAL_WAKE_LOCK);
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
player.setOnPreparedListener(this);
player.setOnCompletionListener(this);
player.setOnErrorListener(this);
}
public void setList(ArrayList<File> theSongs){
songs=theSongs;
}
public void setSong(int songIndex){
songPosn=songIndex;
}
public class AudioBinder extends Binder {
AudioService getService() {
return AudioService.this;
}
}
#Override
public IBinder onBind(Intent intent) {
return musicBind;
}
#Override
public boolean onUnbind(Intent intent){
player.stop();
player.release();
return false;
}
#Override
public void onCompletion(MediaPlayer mp) {
}
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
mp.reset();
return false;
}
#Override
public void onPrepared(MediaPlayer mp) {
//start playback
mp.start();
showNotification();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId){
songPosn = intent.getIntExtra("pos",0);
audio=(ArrayList)intent.getParcelableArrayListExtra("songlist");
name = intent.getStringExtra("name");
Log.e("Service","name"+audio.get(0));
Log.e("Service","position "+songPosn);
return START_STICKY;
}
public void playSong(){
//play a song
player.reset();
Log.e("TRACH the URI",""+trackUri);
trackUri =Uri.parse(audio.get(songPosn).toString());
try{
player.setDataSource(getApplicationContext(), trackUri);
}
catch(Exception e){
Log.e("MUSIC SERVICE", "Error setting data source", e);
}
player.prepareAsync();
}
private void showNotification(){
Intent notIntent = new Intent(this, MyActivity.class);
notIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendInt = PendingIntent.getActivity(this, 0,
notIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder builder = new Notification.Builder(this);
builder.setContentIntent(pendInt)
.setTicker(name)
.setOngoing(true)
.setContentTitle("Playing")
.setContentText(name);
Notification not = builder.build();
startForeground(NOTIFY_ID, not);
}
#Override
public void onDestroy()
{
stopForeground(true);
}
}
MyActivity.java
public class MyActivity extends Activity {
// ***************************** Attributes Start ******************************************************
private ArrayList<File> myfiles= new ArrayList<File>();
private ListView listView;
private ArrayAdapter<String> adapter ;
private String name="";
private int position;
private AudioService musicSrv;
private Intent playIntent;
private boolean musicBound=false;
// ***************************** Attributes End ******************************************************
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
String toneslist[] ={"Airtel"
,"sherlock_theme"};
listView = (ListView) findViewById(R.id.listView);
adapter = new ArrayAdapter<String>(getApplication(),R.layout.list_item,R.id.list_textview,toneslist);
listView.setAdapter(adapter);
getMp3();
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int pos, long id) {
name =adapter.getItem(pos);
position =pos;
Log.e("MAINACTIVITY (clickListener) pos =",""+position+" name = "+name);
musicSrv.setSong(position);
musicSrv.playSong();
}
});
}
#Override
protected void onStart() {
super.onStart();
if(playIntent==null){
Log.e("MAINACTIVITY pos =",""+position+" name = "+name);
playIntent = new Intent(this, AudioService.class).putExtra("pos",position).putExtra("songlist", myfiles).putExtra("name", name);
bindService(playIntent, audioConnection, Context.BIND_AUTO_CREATE);
startService(playIntent);
}
}
private ServiceConnection audioConnection = new ServiceConnection() {
#Override
public void onServiceConnected(ComponentName name, IBinder service) {
AudioService.AudioBinder binder = (AudioService.AudioBinder)service;
musicSrv = binder.getService();
musicSrv.setList(myfiles);
musicBound = true;
}
#Override
public void onServiceDisconnected(ComponentName name) {
musicBound = false;
}
};
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
private void getMp3(){
String s=(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC)).toString();
// s="content://media/external/audio/media";
GetFiles(s);
}
private void GetFiles(String path) {
File file = new File(path);
File[] allfiles = file.listFiles();
if (allfiles.length == 0) {
} else {
for (int i = 0; i < allfiles.length; i++)
{
Log.e("FFFFFFFFF", allfiles[i].getName().toString());
myfiles.add(allfiles[i]);
}
}
}
#Override
protected void onPause() {
super.onPause();
}
#Override
protected void onDestroy() {
stopService(playIntent);
musicSrv=null;
super.onDestroy();
}
}
Try with this in your Activity:
#Override
public void onDestroy(){
if (!isChangingConfigurations()) stopService(new Intent (this, YourService.class));
super.onDestroy();
}
#Override
public void onBackPressed(){
if (mediaIsPlaying) moveTaskToBack(true);
else super.onBackPressed();
}

Categories

Resources