不幸的是,App已停止

时间:2015-01-13 05:43:39

标签: android

我正在尝试开发一个应用程序,它从我的服务器下载我的内容并在本地播放,所以当我点击图标时,初始屏幕出现(这是初始活动执行正常,如果一旦它进入它显示错误的第二个活动是

  

不幸的是app停止了

这是我的日志猫

01-13 00:25:41.070: E/AndroidRuntime(955): FATAL EXCEPTION: main
01-13 00:25:41.070: E/AndroidRuntime(955): Process: com.tmp.timbremediaplayer, PID: 955
01-13 00:25:41.070: E/AndroidRuntime(955): java.lang.RuntimeException: Unable to resume activity {com.tmp.timbremediaplayer/com.tmp.timbremediaplayer.MusicPlayerActivity}: android.util.SuperNotCalledException: Activity {com.tmp.timbremediaplayer/com.tmp.timbremediaplayer.MusicPlayerActivity} did not call through to super.onResume()
01-13 00:25:41.070: E/AndroidRuntime(955):  at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2788)
01-13 00:25:41.070: E/AndroidRuntime(955):  at android.app.ActivityThread.handleResumeActivity(ActivityThread.java:2817)
01-13 00:25:41.070: E/AndroidRuntime(955):  at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2250)
01-13 00:25:41.070: E/AndroidRuntime(955):  at android.app.ActivityThread.access$800(ActivityThread.java:135)
01-13 00:25:41.070: E/AndroidRuntime(955):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1196)
01-13 00:25:41.070: E/AndroidRuntime(955):  at android.os.Handler.dispatchMessage(Handler.java:102)
01-13 00:25:41.070: E/AndroidRuntime(955):  at android.os.Looper.loop(Looper.java:136)
01-13 00:25:41.070: E/AndroidRuntime(955):  at android.app.ActivityThread.main(ActivityThread.java:5017)
01-13 00:25:41.070: E/AndroidRuntime(955):  at java.lang.reflect.Method.invokeNative(Native Method)
01-13 00:25:41.070: E/AndroidRuntime(955):  at java.lang.reflect.Method.invoke(Method.java:515)
01-13 00:25:41.070: E/AndroidRuntime(955):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:779)
01-13 00:25:41.070: E/AndroidRuntime(955):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:595)
01-13 00:25:41.070: E/AndroidRuntime(955):  at dalvik.system.NativeStart.main(Native Method)
01-13 00:25:41.070: E/AndroidRuntime(955): Caused by: android.util.SuperNotCalledException: Activity {com.tmp.timbremediaplayer/com.tmp.timbremediaplayer.MusicPlayerActivity} did not call through to super.onResume()
01-13 00:25:41.070: E/AndroidRuntime(955):  at android.app.Activity.performResume(Activity.java:5312)
01-13 00:25:41.070: E/AndroidRuntime(955):  at android.app.ActivityThread.performResumeActivity(ActivityThread.java:2778)
01-13 00:25:41.070: E/AndroidRuntime(955):  ... 12 more

这是初始活动

