2012-07-02 12 views
8

Como puedes ver, tengo esta actividad PlayLesson_01 que muestra imágenes y audio al mismo tiempo. Esta actividad tiene dos controladores, uno para controlar las imágenes y el audio, mientras que el otro finalizará la lección y volverá a la actividad anterior (Menú de Lecciones).onBackPresionada para matar a un controlador dentro de una actividad - Android

Objetivo: Haga clic en el botón Atrás para volver a la actividad anterior y detener la reproducción de imágenes y audio.

Problema: Cuando hago clic en el disco "Back" yo soy capaz de volver a la actividad anterior, pero el audio no es todavía capaz de playing.I'm parada o matan el manejador que se lanzó dentro de la actividad.

Pregunta: ¿Cómo puedo matar o detener a los controladores por completo?

import android.app.Activity; 
import android.content.Context; 
import android.content.Intent; 
import android.media.MediaPlayer; 
import android.media.MediaPlayer.OnCompletionListener; 
import android.os.Bundle; 
import android.os.Handler; 
import android.os.Looper; 
import android.view.View; 
import android.view.ViewGroup; 
import android.view.Window; 
import android.view.animation.AnimationUtils; 
import android.widget.AdapterView; 
import android.widget.AdapterView.OnItemSelectedListener; 
import android.widget.BaseAdapter; 
import android.widget.Gallery; 
import android.widget.ImageSwitcher; 
import android.widget.ImageView; 
import android.widget.RelativeLayout.LayoutParams; 
import android.widget.ViewSwitcher.ViewFactory; 

public class PlayLesson_01 extends Activity implements OnItemSelectedListener, 
    ViewFactory, Runnable { 

// Setting up images 
// Keeping all Images in array references to our images 
public Integer[] mThumbIds = { R.drawable.nouraniyah, 
     R.drawable.back_angle, R.drawable.back_fox, R.drawable.back_apple, 
     R.drawable.back_twitter, R.drawable.back_thunderbird }; 
// setting up music 
int[] myMusic = { R.raw.button_3, R.raw.button_3, R.raw.button_3, 
     R.raw.button_3, R.raw.button_3, R.raw.button_3 }; 
int mNext; 
private ImageSwitcher mSwitcher; 
MediaPlayer mp; 
Handler mHandlerWholeLesson = new Handler(); 
Runnable mRunnableWholelesson = new Runnable() { 

    @Override 
    public void run() { 
     // TODO Auto-generated method stub 
     startActivity(new Intent("com.example.AmazingGame.LESSONONE")); 
    } 
}; 

Handler mHandlerNextfile = new Handler(); 
Runnable mRunnableNextFile = new Runnable() { 

    @Override 
    public void run() { 
     // TODO Auto-generated method stub 
     mp.setOnCompletionListener(mListener); 
     mp.start(); 
    } 

}; 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    // TODO Auto-generated method stub 
    super.onCreate(savedInstanceState); 
    requestWindowFeature(Window.FEATURE_NO_TITLE); 
    setContentView(R.layout.image_switcher); // it could be lesson one 
               // layout. 

    mSwitcher = (ImageSwitcher) findViewById(R.id.imgswitcher); 
    mSwitcher.setFactory(this); 
    mSwitcher.setInAnimation(AnimationUtils.loadAnimation(this, 
      android.R.anim.fade_in)); 
    mSwitcher.setOutAnimation(AnimationUtils.loadAnimation(this, 
      android.R.anim.fade_out)); 

    Gallery g = (Gallery) findViewById(R.id.gallery); 
    g.setAdapter(new ImageAdapter(this)); 
    g.setOnItemSelectedListener(this); 
    // usual onCreate stuff here, then... 
    // either here or whenever you want to start the sequence 
    mNext = 0; 
    startNextFile(); 

    // Is this good !! Yes it is. count the time for all audio. 
    mHandlerWholeLesson.postDelayed(mRunnableWholelesson, 25000); 

} 

@Override 
public void onBackPressed() { 
    super.onBackPressed(); 
    startActivity(new Intent("com.example.AmazingGame.LESSONONE")); 
    System.exit(0); 
    mHandlerNextfile 
      .removeCallbacks(mRunnableNextFile, PlayLesson_01.class); 
    mHandlerWholeLesson.removeCallbacks(mRunnableWholelesson, 
      PlayLesson_01.class); 

    PlayLesson_01.this.finish(); 
} 

