Show ProgressDialog for Radio streaming Service? - android

I have made an app for radio streaming here is the code:
public class streamService extends Service {
public static MediaPlayer stream;
public static String url;
public static int serviceAvailable;
private static final int HELLO_ID = 1;
public static NotificationManager mNotificationManager;
public static PowerManager.WakeLock wl;
public static Boolean bgPlay = false;
TelephonyManager tm;
ProgressDialog pDialog;
public static String Tag="";
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
pDialog=new ProgressDialog(RadioList.con);
pDialog.setTitle("Please wait!!");
pDialog.setMessage("Connecting");
pDialog.setCancelable(false);
pDialog.show();
}
public void onStart(Intent intent, int startid) {
// Restore preferences
Tag=RadioList.Tag;
//RadioStationThree.pDialog.show();
stream = new MediaPlayer();
try {
stream.setDataSource(RadioList.URL);
} catch (IllegalArgumentException 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();
}
stream.setAudioStreamType(AudioManager.STREAM_MUSIC);
stream.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
public void onPrepared(MediaPlayer stream) {
/* tm = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
tm.listen(mPhoneListener, PhoneStateListener.LISTEN_CALL_STATE);
makeNotification();
*/ // Set the Wake Lock - CPU on, keyboard and screen off
/*PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wl = pm.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK,
getString(R.string.app_name));
wl.acquire();*/
serviceAvailable = 1;
System.out.println("HERE CANCEL");
pDialog.cancel();
stream.start();
}
});
try {
stream.prepare();
} catch (IllegalStateException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
}
#Override
public void onDestroy() {
// kill the stream
serviceAvailable = 0;
stream.stop();
stream.release();
stream = null;
// kill the status notification
}
This service is started at click of a button in activity But as I click on the button the app stops working for a while and then continue normal(Sometimes ANR is also shown). I also used ProgressDialog but it also stop spinning and ANR is shown .What could be the possible solution for this? Please Help?

Thanks to "StinePike" It was simple using the code in new thread it worked all fine!

Related

cannot play the selected music after clicking the "ok" button of Mediastore

In this app, it can play the default music well, but when I try to use MediaStore to select another music to play, something wrong here. In the page of mediastore, it can play the selected music well, but when I click the "ok" button to confirm my choice, it cannot play the music anymore. I do not know why this happened and I am very glad to have your help!
The following is the code
public class MUSIC extends AppCompatActivity implements SensorEventListener,MediaPlayer.OnPreparedListener,GoogleApiClient.ConnectionCallbacks,GoogleApiClient.OnConnectionFailedListener,LocationListener {
private Button JoggingButton,BikingButton;
private SensorManager mSensormanager;
private Sensor accelerometer;
private final float NOISE = (float) 2.0;
private boolean initialization;
private float mLastX, mLastY, mLastZ;
private static final String TAG = "sensor";
private MediaPlayer mediaPlayer1;
private MediaPlayer mediaPlayer2;
private double measurement;
private double speed;
private boolean jogging=false,biking=false;
private Uri urijogging,uribiking;
private LocationManager locationManager;
private GoogleApiClient googleApiClient;
private LocationRequest locationRequest;
private final static int MY_PERMISSION_REQUEST_FINE=100;
private final static int CONNECTION_FAILURE_RESOLUTION_REQUEST=9000;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_music);
mediaPlayer1 = new MediaPlayer();
mediaPlayer2 = new MediaPlayer();
JoggingButton=(Button)findViewById(R.id.button3);
BikingButton=(Button)findViewById(R.id.button4);
if(accelerometer!=null){
if(urijogging==null){
Prepareplay(mediaPlayer1,Uri.parse("android.resource://"+getPackageName()+ "/raw/jogging1"));
}else{
Prepareplay(mediaPlayer1,urijogging);
}
if(uribiking==null){
Prepareplay(mediaPlayer2,Uri.parse("android.resource://"+getPackageName()+ "/raw/biking1"));
}else{
Prepareplay(mediaPlayer2,uribiking);
}
mediaPlayer1.start();
mediaPlayer2.start();
JoggingButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mediaPlayer1.release();
mediaPlayer1=new MediaPlayer();
Intent intent=new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 10);
}
});
BikingButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
mediaPlayer2.release();
mediaPlayer2=new MediaPlayer();
Intent intent=new Intent(Intent.ACTION_PICK, android.provider.MediaStore.Audio.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(intent, 11);
}
});
Toast.makeText(getApplicationContext(), "Current speed:"+String.valueOf(speed),Toast.LENGTH_LONG).show();
}else{
Toast.makeText(getApplicationContext(),"Sorry,there are no accelerometers on your device",Toast.LENGTH_LONG).show();
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if(resultCode == RESULT_OK && requestCode == 10){
urijogging=data.getData();
Toast.makeText(getApplicationContext(),String.valueOf(urijogging),Toast.LENGTH_LONG).show();
Joggingplay(this,urijogging);
}
if(resultCode == RESULT_OK && requestCode == 11){
uribiking=data.getData();
Toast.makeText(getApplicationContext(),String.valueOf(uribiking),Toast.LENGTH_LONG).show();
Bikingplay(this,uribiking);
}
}
private void Joggingplay(Context context, Uri uri) {
try {
mediaPlayer1.setDataSource(context, uri);
mediaPlayer1.setOnPreparedListener(this);
mediaPlayer1.prepareAsync();
onPrepared(mediaPlayer1);
mediaPlayer1.start();
} 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) {
e.printStackTrace();
}
}
private void Bikingplay(Context context, Uri uri) {
try {
mediaPlayer2.setDataSource(context, uri);
mediaPlayer2.setOnPreparedListener(this);
mediaPlayer2.prepareAsync();
onPrepared(mediaPlayer2);
mediaPlayer2.start();
} 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) {
e.printStackTrace();
}
}
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
mediaPlayer.start();
mediaPlayer.pause();
}
public void Prepareplay(MediaPlayer player, Uri uri){
player.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
player.setDataSource(getApplicationContext(), uri);
} catch (IOException e) {
e.printStackTrace();
}
try {
player.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
}
The following is the logcat
05-16 16:42:04.243 14390-14390/com.example.a12086.app_sensor E/MediaPlayer: pause called in state 1, mPlayer(0x0)
05-16 16:42:04.244 14390-14390/com.example.a12086.app_sensor E/MediaPlayer: error (-38, 0)
I searched this problem online, and I already used mediaPlayer.prepareAsync() and onPrepared(mediaPlayer), but it still do not work. And the selected music can only be played on the MediaStore page, I am confused about that...
try to Use: mdiaPlayer.reset();
mdiaPlayer.prepare();
mdiaPlayer.start(); instead of
mediaPlayer.setOnPreparedListener(this);
mediaPlayer.prepareAsync();
onPrepared(mediaPlayer);
mediaPlayer.start();

