Jump to content

[Problème]pourquoi mon appli se ferme soudainement ?


Recommended Posts

bonjour a tous,

voila je fait parti d'une webradio et j'aimerais créer une appli pour l'écouter (la webradio :P ) donc je débute avec eclipse.

voici le code du MainActivity.java:

import android.app.Activity;
import android.os.Bundle;
import java.io.IOException;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnBufferingUpdateListener;
import android.media.MediaPlayer.OnPreparedListener;
import android.util.Log;
import android.view.View;
import android.view.View.onclickListener;
import android.widget.Button;
import android.widget.ProgressBar;
public class MainActivity 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.activity_main);
 initializeUIElements();
 initializeMediaPlayer();
}
private void initializeUIElements() {

 buttonPlay = (Button) findViewById(R.id.buttonPlay);
 buttonPlay.setonclickListener(this);
 buttonstopPlay = (Button) findViewById(R.id.buttonstopPlay);
 buttonstopPlay.setEnabled(false);
 buttonstopPlay.setonclickListener(this);
}
public void onclick(View v) {
 if (v == buttonPlay) {
	 startPlaying();
 } else if (v == buttonstopPlay) {
	 stopPlaying();
 }
}
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();
	 }
 });
}
private void stopPlaying() {
 if (player.isPlaying()) {
	 player.stop();
	 player.release();
	 initializeMediaPlayer();
 }
 buttonPlay.setEnabled(true);
 buttonstopPlay.setEnabled(false);
 playSeekBar.setVisibility(View.INVISIBLE);
}
private void initializeMediaPlayer() {
 player = new MediaPlayer();
 try {
	 player.setDataSource("http://listen.radionomy.com/enchantedradio");
 } catch (IllegalArgumentException e) {
	 e.printStackTrace();
 } catch (IllegalStateException e) {
	 e.printStackTrace();
 } catch (IOException e) {
	 e.printStackTrace();
 }
 player.setOnBufferingUpdateListener(new OnBufferingUpdateListener() {
	 public void onBufferingUpdate(MediaPlayer mp, int percent) {
		 playSeekBar.setSecondaryProgress(percent);
		 Log.i("Buffering", "" + percent);
	 }
 });
}
@Override
protected void onpause() {
 super.onpause();
 if (player.isPlaying()) {
	 player.stop();
 }
}
}

le code du activity_main.xml :

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<Button
 android:id="@+id/buttonPlay"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentLeft="true"
 android:layout_alignParentTop="true"
 android:layout_marginLeft="30dp"
 android:layout_marginTop="68dp"
 android:text="BT1" />
<Button
 android:id="@+id/buttonstopPlay"
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 android:layout_alignParentLeft="true"
 android:layout_alignParentTop="true"
 android:layout_marginLeft="200dp"
 android:layout_marginTop="68dp"
 android:text="BT2" />
</RelativeLayout>

et celui du manifest:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.package a moi"
android:versionCode="1"
android:versionName="1.0" >
<uses-sdk
 android:minSdkVersion="8"
 android:targetSdkVersion="15" />
<uses-permission android:name="android.permission.INTERNET"></uses-permission>

<application
 android:icon="@drawable/ic_launcher"
 android:label="@string/app_name"
 android:theme="@style/AppTheme" >
<activity android:name=".myMain"
		 android:label="@string/app_name">
 <intent-filter>
	 <action android:name="android.intent.action.MAIN" />
	 <category android:name="android.intent.category.LAUNCHER" />
 </intent-filter>
</activity>

</application>

</manifest>

donc eclipse ne m'indique aucune erreur, je l'export et le signe pour le tester sur mon telephone, mais lorsque je le lance j'ai a chaque lancement l'erreur " Fermeture soudaine de l'application .... merci de réessayer"

quel en serait la cause ??? ya-t-il une erreur dans mon code ??

je vous remercie d'avance amis développeurs :P :lol:

Edited by tic&tac
Link to comment
Share on other sites