@Override 
protected void onDestroy() { 
    // TODO Auto-generated method stub 
    super.onDestroy(); 
    // mHandlerNextFile.removeCallbacksAndMesssages(PlayLesson_01.class); 
} 

public void onItemSelected(AdapterView<?> parent, View v, 
     final int position, long id) { 

} 

@Override 
public void onNothingSelected(AdapterView<?> arg0) { 
    // TODO Auto-generated method stub 

} 

@Override 
public View makeView() { 
    ImageView i = new ImageView(this); 
    i.setBackgroundColor(0xFF000000); 
    i.setScaleType(ImageView.ScaleType.FIT_CENTER); 
    i.setLayoutParams(new ImageSwitcher.LayoutParams(
      LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT)); 
    return i; 
} 

public class ImageAdapter extends BaseAdapter { 
    public ImageAdapter(Context c) { 
     mContext = c; 
    } 

    public int getCount() { 
     return mThumbIds.length; 
    } 

    public Object getItem(int position) { 
     return position; 
    } 

    public long getItemId(int position) { 
     return position; 
    } 

    public View getView(int position, View convertView, ViewGroup parent) { 
     ImageView i = new ImageView(mContext); 

     i.setImageResource(mThumbIds[position]); 
     i.setAdjustViewBounds(true); 
     i.setLayoutParams(new Gallery.LayoutParams(
       LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); 
     i.setBackgroundResource(R.drawable.picture_frame); 
     return i; 
    } 

    private Context mContext; 

} 

OnCompletionListener mListener = new OnCompletionListener() { 

    @Override 
    public void onCompletion(MediaPlayer mp) { 
     mp.release(); 
     startNextFile(); 
    } 
}; 

@Override 
protected void onPause() { 
    // TODO Auto-generated method stub 
    super.onPause(); 
    this.finish(); 

} 

public void startNextFile() { 

    if (mNext < myMusic.length) { 

     mp = MediaPlayer.create(this, myMusic[mNext]); 
     mSwitcher.setImageResource(mThumbIds[mNext++]); 
     mHandlerNextfile.postDelayed(mRunnableNextFile, 3000); 
    } 

} 

@Override 
public void run() { 
    // TODO Auto-generated method stub 

} 

}

Respuesta

42

Ahora hay un par de cosas mal en su código:

  1. Si quiere volver a su actividad anterior, no relanzarlo utilizando un startActivity como el comportamiento predeterminado de Android es que mantiene una pila de actividades previas. En la prensa de back será por defecto volver a la actividad anterior (a menos que haya puesto en marcha la actividad del niño usando algunas banderas.)

  2. ¿Por qué utiliza un System.exit(0); de prensa en la espalda? Solo tiene que llamar al finish() para finalizar la actividad actual.

  3. La mejor forma de eliminar las devoluciones de llamada desde un controlador es usar un null como parámetro. Puede probar el siguiente código:

    mHandlerNextfile.removeCallbacksAndMessages(null); 
    mHandlerWholeLesson.removeCallbacksAndMessages(null); 
    

    ya que esto eliminaría todas las devoluciones de llamada. Compruebe este enlace para saber más: http://developer.android.com/reference/android/os/Handler.html#removeCallbacksAndMessages(java.lang.Object)

+0

Gracias. Ahora funciona. Cambié los parámetros de ambos controladores a "nulo". Saqué System.exit (0). – Jawwalcom

+0

handler.removeCallbacksAndMessages (null); es increíble para eliminar todo el controlador. –

+0

anula el método Destroy() y llama a mp.release() para detener la reproducción .. – SHB

0

su controlador no está "en marcha", el reproductor multimedia es. Simplemente llame al mp.stop() en onBackPressed().

Además, lo que dijo Arun George.

+0

Agregar ** mp.stop() ** en ** onBackPressed ** no funcionó. Lanza MediaPalyer Error (-38,0). – Jawwalcom

+0

con un par de cambios. Funcionó. Agregué ** mp.stop() ** en ** OnBackPressed ** – Jawwalcom

+0

sería mp.release() – SHB

Cuestiones relacionadas