public class SyncActivity extends Activity {
    private Button btnProgressBar;
    private ProgressDialog prgDialog;
    // Progress Dialog type (0 - for Horizontal progress bar)
    public static final int progress_bar_type = 0;
    // Music resource URL
    private static String file_url = "https://docs.google.com/uc?export=download&id=0B_TtB7EjzcYCUXVuRTFmRzNkczg";

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // Show Download Music Button
        btnProgressBar = (Button) findViewById(R.id.btnProgressBar);
        // Download Music Button click listener
        btnProgressBar.setOnClickListener(new View.OnClickListener() {
            // When Download Music Button is clicked
            public void onClick(View v)
            {
                // Disable the button to avoid playing of song multiple times
                btnProgressBar.setEnabled(false);
                // Downloaded Music File path in SD Card
                File sdcard = Environment.getExternalStorageDirectory();
                File dir = new File(sdcard.getAbsolutePath()+"/timbre media");
                dir.mkdirs();
                File file = new File(Environment.getExternalStorageDirectory().getPath()+"/timbre media/song.mp3");
                // Check if the Music file already exists
                if (file.exists()) 
                {
                    Toast.makeText(getApplicationContext(), "File already exist under SD card, playing Music", Toast.LENGTH_SHORT).show();
                    /* Play Music
                     * Include the player activity
                     * and playing starts from here if the music file
                     * already exist
                     */
                    Intent i = new Intent(getApplicationContext(), MusicPlayerActivity.class);
                    startActivityForResult(i, 100);
                // If the Music File doesn't exist in SD card (Not yet downloaded)
                } 
                else 
                {
                    Toast.makeText(getApplicationContext(), "File doesn't exist under SD Card, downloading Mp3", Toast.LENGTH_SHORT).show();
                    // Trigger Async Task (onPreExecute method)
                    new DownloadMusic().execute(file_url);
                }
            }
        });
    }

    // Show Dialog Box with Progress bar
    @Override
    protected Dialog onCreateDialog(int id) {
        switch (id) {
        case progress_bar_type:
            prgDialog = new ProgressDialog(this);
            prgDialog.setMessage("Downloading Mp3 file. Please wait...");
            prgDialog.setIndeterminate(false);
            prgDialog.setMax(100);
            prgDialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            prgDialog.setCancelable(false);
            prgDialog.show();
            return prgDialog;
        default:
            return null;
        }
    }

    // Async Task Class
    class DownloadMusic extends AsyncTask<String, String, String> 
    {

        // Show Progress bar before downloading Music


        @SuppressWarnings("deprecation")
        @Override
        protected void onPreExecute() {
            super.onPreExecute();
            // Shows Progress Bar Dialog and then call doInBackground method
            showDialog(progress_bar_type);
        }

        // Download Music File from Internet
        @Override
        protected String doInBackground(String... f_url) {
            int count;
            try {
                URL url = new URL(f_url[0]);
                URLConnection conection = url.openConnection();
                conection.connect();
                // Get Music file length
                int lenghtOfFile = conection.getContentLength();
                // input stream to read file - with 8k buffer
                InputStream input = new BufferedInputStream(url.openStream(),10*1024);
                // Output stream to write file in SD card
                OutputStream output = new FileOutputStream(Environment.getExternalStorageDirectory().getPath()+"/timbre media/song.mp3");
                byte data[] = new byte[1024];
                long total = 0;
                while ((count = input.read(data)) != -1) {
                    total += count;
                    // Publish the progress which triggers onProgressUpdate method
                    publishProgress("" + (int) ((total * 100) / lenghtOfFile));

                    // Write data to file
                    output.write(data, 0, count);
                }
                // Flush output
                output.flush();
                // Close streams
                output.close();
                input.close();
            } catch (Exception e) {
                Log.e("Error: ", e.getMessage());
            }
            return null;
        }

        // While Downloading Music File
        protected void onProgressUpdate(String... progress) {
            // Set progress percentage
            prgDialog.setProgress(Integer.parseInt(progress[0]));
        }

        // Once Music File is downloaded

        @SuppressWarnings("deprecation")
        @Override
        protected void onPostExecute(String file_url) {
            // Dismiss the dialog after the Music file was downloaded
            dismissDialog(progress_bar_type);
            Toast.makeText(getApplicationContext(), "Download complete, playing Music", Toast.LENGTH_LONG).show();
            /*
             *  Play the music
             */

                Intent i = new Intent(getApplicationContext(), MusicPlayerActivity.class);
                startActivityForResult(i, 100);         

        }
    }

}

这是第二项活动

public class MusicPlayerActivity extends Activity implements OnCompletionListener, SeekBar.OnSeekBarChangeListener {

private ImageButton btnPlay;
private ImageButton btnForward;
private ImageButton btnBackward;
private ImageButton btnNext;
private ImageButton btnPrevious;
private ImageButton btnPlaylist;
private ImageButton btnRepeat;
private ImageButton btnShuffle;
private ImageButton btnClose;
private SeekBar songProgressBar;
private TextView songTitleLabel;
private TextView songCurrentDurationLabel;
private TextView songTotalDurationLabel;
// Media Player
public MediaPlayer mp;
// Handler to update UI timer, progress bar etc,.
private Handler mHandler = new Handler();;
private SongsManager songManager;
private Utilities utils;
public int length=0;
private int seekForwardTime = 5000; // 5000 milliseconds
private int seekBackwardTime = 5000; // 5000 milliseconds
private int currentSongIndex = 0; 
private boolean isShuffle = false;
private boolean isRepeat = false;
private ArrayList<HashMap<String, String>> songsList = new ArrayList<HashMap<String, String>>();
String TAG = "phoneCallListener";


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