Si ton application plante sans raison "apparente", c'est quand même sûrement qu'il y a une erreur dans ton code ;)

Mais pour qu'on puisse t'aider, il va falloir d'abord nous aider à y voir plus clair

Que se passe-t'il exactement ? As tu regardé les traces qui apparaissent dans le LogCat ? Y vois tu la trace d'une exception ? laquelle ?

Link to comment
Share on other sites

Bonjour,

Il est vrai qu'avoir le message affiché sur catlog faciliterait la tache, mais en regardant ton code, voici plusieurs pistes qui t'aideront à faire marcher ton application :D

1- Nul part je ne vois playSeekBar qui est initialisé.

Du coup ton application risque de planter avec un beau 'nullPointerException' :P

Pense donc à l'initialiser.

2- Dans ton manifeste, il faut que tu changes package="com.package a moi" par le nom de ton package. Pour rappel il ne faut pas qu'il y-ai d'espace, par exemple: package="com.package.amoi"

3- Aussi remplace <activity android:name=".myMain" par

<activity android:name=".MainActivity"

Avec tout ça je pense qu'à la fin ça devrait au moins ne pas planter dès le lancement.

Tiens nous au courant B)

Link to comment
Share on other sites

lool oui dimach c'est moi qui l'est enlever pour pas le mettre sur le net :P

sinon ça y est j'ai résolu le problème mais actuellement j'ai un deuxieme problème, et sur le logcat je n'ai aucune erreur :/

donc j'ai changer mon code sur le MainActivity.java, j'ai un bouton play et un bouton stop, mon bouton play fonctionne et quand je rajoute pour le bouton stop j'ai plein d'érreur, faut il rajouté un }?? a quel endroit ? car lorsque je le met pour fermé le bouton 1 j'ai d'autre erreur qui apparaisse :/

voici le code en question:

import java.io.IOException;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.app.Activity;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.Button;

public class MainActivity extends Activity {


@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
 getMenuInflater().inflate(R.menu.activity_main, menu);
 return true;
}

@Override
protected void onstart() {

 Button btnop=(Button) findViewById(R.id.button1);
 btnop.setonclickListener(new View.onclickListener()
 {

 protected void onstop() {

	 Button btnop=(Button) findViewById(R.id.button2);
	 btnop.setonclickListener(new View.onclickListener()
	 {


	 public void onclick(View v) {
	 MediaPlayer mediaPlayer = new MediaPlayer();
		 try {
		 mediaPlayer.setDataSource("http://streaming208.radionomy.com/EnchantedRadio?group=55&countrycode=FR");
		 mediaPlayer.prepare();
		 mediaPlayer.start();
		 } catch (IOException e) {
		 Log.v("AUDIOHTTPPLAYER", e.getMessage());
		 }




 }});

 super.onDestroy();
}
}

Edited by tic&tac
Link to comment
Share on other sites

Salut!

C'est Eclipse qui ne compile pas là non?

Ta méthode onstart() n'est pas claire...il manque des choses j'ai l'impression lol

Essaie plutôt un truc dans le genre :

public class MainActivity extends Activity {

private MediaPlayer mediaPlayer;
private Button btStart;
private Button btStop;
@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);

 setContentView(R.layout.activity_main);

 mediaPlayer = new MediaPlayer();

 btStart=(Button) findViewById(R.id.button1);		
 btStart.setonclickListener(new onclickListener(){	   

  @Override 
  public void onclick(View v) {		 

   if (mediaPlayer.isPlaying() == false) {

 try {
  mediaPlayer.setDataSource("http://streaming208.radionomy.com/EnchantedRadio?group=55&countrycode=FR");
  mediaPlayer.prepare();
  mediaPlayer.start();
 } catch (IOException e) {
  Log.v("AUDIOHTTPPLAYER", e.getMessage());
 }
   }
  }		  
 });

 btStop =(Button) findViewById(R.id.button2);		
 btStop.setonclickListener(new onclickListener(){	   

  @Override 
  public void onclick(View v) {		 

   if (mediaPlayer.isPlaying()) {

 mediaPlayer.stop();

   }		  
  }		 
 });

}

@Override
protected void onpause() { 
 super.onpause();

 if (mediaPlayer.isPlaying()) {
  mediaPlayer.stop();
 }
}
}