AudioRecorder App crashes when I record a second time

My app breaks down when I attempt to record a second a time when I hit the stop button. I went through this code several times. I can't find the problem. I'm not sure if its my MediaRecorder or my MediaPlayer. It works the first time around. But not the second time. can anyone find the problem.
public class PatientName extends Activity implements OnClickListener {
private Button instructionsBtn;
private ImageView record;
private ImageView stop;
private MediaPlayer instructions;
private MediaPlayer namePlayer;
private MediaRecorder nameRecorder;
private String OUTPUT_FILE;
private Button play;
private Button accept;
private LinearLayout review;
private Button delete;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.patient_name);
OUTPUT_FILE = Environment.getExternalStorageDirectory() + "/namerecording.3gpp";
initializeViews();
initializeListeners();
}
public void initializeViews() {
instructionsBtn = (Button)findViewById(R.id.patient_name_instructions);
record = (ImageView)findViewById(R.id.record_name);
stop = (ImageView)findViewById(R.id.stop_name);
stop.setVisibility(View.GONE);
play = (Button)findViewById(R.id.play_name);
play.setVisibility(View.GONE);
review = (LinearLayout)findViewById(R.id.review_name);
delete = (Button)findViewById(R.id.delete_name);
accept = (Button)findViewById(R.id.accept_name);
review.setVisibility(View.GONE);
}
public void initializeListeners() {
instructionsBtn.setOnClickListener(this);
record.setOnClickListener(this);
stop.setOnClickListener(this);
play.setOnClickListener(this);
delete.setOnClickListener(this);
accept.setOnClickListener(this);
}
#Override
public void onBackPressed() {
}
public void playInstructions() {
setMaxVolume();
instructions = MediaPlayer.create(PatientName.this, R.raw.intro_instructions);
instructions.start();
instructions.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer play) {
instructions.release();
instructionsBtn.setEnabled(true);
}
});
}
public void setMaxVolume() {
AudioManager audio = (AudioManager) getSystemService(this.AUDIO_SERVICE);
int maxVolume = audio.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
audio.setStreamVolume(AudioManager.STREAM_MUSIC, maxVolume, 0);
}
public void onClick(View v) {
int id = v.getId();
if (id==R.id.patient_name_instructions) {
instructionsBtn.setEnabled(false);
playInstructions();
}
if (id==R.id.record_name) {
beginRecording();
}
if (id==R.id.stop_name){
play.setVisibility(View.VISIBLE);
nameRecorder.stop();
}
if (id==R.id.play_name) {
playbackRecording();
}
if (id==R.id.delete_name){
deleteRecording();
}
if (id==R.id.accept_name) {
saveAndContinue();
}
}
private void beginRecording(){
record.setVisibility(View.GONE);
stop.setVisibility(View.VISIBLE);
File outFile = new File(OUTPUT_FILE);
if (outFile.exists()) {
outFile.delete();
}else {
nameRecorder = new MediaRecorder();
nameRecorder.setAudioSource(MediaRecorder.AudioSource.MIC);
nameRecorder.setOutputFormat(MediaRecorder.OutputFormat.THREE_GPP);
nameRecorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_WB);
nameRecorder.setOutputFile(OUTPUT_FILE);
try {
nameRecorder.prepare();
} catch (IllegalStateException e) {
Toast toast = Toast.makeText(this,"Illegal State",Toast.LENGTH_LONG);
toast.show();
e.printStackTrace();
} catch (IOException e) {
Toast toast = Toast.makeText(this,"Error Recording",Toast.LENGTH_LONG);
toast.show();
e.printStackTrace();
}
nameRecorder.start();
}
}
private void playbackRecording() {
play.setVisibility(View.GONE);
namePlayer = new MediaPlayer();
try {
namePlayer.setDataSource(OUTPUT_FILE);
} 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 {
namePlayer.prepare();
} catch (IllegalStateException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
namePlayer.start();
namePlayer.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer play) {
namePlayer.release();
nameRecorder.release();
review.setVisibility(View.VISIBLE);
}
});
}
private void deleteRecording() {
Intent i = getBaseContext().getPackageManager().getLaunchIntentForPackage( getBaseContext().getPackageName() );
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(i);
}
private void saveAndContinue() {
Intent intent = new Intent(PatientName.this, PatientLocation.class);
startActivity(intent);
}
}
Here is my logCat:
I figured out the issue. In the beginRecording method, I have an if and else statement that handles the output file. Unfortunately, the code that I had in the else statement was something that I wanted to always run no matter what.