    // All player buttons
    btnPlay = (ImageButton) findViewById(R.id.btnPlay);
    btnForward = (ImageButton) findViewById(R.id.btnForward);
    btnBackward = (ImageButton) findViewById(R.id.btnBackward);
    btnNext = (ImageButton) findViewById(R.id.btnNext);
    btnPrevious = (ImageButton) findViewById(R.id.btnPrevious);
    btnPlaylist = (ImageButton) findViewById(R.id.btnPlaylist);
    btnRepeat = (ImageButton) findViewById(R.id.btnRepeat);
    btnShuffle = (ImageButton) findViewById(R.id.btnShuffle);
    btnClose = (ImageButton) findViewById(R.id.btnClose);
    songProgressBar = (SeekBar) findViewById(R.id.songProgressBar);
    songTitleLabel = (TextView) findViewById(R.id.songTitle);
    songCurrentDurationLabel = (TextView) findViewById(R.id.songCurrentDurationLabel);
    songTotalDurationLabel = (TextView) findViewById(R.id.songTotalDurationLabel);

    // Mediaplayer
    mp = new MediaPlayer();
    songManager = new SongsManager();
    utils = new Utilities();

    // Listeners
    songProgressBar.setOnSeekBarChangeListener(this); // Important
    mp.setOnCompletionListener(this); // Important

    // Getting all songs list
    songsList = songManager.getPlayList();

    // By default play first song
    playSong(0);

    /**
     * Play button click event
     * plays a song and changes button to pause image
     * pauses a song and changes button to play image
     * */
    btnPlay.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // check for already playing
            if(mp.isPlaying()){
                if(mp!=null){
                    mp.pause();
                    length = mp.getCurrentPosition();

                    // Changing button image to play button

                    btnPlay.setImageResource(R.drawable.btn_play);
                        }

            }else if(mp!=null)
            {
                // Resume song
                mp.start();
                // Changing button image to pause button
                btnPlay.setImageResource(R.drawable.btn_pause);

            }
            else 
            {
            onResume();             
            }
        }
    });
            /**
     * Forward button click event
     * Forwards song specified seconds
     * */
    btnForward.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // get current song position                
            int currentPosition = mp.getCurrentPosition();
            // check if seekForward time is lesser than song duration
            if(currentPosition + seekForwardTime <= mp.getDuration()){
                // forward song
                mp.seekTo(currentPosition + seekForwardTime);
            }else{
                // forward to end position
                mp.seekTo(mp.getDuration());
            }
        }
    });

    /*
     * Close image button
     */
    btnClose.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            openAlert(v);   
        }
    });
    /*private void openAlert(View view) {

    }
    */


    /**
     * Backward button click event
     * Backward song to specified seconds
     * */
    btnBackward.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // get current song position                
            int currentPosition = mp.getCurrentPosition();
            // check if seekBackward time is greater than 0 sec
            if(currentPosition - seekBackwardTime >= 0){
                // forward song
                mp.seekTo(currentPosition - seekBackwardTime);
            }else{
                // backward to starting position
                mp.seekTo(0);
            }

        }
    });

    /**
     * Next button click event
     * Plays next song by taking currentSongIndex + 1
     * */
    btnNext.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            // check if next song is there or not
            if(currentSongIndex < (songsList.size() - 1)){
                playSong(currentSongIndex + 1);
                currentSongIndex = currentSongIndex + 1;
            }else{
                // play first song
                playSong(0);
                currentSongIndex = 0;
            }

        }
    });

    /**
     * Back button click event
     * Plays previous song by currentSongIndex - 1
     * */
    btnPrevious.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if(currentSongIndex > 0){
                playSong(currentSongIndex - 1);
                currentSongIndex = currentSongIndex - 1;
            }else{
                // play last song
                playSong(songsList.size() - 1);
                currentSongIndex = songsList.size() - 1;
            }

        }
    });

    /**
     * Button Click event for Repeat button
     * Enables repeat flag to true
     * */
    btnRepeat.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if(isRepeat){
                isRepeat = false;
                Toast.makeText(getApplicationContext(), "Repeat is OFF", Toast.LENGTH_SHORT).show();
                btnRepeat.setImageResource(R.drawable.btn_repeat);
            }else{
                // make repeat to true
                isRepeat = true;
                Toast.makeText(getApplicationContext(), "Repeat is ON", Toast.LENGTH_SHORT).show();
                // make shuffle to false
                isShuffle = false;
                btnRepeat.setImageResource(R.drawable.btn_repeat_focused);
                btnShuffle.setImageResource(R.drawable.btn_shuffle);
            }   
        }
    });

    /**
     * Button Click event for Shuffle button
     * Enables shuffle flag to true
     * */
    btnShuffle.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            if(isShuffle){
                isShuffle = false;
                Toast.makeText(getApplicationContext(), "Shuffle is OFF", Toast.LENGTH_SHORT).show();
                btnShuffle.setImageResource(R.drawable.btn_shuffle);
            }else{
                // make repeat to true
                isShuffle= true;
                Toast.makeText(getApplicationContext(), "Shuffle is ON", Toast.LENGTH_SHORT).show();
                // make shuffle to false
                isRepeat = false;
                btnShuffle.setImageResource(R.drawable.btn_shuffle_focused);
                btnRepeat.setImageResource(R.drawable.btn_repeat);
            }   
        }
    });

    /**
     * Button Click event for Play list click event
     * Launches list activity which displays list of songs
     * */
    btnPlaylist.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View arg0) {
            Intent i = new Intent(getApplicationContext(), PlayListActivity.class);
            startActivityForResult(i, 100);         
        }
    });

}