Edited by eridsan
Link to comment
Share on other sites

merci pour ton aide, je l'ai un peu modifier car eclipse m'indiquai des erreurs

mon appli fonctionne presque maintenant :P je dit presque parce que bon je lance lance, la tout va bien, donc je fait play la musique marche donc tou va bien, je fait stop la musique s'arrete c'est bien... le probleme c'est que si je veu refaire play ba j'ai une fermeture soudiane de l'appli, voici le logcat si vous souhaitez m'aider ^_^

10-28 03:24:12.226: E/JBtlAgHandler(280): JBtlAg context is disabled
10-28 03:24:14.484: E/AudioHardwareALSA(9721): RE-OPEN AFTER STANDBY:: took 94 msecs
10-28 03:24:17.343: E/JBtlAgHandler(280): JBtlAg context is disabled
10-28 03:24:23.812: E/MediaPlayer(16147): setDataSource called in state 64
10-28 03:24:23.820: E/AndroidRuntime(16147): FATAL EXCEPTION: main
10-28 03:24:23.820: E/AndroidRuntime(16147): java.lang.IllegalStateException
10-28 03:24:23.820: E/AndroidRuntime(16147):     at android.media.MediaPlayer.setDataSource(Native Method)
10-28 03:24:23.820: E/AndroidRuntime(16147):     at com.radiodclub12200989.MainActivity$1.onclick(MainActivity.java:35)
10-28 03:24:23.820: E/AndroidRuntime(16147):     at android.view.View.performClick(View.java:2586)
10-28 03:24:23.820: E/AndroidRuntime(16147):     at android.view.View$PerformClick.run(View.java:9262)
10-28 03:24:23.820: E/AndroidRuntime(16147):     at android.os.Handler.handleCallback(Handler.java:587)
10-28 03:24:23.820: E/AndroidRuntime(16147):     at android.os.Handler.dispatchMessage(Handler.java:92)
10-28 03:24:23.820: E/AndroidRuntime(16147):     at android.os.Looper.loop(Looper.java:130)
10-28 03:24:23.820: E/AndroidRuntime(16147):     at android.app.ActivityThread.main(ActivityThread.java:3744)
10-28 03:24:23.820: E/AndroidRuntime(16147):     at java.lang.reflect.Method.invokeNative(Native Method)
10-28 03:24:23.820: E/AndroidRuntime(16147):     at java.lang.reflect.Method.invoke(Method.java:507)
10-28 03:24:23.820: E/AndroidRuntime(16147):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:860)
10-28 03:24:23.820: E/AndroidRuntime(16147):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
10-28 03:24:23.820: E/AndroidRuntime(16147):     at dalvik.system.NativeStart.main(Native Method)
10-28 03:24:24.882: E/Omap4ALSA(9721): called drain&close

je vais essayer de voir, mais bon je m'y connais pas beaucoup :/

Edited by tic&tac
Link to comment
Share on other sites

Essaie plutôt comme ça alors ;)