Android, will the socket close in service when activity destroy?

service code :
public class AlarmListeningService extends Service{
public static final String sHost = "*.*.*.*";
public static final int sPort = 5566;
Thread thrSocket;
#SuppressWarnings("deprecation")
public void onStartCommand(Intent intent, int startId) {
super.onStartCommand(intent, startId, startId);
thrSocket = new thrSocket();
thrSocket.start();
}
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
class thrSocket extends Thread {
Socket mSocket;
public void run() {
InitSocket();
new Thread(){
public void run() {
try {
String msg = "";
while (true) {
int count = 0;
while (count == 0) {
count=ips.available();
}
byte[] serverdata = new byte[count];
ips.read(serverdata);
}
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}.start();
}
private void InitSocket(){
try {
mSocket = new Socket(sHost,sPort);
OutputStream out=mSocket.getOutputStream();
byte[] b_client = "client".getBytes(Charset.forName("UTF-8"));
out.write(b_client);
} catch (UnknownHostException e) {
// TODO Auto-generated catch block
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
}
Activity code:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
Intent startAL = new Intent();
startAL.setClass(MainActivity.this, AlarmListeningService.class);
startService(startAL);
}
My question is will the socket in service close when I destroy the activity
(Observation at socket server)?
And the socket will re-connection in seconds to tens of seconds (Observation at socket server too)
How could I let the socket not close when I destroy the activity?

Android handling state of ProgressBar onPause/onResume

Hi have a progressBar that i run. but when the user exits the app via the home button and then re-enters it by holding down the home button and selected the app. The progressBar setProgress flickers between an old value and a new one almost as if its remembering the previous state. I have created a function in my on pause/onResume methods to pause the timer save the values and on resume get those values and start the timer and progress bar again. The confusing thing is it works the onPause stuff works perfectly if the onPause function is run and the user stays in the app for example presses the back button. Does anyone know where im going wrong or how to correctly implement a progressBar using a CountDownTimer?
heres my code
#Override
protected void onResume() {
// TODO Auto-generated method stub
Log.v("Game","ONRESUME");
loadData();
layoutChecks();
loadViews();
try {
if(!myData.get("completed").equals("3")){
hintCheck();
getHints();
startTimer();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onResume();
}
#Override
protected void onPause() {
Log.v("Game","ONPAUSE");
try {
if(!myData.get("completed").equals("3")){
pauseTimer();
updateData();
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
super.onPause();
}
public void loadViews(){
progressBar = new ProgressBar(this);
progressBar = (ProgressBar) findViewById(R.id.progressBar);
progressD = progressBar.getProgressDrawable();
}
public void prepareProgressBar(){
progressD.setLevel(0);
progressBar.setProgress(0);
progressD.setLevel(points*100);
progressBar.setProgress(points);
}
public void startTimer(){
try {
points = Integer.valueOf(myData.getJSONObject("Data").getString("points"));
int timer = points;
hasTimerCancelled = false;
prepareProgressBar();
counter = new MyCount(timer/2 * 1000,1000);
counter.start();
} catch (NumberFormatException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (JSONException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
}
public void pauseTimer(){
try {
counter.cancel();
hasTimerCancelled = true;
JSONObject Data = myData.getJSONObject("Data");
Data.put("points", String.valueOf(points));
myData.put("Data", Data);
updateData();
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public class MyCount extends CountDownTimer{
public long totaltime;
public MyCount(long totalTime, long countDownInterval) {
super(totalTime, countDownInterval);
totaltime = totalTime;
}
#Override
public void onFinish() {
counter.cancel();
points = 0;
progressBar.setProgress(0);
}
#Override
public void onTick(long millisUntilFinished) {
if(!hasTimerCancelled){
if(points > 0){
points = points - 1;
}
progressBar.setProgress((int) totaltime);
}
}
}

Android: Starting a service to play radio channels

I am trying to make a service that plays in background which is unbounded. I have walked myself through some of the example codes on the internet but I can't get my application to play the radio when I'm calling the service class.
Please have a look at the code and tell me where I am going wrong... When I call MyService class from ArmanFMRadio onClick It toasts "My Service Created" & "My Service Started" but doesnt get to play the audio for the radio stream link. I've checked it otherwise and the link seems fine, so problem lies somewhere in the code to my understanding:
package com.etc.etcc;
public class ArmanFMRadio extends Activity implements OnClickListener {
private ProgressBar playSeekBar;
private Button buttonPlay;
private Button buttonStopPlay;
private MediaPlayer player;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.armanfm);
initializeUIElements();
//initializeMediaPlayer();
}
private void initializeUIElements() {
playSeekBar = (ProgressBar) findViewById(R.id.progressBar1);
playSeekBar.setMax(100);
playSeekBar.setVisibility(View.INVISIBLE);
buttonPlay = (Button) findViewById(R.id.buttonPlay);
buttonPlay.setOnClickListener(this);
buttonStopPlay = (Button) findViewById(R.id.buttonStopPlay);
buttonStopPlay.setEnabled(false);
buttonStopPlay.setOnClickListener(this);
}
private void initializeMediaPlayer() {
player = new MediaPlayer();
try {
player.setDataSource("http://50.117.26.26:3953/Live");
} 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();
}
player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
public void onBufferingUpdate(MediaPlayer mp, int percent) {
playSeekBar.setVisibility(View.VISIBLE);
playSeekBar.setSecondaryProgress(percent);
Log.i("Buffering", "" + percent);
}
});
}
public void onClick(View v) {
switch(v.getId()){
case R.id.buttonPlay:
playSeekBar.setVisibility(View.VISIBLE);
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
startService(new Intent(this, MyService.class));
//startPlaying();
break;
case R.id.buttonStopPlay:
stopPlaying();
break;
}
}
private void startPlaying() {
buttonStopPlay.setEnabled(true);
buttonPlay.setEnabled(false);
playSeekBar.setVisibility(View.VISIBLE);
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
}
private void stopPlaying() {
if (player.isPlaying()) {
player.stop();
player.release();
initializeMediaPlayer();
}
buttonPlay.setEnabled(true);
buttonStopPlay.setEnabled(false);
playSeekBar.setVisibility(View.INVISIBLE);
}
#Override
protected void onPause() {
super.onPause();
if (player.isPlaying()) {
player.stop();
}
}
}
Just look at onClick on the above code, because this class works fine to my thinking.
MyService class:
package com.etc.etcc;
public class MyService extends Service {
private static final String TAG = "MyService";
private MediaPlayer player;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
#Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
#Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
player = new MediaPlayer();
try {
player.setDataSource("http://50.117.26.26:3953/Live");
} 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();
}
player.prepareAsync();
player.setOnPreparedListener(new OnPreparedListener() {
public void onPrepared(MediaPlayer mp) {
player.start();
}
});
}
}
onStart is deprecated method. you should use onStartCommand method.
Debug your code and check weather there is any Exception or something
Also you are using the service so possible that you service will call twice in that case your onStartCommand method will be called twice so there you will have to check the startId which you will get as a parameter. If startId > 1 that means previously your service is started so you can stop media player and again start a media player with latest source or you can just ignore the second request.
If you are not confidence with service you can put your code in the activity and check weather your code is working fine or not after that you can replace this code in the service.

Categories

Resources