public void onCallStateChanged(int state, String incoming_Number)
    {

    Intent i = new Intent(getApplicationContext(),Call_Exception.class);
    startActivityForResult(i, 100);

    }


protected void onResume(){
if(mp.isPlaying()== false)
{
    if(mp!=null)
    {
        mp.seekTo(length);
        super.onResume();
        mp.start();
        btnPlay.setImageResource(R.drawable.btn_pause);

    }

}
}

protected void openAlert(View v) {
    // TODO Auto-generated method stub
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(MusicPlayerActivity.this);

     alertDialogBuilder.setTitle(this.getTitle()+ " decision");
     alertDialogBuilder.setMessage("Are you sure?");
             // set negative button: No message
     alertDialogBuilder.setNegativeButton("No",new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int id) {
                // cancel the alert box and put a Toast to the user
                dialog.cancel();
                Toast.makeText(getApplicationContext(), "You choose a negative answer", 
                        Toast.LENGTH_SHORT).show();
            }
        });
     // set neutral button: Exit the app message
     alertDialogBuilder.setNeutralButton("Exit the app",new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog,int id) {
                // exit the app and go to the HOME
                MusicPlayerActivity.this.finish();
            }
        });

     AlertDialog alertDialog = alertDialogBuilder.create();
     // show alert
    alertDialog.show();
}

/**
 * Receiving song index from playlist view
 * and play the song
 * */
@Override
protected void onActivityResult(int requestCode,
                                 int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    if(resultCode == 100){
         currentSongIndex = data.getExtras().getInt("songIndex");
         // play selected song
         playSong(currentSongIndex);
    }

}




/**
 * Function to play a song
 * @param songIndex - index of song
 * */