public class MainActivity extends Activity {
private MediaPlayer mediaPlayer;
private Button btStart;
private Button btStop;
private ProgressDialog progress;
@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);	  
 setContentView(R.layout.horz_scroll_main);
 progress = new ProgressDialog(this);
 progress.setTitle("Patientez");
 progress.setMessage("Initialisation mediaplayer...");
 progress.setIndeterminate(true);	   
 btStart=(Button) findViewById(R.id.button1);		 
 btStart.setonclickListener(new onclickListener(){	   
  @Override
  public void onclick(View v) {				
   if (mediaPlayer.isPlaying() == false) {
 mediaPlayer.start();
   }
  }			 
 });
 btStop =(Button) findViewById(R.id.button2);		 
 btStop.setonclickListener(new onclickListener(){		
  @Override
  public void onclick(View v) {				
   if (mediaPlayer.isPlaying()) {
 mediaPlayer.pause();
   }				
  }			
 });
 initMediaPlayer();	   
}
private void initMediaPlayer(){
 mediaPlayer = new MediaPlayer();
 progress.show();
 new Thread((new Runnable() {
  @Override
  public void run() {
   try {
 mediaPlayer.setDataSource("http://streaming208.radionomy.com/EnchantedRadio?group=55&countrycode=FR");
 mediaPlayer.prepare();
 mHandler.sendMessage(mHandler.obtainMessage());
   } catch (IOException e) {
 Log.v("AUDIOHTTPPLAYER", e.getMessage());
   }			 
  }
 })).start();
}
final Handler mHandler = new Handler() {
 public void handleMessage(Message msg) {
  progress.dismiss();
 }	   
};
@Override
protected void onpause() {
 super.onpause();
 if (mediaPlayer.isPlaying()) {
  mediaPlayer.pause();
 }
}
@Override
protected void onDestroy() { 
 super.onDestroy();
 if (mediaPlayer.isPlaying()) {
  mediaPlayer.stop();
 }
}
}

Edited by eridsan
Link to comment
Share on other sites

  • 1 month later...

hey les amis merci pour votre aide,

donc j'ai changé le code, mais deux problèmes persistent :emo_im_undecided: :

- premièrement, lorsque l'on clique sur play et que l'on appui sur le bouton accueil du telephone l'appli est en arriere plan la aucun problème, mais lorsque l'on veu revenir dessus en cliquant sur l'icone dans la notification une autre activity se lance et on ne peut pas faire stop pour stopper la musique, je ne vois pas comment faire :o

- deuxiement, quand l'on clique sur stop pour stopper la musique et que l'on reclique sur play pour remettre la musique l'appli se ferme soudainement, je ne vois pas comment faire non plus :(

étant débutant ça commence a me déprimé :o

voici mon code:

