Welcome to the Java Programming Forums


The professional, friendly Java community. 21,500 members and growing!


The Java Programming Forums are a community of Java programmers from all around the World. Our members have a wide range of skills and they all have one thing in common: A passion to learn and code Java. We invite beginner Java programmers right through to Java professionals to post here and share your knowledge. Become a part of the community, help others, expand your knowledge of Java and enjoy talking with like minded people. Registration is quick and best of all free. We look forward to meeting you.


>> REGISTER NOW TO START POSTING


Members have full access to the forums. Advertisements are removed for registered users.

Results 1 to 4 of 4

Thread: android.telephony.PhoneStateListener - Start and Stop

  1. #1
    Junior Member
    Join Date
    May 2014
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default android.telephony.PhoneStateListener - Start and Stop

    The audio stream is stopping perfectly when a call comes in, however, I can't get the stream to resume when the call is ended. Any ideas"

    package com.radio.player;
     
    import java.io.IOException;
    import java.io.InputStream;
    import java.net.MalformedURLException;
    import java.net.URL;
    import java.util.Timer;
    import java.util.TimerTask;
     
    import org.jsoup.Jsoup;
    import org.jsoup.nodes.Document;
    import org.jsoup.select.Elements;
     
    import android.app.Activity;
    import android.app.AlertDialog;
    import android.app.NotificationManager;
    import android.app.PendingIntent;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.graphics.Typeface;
    import android.content.Context;
    import android.content.DialogInterface;
    import android.content.Intent;
    import android.database.ContentObserver;
    import android.view.KeyEvent;
    import android.media.AudioManager;
    import android.media.AudioTrack;
    import android.net.Uri;
    import android.os.AsyncTask;
    import android.os.Bundle;
    import android.os.Handler;
    import android.provider.Settings.System;
    import android.support.v4.app.NotificationCompat;
    import android.telephony.PhoneStateListener;
    import android.telephony.TelephonyManager;
    import android.util.Log;
    import android.view.Menu;
    import android.view.MenuItem;
    import android.view.View;
    import android.view.Window;
    import com.spoledge.aacdecoder.MultiPlayer;
    import com.spoledge.aacdecoder.PlayerCallback;
     
     
     
     
     
     
    import android.widget.Button;
    import android.widget.ImageView;
    import android.widget.ProgressBar;
    import android.widget.SeekBar;
    import android.widget.TextView;
    import com.radio.aacttplayer.data.information;
     
    import com.google.ads.AdRequest;
    import com.google.ads.InterstitialAd;
     
     
     
     
     
    /**
     * This is the main activity.
     */
    public class MainActivity extends Activity implements View.OnClickListener, PlayerCallback {
    	// Notification
    	private String artist = "";
    	private String track = "";
    	private Bitmap albumCover = null;
    	private static String lastfm_api_key = information.LastFm;
    	private InterstitialAd interstitial;
    	NotificationCompat.Builder NotiBld;
    	private static final int NOTIFY_ME_ID=12121;
    	private NotificationManager MiNotyr=null;
        private static final String LOG = "AACPlayerActivity";
        private History history;
        private SeekBar volControl;
        private Button btnPlay;
        private Button btnStop;
        private TextView txtStatus;
        private TextView txtMetaTitle;
        private TextView txtMetaGenre;
        private boolean wasPlayingBeforePhoneCall = false;
        private AudioManager VolUm;
        private TelephonyManager telephonyManager;
    	private ContentObserver mVolumeObserver;
        private ProgressBar progress;
        private Handler uiHandler;
        private String radioTitle = information.RadioName;
        private String StreamUrl = information.StreamURL;
        private String PublisherId = information.PublisherID;
        private MultiPlayer multiPlayer;
        private static final int AAC_BUFFER_CAPACITY_MS = 2500;
    	private static final int AAC_DECODER_CAPACITY_MS = 700;
    	private static boolean isExitMenuClicked;
    	TextView dj;
        ////////////////////////////////////////////////////////////////////////////
        // PlayerCallback
        ////////////////////////////////////////////////////////////////////////////
     
        private boolean playerStarted;
     
        public void playerStarted() {
            uiHandler.post( new Runnable() {
                public void run() {
                    btnPlay.setEnabled( false );
                    btnStop.setEnabled( true );
                    txtStatus.setText( R.string.text_buffering );
                    progress.setProgress( 0 );
                    progress.setVisibility( View.VISIBLE );
     
                    playerStarted = true;
                }
            });
        }
     
        public void playerPCMFeedBuffer( final boolean isPlaying,
                                         final int audioBufferSizeMs, final int audioBufferCapacityMs ) {
     
            uiHandler.post( new Runnable() {
                public void run() {
                    progress.setProgress( audioBufferSizeMs * progress.getMax() / audioBufferCapacityMs );
                    if (isPlaying) txtStatus.setText( R.string.text_playing );
                }
            });
        }
     
     
        public void playerStopped( final int perf ) {
            uiHandler.post( new Runnable() {
                public void run() {
                    btnPlay.setEnabled( true );
                    btnStop.setEnabled( false );
                    if(NotiBld!=null && MiNotyr!=null) {
     
    					NotiBld.setContentText("stopped").setWhen(0);
    					MiNotyr.notify(NOTIFY_ME_ID,NotiBld.build());
    				}
     
     
                    txtStatus.setText( R.string.text_stopped );
                    //txtStatus.setText( "" + perf + " %" );
                    progress.setVisibility( View.INVISIBLE );
     
                    playerStarted = false;
                }
            });
        }
     
     
        public void playerException( final Throwable t) {
            uiHandler.post( new Runnable() {
                public void run() {
                    new AlertDialog.Builder( MainActivity.this )
                        .setTitle( R.string.text_exception )
                        .setMessage(R.string.text_off )
                        .setNeutralButton( R.string.button_close,
                            new DialogInterface.OnClickListener() {
                                public void onClick( DialogInterface dialog, int id) {
                                    dialog.cancel();
                                }
                            }
                         )
                        .show();
     
                    txtStatus.setText( R.string.text_stopped );
     
                    if (playerStarted) playerStopped( 0 );
                }
            });
        }
     
     
        public void playerMetadata( final String key, final String value ) {
            TextView tv = null;
     
            if ("StreamTitle".equals( key ) || "icy-name".equals( key ) || "icy-description".equals( key )) {
     
     
            }
     
            else if ("icy-genre".equals( key )) {
     
     
            }
            else return;
     
     
     
            uiHandler.post( new Runnable() {
                public void run() {
                	Runnable runnable = new Runnable() {
                	    public void run () {
                	    	updateAlbum();
                	    }
                	};
                	Handler handler = new Handler();
                	handler.postDelayed(runnable, 3000);
     
     
     
                	artist = getArtistFromAAC(value);
    				track = getTrackFromAAC(value);
     
                	txtMetaTitle.setText(getTrackFromAAC(value));
                	txtMetaGenre.setText(getArtistFromAAC(value));
                    if(NotiBld!=null && MiNotyr!=null) {
     
    					NotiBld.setContentText("Now playing: "+value).setWhen(0);
    					MiNotyr.notify(NOTIFY_ME_ID,NotiBld.build());
    				}
                }
            });
        }
     
     
     
     
     
        private String getArtistFromAAC(String streamTitle) {
    		int end = streamTitle.indexOf("-");
    		if (end <= 0)
    			end = streamTitle.indexOf(":");
     
    		String title;
    		if (end > 0)
    			title = streamTitle.substring(0, end);
    		else
    			title = streamTitle;
    		return title.trim();
    	}
        private String getTrackFromAAC(String streamTitle) {
    		int start = streamTitle.indexOf("-") + 1;
    		if (start <= 0)
    			start = streamTitle.indexOf(":") + 1;
     
    		String track;
    		if (start > 0)
    			track = streamTitle.substring(start);
    		else
    			track = streamTitle;
     
    		int end = streamTitle.indexOf("(");
    		if (end > 0)
    			track = streamTitle.substring(start, end);
     
    		end = streamTitle.indexOf("[");
    		if (end > 0)
    			track = streamTitle.substring(start, end);
     
    		return track.trim();
    	}
     
     
        public void playerAudioTrackCreated( AudioTrack atrack ) {
        }
     
     
        ////////////////////////////////////////////////////////////////////////////
        // OnClickListener
        ////////////////////////////////////////////////////////////////////////////
     
        /**
         * Called when a view has been clicked.
         */
        public void onClick( View v ) {
            try {
                switch (v.getId()) {
                    case R.id.view_main_button_play: start(); break; 
                    case R.id.view_main_button_stop: stop(); break;
                }
            }
            catch (Exception e) {
                Log.e( LOG, "exc" , e );
            }
        }
     
     
        ////////////////////////////////////////////////////////////////////////////
        // Protected
        ////////////////////////////////////////////////////////////////////////////
     
        @Override
        protected void onCreate( Bundle savedInstanceState ) {
     
            super.onCreate( savedInstanceState );
            requestWindowFeature(Window.FEATURE_NO_TITLE);
     
            setContentView( R.layout.activity_main );
            Typeface font2 = Typeface.createFromAsset(getAssets(),
    				"ASansBlack.ttf");
    		dj = (TextView) findViewById(R.id.djname);
    		dj.setText(radioTitle);
    		dj.setTypeface(font2);
     
    		telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
    		if (telephonyManager != null) {
    			telephonyManager.listen(phoneStateListener,
    					PhoneStateListener.LISTEN_CALL_STATE);
    		}
     
    		interstitial = new InterstitialAd(this, PublisherId );
    		AdRequest adRequest = new AdRequest();
    		interstitial.loadAd(adRequest);
    		isExitMenuClicked = false;
     
     
            // get the instance of AudioManager class
     
     
      //volume start  
         // volume control
         		VolUm = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
     
         		int maxVolume = VolUm
         				.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
         		int curVolume = VolUm.getStreamVolume(AudioManager.STREAM_MUSIC);
         		volControl = (SeekBar) findViewById(R.id.volumebar);
         		volControl.setMax(maxVolume);
         		volControl.setProgress(curVolume);
         		volControl
         				.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
     
         					@Override
         					public void onStopTrackingTouch(SeekBar arg0) {
         					}
     
         					@Override
         					public void onStartTrackingTouch(SeekBar arg0) {
         					}
     
         					@Override
         					public void onProgressChanged(SeekBar a0, int a1,
         							boolean a2) {
         						VolUm.setStreamVolume(AudioManager.STREAM_MUSIC,
         								a1, 0);
         					}
         				});
     
         		Handler mHandler = new Handler();
         		// in onCreate put
         		mVolumeObserver = new ContentObserver(mHandler) {
         			@Override
         			public void onChange(boolean selfChange) {
         				super.onChange(selfChange);
         				if (volControl != null && VolUm != null) {
         					int volume = VolUm
         							.getStreamVolume(AudioManager.STREAM_MUSIC);
         					volControl.setProgress(volume);
         				}
         			}
     
         		};
         		this.getContentResolver()
         				.registerContentObserver(
         						System.getUriFor(System.VOLUME_SETTINGS[AudioManager.STREAM_MUSIC]),
         						false, mVolumeObserver);
    //volume
            btnPlay = (Button) findViewById( R.id.view_main_button_play );
            btnStop = (Button) findViewById( R.id.view_main_button_stop );
            txtStatus = (TextView) findViewById( R.id.view_main_text_status );
            txtMetaTitle = (TextView) findViewById( R.id.view_main_text_meta_title );
            txtMetaGenre = (TextView) findViewById( R.id.view_main_text_meta_genre );
            progress = (ProgressBar) findViewById( R.id.view_main_progress );
            btnPlay.setOnClickListener( this );
            btnStop.setOnClickListener( this );
     
            history = new History( this );
            history.read();
     
            if (history.size() == 0 ) {
     
            }
     
     
            uiHandler = new Handler();
     
            try {
                java.net.URL.setURLStreamHandlerFactory( new java.net.URLStreamHandlerFactory(){
                    public java.net.URLStreamHandler createURLStreamHandler( String protocol ) {
                        Log.d( LOG, "Asking for stream handler for protocol: '" + protocol + "'" );
                        if ("icy".equals( protocol )) return new com.spoledge.aacdecoder.IcyURLStreamHandler();
                        return null;
     
                    }
                });
            }
            catch (Throwable t) {
     
                Log.w( LOG, "Cannot set the ICY URLStreamHandler - maybe already set ? - " + t );
            }
        }
     
        @Override
    		public boolean onKeyDown(int keyCode, KeyEvent event) {
    			volControl = (SeekBar) findViewById(R.id.volumebar);
    			if (keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
    				int index = volControl.getProgress();
    				volControl.setProgress(index + 1);
    				return true;
    			} else if (keyCode == KeyEvent.KEYCODE_VOLUME_DOWN) {
    				int index = volControl.getProgress();
    				volControl.setProgress(index - 1);
    				return true;
    			}
     
    			return super.onKeyDown(keyCode, event);
    		}
     
     
        @Override
        public void onBackPressed(){
        	Log.d("CDA", "OnBackPressed Called");
        	Intent setIntent = new Intent(Intent.ACTION_MAIN);
        	setIntent.addCategory(Intent.CATEGORY_HOME);
        	setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        	startActivity(setIntent);
        }
     
        @Override
    	protected void onRestart() {
    		// TODO Auto-generated method stub
    		super.onRestart();
     
    		interstitial = new InterstitialAd(this, PublisherId);
    		AdRequest adRequest = new AdRequest();
    		interstitial.loadAd(adRequest);
     
        }
     
        @Override
    	protected void onStop() {
    		// TODO Auto-generated method stub
     
    		super.onStop();
     
    		interstitial = new InterstitialAd(this, PublisherId);
    		AdRequest adRequest = new AdRequest();
    		interstitial.loadAd(adRequest);
     
    	}
     
        @Override
    	protected void onStart() {
    		// TODO Auto-generated method stub
    		super.onStart();
    		interstitial = new InterstitialAd(this, PublisherId);
    		AdRequest adRequest = new AdRequest();
    		interstitial.loadAd(adRequest);
     
        }
     
    	public void salir(){
    		if (multiPlayer != null) {
                multiPlayer.stop();
                multiPlayer = null;
            }
     
     
    	}
     
    	public void showWall() {
     
    	      interstitial.show();
     
    	}
     
     
        @Override
        protected void onPause() {
            super.onPause();
            history.write();
            interstitial = new InterstitialAd(this, PublisherId);
    		AdRequest adRequest = new AdRequest();
    		interstitial.loadAd(adRequest);
        }
     
     
        @Override
        protected void onDestroy() {
            super.onDestroy();
            stop();
            interstitial = new InterstitialAd(this, PublisherId);
    		AdRequest adRequest = new AdRequest();
    		interstitial.loadAd(adRequest);
            if (telephonyManager != null) {
    			telephonyManager.listen(phoneStateListener,
    					PhoneStateListener.LISTEN_NONE);
    		}
        }
     
     
        ////////////////////////////////////////////////////////////////////////////
        // Private
        ////////////////////////////////////////////////////////////////////////////
     
        private void start() {
     
        	showNotification();
     
        	interstitial.show();
     
            // we cannot do it in playerStarted() - it is too late:
            txtMetaTitle.setText("");
            txtMetaGenre.setText("");
     
            multiPlayer = new MultiPlayer( this, AAC_BUFFER_CAPACITY_MS, AAC_DECODER_CAPACITY_MS);
            multiPlayer.playAsync(StreamUrl);
            //----  crear aqui el string para la radio
        }
     
     
        private void stop() {
        	albumCover = null;
    		ImageView logoimg = (ImageView) findViewById(R.id.logo);
    		logoimg.setImageBitmap(albumCover);
        	txtMetaTitle.setText("press play to listen");
            txtMetaGenre.setText("");
        	interstitial.show();
        	exitNotification();
     
            if (multiPlayer != null) {
                multiPlayer.stop();
                multiPlayer = null;
            }
        }
     
        public void stopOncall(){
        	 if (multiPlayer != null) {
                 multiPlayer.stop();
                 multiPlayer = null;
             }
     
     
     
        }
     
     
     
     
     
     
     
     
     
        PhoneStateListener phoneStateListener = new PhoneStateListener() {
    		@Override
    		public void onCallStateChanged(int state, String incomingNumber) {
    			if (state == TelephonyManager.CALL_STATE_RINGING) {
    				wasPlayingBeforePhoneCall = playerStarted = true;
    				stopOncall();
    			} else if (state == TelephonyManager.CALL_STATE_IDLE) {
    				if (wasPlayingBeforePhoneCall) {
     
    				}
    			} else if (state == TelephonyManager.CALL_STATE_OFFHOOK) {
    				// A call is dialing,
    				// active or on hold
    				wasPlayingBeforePhoneCall = playerStarted = true;
    				stopOncall();
    			}
    			super.onCallStateChanged(state, incomingNumber);
    		}
    	};
    	public void btnFacebook(View v) {
     
    		Intent next = new Intent(getApplicationContext(), FbActivity.class);
     
    		startActivity(next);
    	}	
     
     
    	public void btnTwitter(View v) {
     
    		Intent next = new Intent(getApplicationContext(), TwActivity.class);
     
    		startActivity(next);
    	}
     
    	public void btnChat(View v) {
     
    		Intent next = new Intent(getApplicationContext(), chatActivity.class);
     
    		startActivity(next);
    	}
     
    public void showNotification() {
     
     
    		NotiBld = new NotificationCompat.Builder(this)
     
    		.setSmallIcon(R.drawable.ic_launcher)
    		.setContentTitle(radioTitle)
    		.setContentText ("")
    		.setOngoing(true);
    		Intent intent = new Intent(this, MainActivity.class);
    		PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
     
    		NotiBld.setContentIntent(pIntent);
    		MiNotyr = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    		MiNotyr.notify(NOTIFY_ME_ID, NotiBld.build());
    	}
    public void exitNotification() {
    	clearNotification();
    	NotiBld = null;
    	MiNotyr = null;
    }
    public void clearNotification() {
    	if (MiNotyr != null)
    		MiNotyr.cancel(NOTIFY_ME_ID);
    }
     
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    	getMenuInflater().inflate(R.menu.main, menu);
    	return true;
    }
     
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
    	switch (item.getItemId()) {
    	case R.id.rating:
     
    		Intent intent = new Intent (Intent.ACTION_VIEW,Uri.parse(information.Goplay));
     
    		startActivity(intent);
     
     
    		return true;
     
     
    	case R.id.share:
    		Intent sharingIntent = new Intent(Intent.ACTION_SEND);
    		sharingIntent.setType("text/plain");
     
    		sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,"Listen your favorite music on");
    		sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT,information.Goplay);
    		startActivity(Intent.createChooser(sharingIntent, "Share via"));
     
    		return true;
     
    	case R.id.exit:
     
     
    		String message = "Are you sure want to exit?";
    		isExitMenuClicked = true;
     
    		AlertDialog.Builder ad = new AlertDialog.Builder(this);
    		ad.setTitle(radioTitle);
    		ad.setMessage(message);
    		ad.setCancelable(true);
    		ad.setPositiveButton("Yes",
    				new DialogInterface.OnClickListener() {
    					@Override
    					public void onClick(DialogInterface dialog, int which) {
     
    						if (multiPlayer != null) {
    							exitNotification();
    							multiPlayer.stop();
     
    							isExitMenuClicked = true;
    							finish();
    						}
    						else{
    							Intent setIntent = new Intent(Intent.ACTION_MAIN);
    					    	setIntent.addCategory(Intent.CATEGORY_HOME);
    					    	setIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    					    	startActivity(setIntent);
     
    						}
    					}
    				});
     
    		ad.setNegativeButton("No", null);
     
    		ad.show();
     
    		return true;
     
     
        }
        return super.onOptionsItemSelected(item);
     
     
    	}
     
     
     
    		public void updateAlbum() {
     
     
     
    			try {
    				String musicInfo[] = { artist, track};
     
    				if (!musicInfo[0].equals("") && !musicInfo[1].equals(""))
    					new LastFMCoverAsyncTask().execute(musicInfo);
    			} catch (Exception e) {
    				e.printStackTrace();
    			}
    		}
     
    		private class LastFMCoverAsyncTask extends
    				AsyncTask<String, Integer, Bitmap> {
     
    			@Override
    			protected Bitmap doInBackground(String... params) {
    				Bitmap bmp = null;
    				try {
    					bmp = LastFMCover.getCoverImageFromTrack(lastfm_api_key,
    							params[0], params[1]);
    				} catch (Exception e) {
    					e.printStackTrace();
    				}
     
    				return bmp;
    			}
     
    			@Override
    			protected void onPostExecute(Bitmap bmp) {
    				if (bmp != null){
    				albumCover = bmp;
    				ImageView logoimg = (ImageView) findViewById(R.id.logo);
    				logoimg.setImageBitmap(albumCover);}
     
    				else {
    			    albumCover = null;
    				ImageView logoimg = (ImageView) findViewById(R.id.logo);
    				logoimg.setImageBitmap(albumCover);}
     
     
     
    			}
     
     
    		}
     
    		public Bitmap getAlbumCover() {
    			return albumCover;
    		}
     
     
    		public void updatelogo() {
     
    			Bitmap albumlogo = getAlbumCover();
    			ImageView logoimg = (ImageView) findViewById(R.id.logo);
    			logoimg.setImageBitmap(albumlogo);
     
    		}
     
     
     
     
     
     
     
     
     
     
    }


  2. #2
    Forum VIP
    Join Date
    Jun 2011
    Posts
    394
    My Mood
    Busy
    Thanks
    49
    Thanked 112 Times in 95 Posts
    Blog Entries
    5

    Default Re: android.telephony.PhoneStateListener - Start and Stop

    You could use the PhoneStateListener to listen for when the call state goes from CALL_STATE_OFFHOOK to CALL_STATE_IDLE. I can see in your code an empty if statement (wasPlayingBeforePhoneCall) that looks like it should have the resume playback functionaility.

    Another option is to create a reciever intent and extend a BroadcastReciever. Details here.

  3. #3
    Junior Member
    Join Date
    May 2014
    Posts
    3
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Re: android.telephony.PhoneStateListener - Start and Stop

    Quote Originally Posted by ChristopherLowe View Post
    You could use the PhoneStateListener to listen for when the call state goes from CALL_STATE_OFFHOOK to CALL_STATE_IDLE. I can see in your code an empty if statement (wasPlayingBeforePhoneCall) that looks like it should have the resume playback functionaility.

    Another option is to create a reciever intent and extend a BroadcastReciever. Details here.
    The original resume playback functionality would not work right. I'll give your suggestion a try. Thank You!!

  4. #4
    Forum VIP
    Join Date
    Jun 2011
    Posts
    394
    My Mood
    Busy
    Thanks
    49
    Thanked 112 Times in 95 Posts
    Blog Entries
    5

    Default Re: android.telephony.PhoneStateListener - Start and Stop

    What do you mean by 'would not work right'? Did you stick a break point in that if statement to check if the logic was getting fired?

Similar Threads

  1. Replies: 1
    Last Post: May 4th, 2014, 04:04 AM
  2. Replies: 2
    Last Post: February 27th, 2014, 02:59 PM
  3. Replies: 1
    Last Post: February 26th, 2014, 05:45 PM
  4. How to start and stop GlassFish Application server using java code
    By aprabhat in forum What's Wrong With My Code?
    Replies: 0
    Last Post: December 26th, 2013, 06:49 AM
  5. JButton, adding a Listener to stop and start?
    By spunkyk014 in forum Object Oriented Programming
    Replies: 1
    Last Post: November 16th, 2012, 09:30 AM