public void  playSong(int songIndex){
    // Play song
    try {
        mp.reset();
        mp.setDataSource(songsList.get(songIndex).get("songPath"));
        mp.prepare();
        mp.start();

        // Displaying Song title
        String songTitle = songsList.get(songIndex).get("songTitle");
        songTitleLabel.setText(songTitle);

        // Changing Button Image to pause image
        btnPlay.setImageResource(R.drawable.btn_pause);

        // set Progress bar values
        songProgressBar.setProgress(0);
        songProgressBar.setMax(100);

        // Updating progress bar
        updateProgressBar();            
    } catch (IllegalArgumentException e) {
        e.printStackTrace();
    } catch (IllegalStateException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

/**
 * Update timer on seekbar
 * */
public void updateProgressBar() {
    mHandler.postDelayed(mUpdateTimeTask, 100);        
}   

/**
 * Background Runnable thread
 * */
private Runnable mUpdateTimeTask = new Runnable() {
       public void run() {
           long totalDuration = mp.getDuration();
           long currentDuration = mp.getCurrentPosition();

           // Displaying Total Duration time
           songTotalDurationLabel.setText(""+utils.milliSecondsToTimer(totalDuration));
           // Displaying time completed playing
           songCurrentDurationLabel.setText(""+utils.milliSecondsToTimer(currentDuration));

           // Updating progress bar
           int progress = (int)(utils.getProgressPercentage(currentDuration, totalDuration));
           //Log.d("Progress", ""+progress);
           songProgressBar.setProgress(progress);

           // Running this thread after 100 milliseconds
           mHandler.postDelayed(this, 100);
       }
    };

/**
 * 
 * */
@Override
public void onProgressChanged(SeekBar seekBar, int progress, boolean fromTouch) {

}

/**
 * When user starts moving the progress handler
 * */
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
    // remove message Handler from updating progress bar
    //mHandler.removeCallbacks(mUpdateTimeTask);


}

/**
 * When user stops moving the progress hanlder
 * */
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
    //mHandler.removeCallbacks(mUpdateTimeTask);
    //int totalDuration = mp.getDuration();
    // currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);

    // forward or backward to certain seconds
    //mp.seekTo(currentPosition);

    // update timer progress again
    //updateProgressBar();
    Toast.makeText(getApplicationContext(), "This facility is disabled",Toast.LENGTH_SHORT).show();

}

/**
 * On Song Playing completed
 * if repeat is ON play same song again
 * if shuffle is ON play random song
 * */
@Override
public void onCompletion(MediaPlayer arg0) {

    // check for repeat is ON or OFF
    if(isRepeat){
        // repeat is on play same song again
        playSong(currentSongIndex);
    } else if(isShuffle){
        // shuffle is on - play a random song
        Random rand = new Random();
        currentSongIndex = rand.nextInt((songsList.size() - 1) - 0 + 1) + 0;
        playSong(currentSongIndex);
    } else{
        // no repeat or shuffle ON - play next song
        if(currentSongIndex < (songsList.size() - 1)){
            playSong(currentSongIndex + 1);
            currentSongIndex = currentSongIndex + 1;
        }else{
            // play first song
            playSong(0);
            currentSongIndex = 0;
        }
    }
}

@Override
 public void onDestroy(){
 super.onDestroy();
    mp.release();
 }

}

3 个答案:

答案 0 :(得分:0)

从log cat我观察到的是你已经覆盖了activty的onResume()方法,但没有调用super方法。尝试按如下方式实现onResume()。

@Override
protected void onResume() {
    super.onResume();
    //Your code here
}

请注意,super.onResume()必须是onResume()函数内的第一个调用。

希望这有帮助。

答案 1 :(得分:0)

  

01-13 00:25:41.070:E / AndroidRuntime(955):进程:com.tmp.timbremediaplayer,PID:955   01-13 00:25:41.070:E / AndroidRuntime(955):java.lang.RuntimeException:无法恢复活动{com.tmp.timbremediaplayer / com.tmp.timbremediaplayer.MusicPlayerActivity}:android.util.SuperNotCalledException:Activity { com.tmp.timbremediaplayer / com.tmp.timbremediaplayer.MusicPlayerActivity}没有调用super.onResume()

您忘了拨打 super.onResume()

答案 2 :(得分:0)

从日志里面说的是你“没有打电话给super.onResume()” 因此,如果要覆盖'onResume',则在Activity类中,它应该如下所示

protected void onResume()
{
    super.onResume();//This is important

    //Your code goes here
}

如果您已经完成此操作,请发布您的活动代码