import java.io.IOException;
import android.app.Activity;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.MediaPlayer.OnPreparedListener;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.SeekBar;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends Activity {
 private MediaPlayer mediaPlayer = new MediaPlayer();
 private NotificationManager mNotificationManager;

 /**************************************
	 * Initialisation des données pour le controle du volume
	 */
 AudioManager audioManager;


@Override
public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);

}
@Override
protected void onstart() {

 audioManager = (AudioManager)getSystemService(MainActivity.AUDIO_SERVICE);
 int maxVolume = audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
 int curVolume = audioManager.getStreamVolume(AudioManager.STREAM_MUSIC);
 SeekBar volControl = (SeekBar)findViewById(R.id.seekBar1);
 volControl.setMax(maxVolume);
 volControl.setProgress(curVolume);
 volControl.setonseekBarChangeListener(new SeekBar.onseekBarChangeListener() {
			 public void onstopTrackingTouch(SeekBar arg0) {
			 // TODO Auto-generated method stub
			 }
			 public void onstartTrackingTouch(SeekBar arg0) {
			 // TODO Auto-generated method stub
			 }
			 public void onprogressChanged(SeekBar arg0, int arg1, boolean arg2) {
			 // TODO Auto-generated method stub
			 audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, arg1, 0);
			 }
 });


 //bouton pour le lancement de la radio
 Button btnop=(Button) findViewById(R.id.button1);
 btnop.setonclickListener(new View.onclickListener()
 {
	 public void onclick(View v) {

		 try {
			 //on definit la source du stream
		 mediaPlayer.setDataSource("http://streaming208.radionomy.com/EnchantedRadio?group=55&countrycode=FR");
		 //on le prepare de façon asynchrone pour eviter l'effet de freeze
		 mediaPlayer.prepareAsync();
		 //on joue
		 // mediaPlayer.start();
		 Toast.makeText(MainActivity.this, "Préparation de la Radio, Merci de patienter...", Toast.LENGTH_LONG).show();
		 ProgressBar _Prog = (ProgressBar) findViewById(R.id.progressBar1);
						 _Prog.setVisibility(View.VISIBLE);


		 }
		 //s'il y a des soucis on garde une trace de log
		 catch (IOException e) {
		 Log.v("AUDIOHTTPPLAYER", e.getMessage());
		 }
		 mediaPlayer.setOnPreparedListener(new OnPreparedListener() {

						 public void onPrepared(MediaPlayer mp) {
								 mediaPlayer.start();
								 mediaPlayer.isPlaying();
								 ProgressBar _Prog = (ProgressBar) findViewById(R.id.progressBar1);
								 _Prog.setVisibility(View.INVISIBLE);
									 Toast.makeText(MainActivity.this, "Radio en Lecture", Toast.LENGTH_LONG).show();
					 TextView _Text = (TextView) findViewById(R.id.textView3);
					 _Text.setText("Lecture");


					 //Initialisation de la notification
		 mNotificationManager =
			 (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
		 final Notification notifyDetails =
		 new Notification(R.drawable.playmedia,"Now playing radio",System.currentTimeMillis());
		 Context context = getApplicationContext();

		 CharSequence contentTitle = "Radio Disney Club en lecture";

		 CharSequence contentText = "Cliquer pour stopper";
		 Intent notifyIntent = new Intent(MainActivity.this, MainActivity.class);

		 PendingIntent intent =
			 PendingIntent.getActivity(MainActivity.this, 0,
			 notifyIntent, android.content.Intent.FLAG_ACTIVITY_NEW_TASK);
		 notifyDetails.setLatestEventInfo(context, contentTitle, contentText, intent);

		 mNotificationManager.notify(110, notifyDetails);

						 }
				 });


	 }	
 });

 //bouton pour stopper l'ecoute
 Button btnop1=(Button) findViewById(R.id.button2);
 btnop1.setonclickListener(new View.onclickListener() {

 public void onclick(View v) {
 if(mediaPlayer.isPlaying())
 {
 try {
 mediaPlayer.stop();
	 mediaPlayer.reset();
	 mediaPlayer.release();
	 mNotificationManager.cancel(110);

	 TextView _Text = (TextView) findViewById(R.id.textView3);
		 _Text.setText("Radio Stop");
} catch (Exception e) {
// TODO: handle exception
}
 }
 else
 Toast.makeText(MainActivity.this, "Pas de Lecture en cours", Toast.LENGTH_LONG).show();


 }
});

 super.onstart();
}

@Override
protected void onstop() {

super.onstop();
}
}

Link to comment
Share on other sites

Pour le premier problème, il te faut gérer ton player dans un Service. Ton Activity communique ensuite avec ton Service pour lancer/arrêter le player. Le Service survit à la fermeture de ton Activity, donc tu peux ainsi t'assurer de ne pas relancer un deuxième player en la réaffichant

Pour le second problème, il doit te suffire de réinitialiser le player (celui-ci garde un état, et une fois arrêté complètement, il ne peut être redémarré qu'après avoir été réinitialisé)

Link to comment
Share on other sites

pourtant le player se réinitialise.... enfin je croit

Button btnop1=(Button) findViewById(R.id.button2);
 btnop1.setonclickListener(new View.onclickListener() {

 public void onclick(View v) {
 if(mediaPlayer.isPlaying())
 {
 try {
 mediaPlayer.stop();
	 mediaPlayer.reset();
	 mediaPlayer.release();
	 mNotificationManager.cancel(110);

	 TextView _Text = (TextView) findViewById(R.id.textView3);
		 _Text.setText("Radio Stop");
} catch (Exception e) {

Link to comment
Share on other sites

Tu le réinitialises, certes, mais tu le libères ensuite ("release"), et à partir de là, tu ne peux plus utiliser ce player

Regarde la doc de MediaPlayer, il y a un beau diagramme d'état qui indique quelle action il faut effectuer par rapport à l'état du MediaPlayer

Link to comment
Share on other sites

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...