(android)启动我的应用程序时出现错误java.lang.IllegalStateException

(android)启动我的应用程序时出现错误java.lang.IllegalStateException,第1张

概述我想写一个带有可视化的简单音乐播放器(扫描/ sdcard /音乐,添加到播放列表,播放和可视化)/ 但是当我启动应用程序时,我有一个错误无法启动活动(ru.vspr.MyMediaPlayerActivity) java.lang.IllegalStateException 我该怎么办呢? 源代码:http://www.mediafire.com/download/y1paremphr57mbz 我想写一个带有可视化的简单音乐播放器(扫描/ sdcard /音乐,添加到播放列表,播放和可视化)/
但是当我启动应用程序时,我有一个错误无法启动活动(ru.vspr.MyMediaPlayerActivity) java.lang.IllegalStateException
我该怎么办呢?

源代码:http://www.mediafire.com/download/y1paremphr57mbz/MyMediaPlayer.zip

日志:

07-24 13:20:01.023 E/AndroIDRuntime(22997): FATAL EXCEPTION: main07-24 13:20:01.023 E/AndroIDRuntime(22997): java.lang.RuntimeException: Unable to start activity ComponentInfo{ru.vspr/ru.vspr.MyMediaPlayerActivity}: java.lang.IllegalStateException07-24 13:20:01.023 E/AndroIDRuntime(22997): at androID.app.ActivityThread.performlaunchActivity(ActivityThread.java:1956)07-24 13:20:01.023 E/AndroIDRuntime(22997): at androID.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1981)07-24 13:20:01.023 E/AndroIDRuntime(22997): at androID.app.ActivityThread.access0(ActivityThread.java:123)07-24 13:20:01.023 E/AndroIDRuntime(22997): at androID.app.ActivityThread$H.handleMessage(ActivityThread.java:1147)07-24 13:20:01.023 E/AndroIDRuntime(22997): at androID.os.Handler.dispatchMessage(Handler.java:99)07-24 13:20:01.023 E/AndroIDRuntime(22997): at androID.os.Looper.loop(Looper.java:137)07-24 13:20:01.023 E/AndroIDRuntime(22997): at androID.app.ActivityThread.main(ActivityThread.java:4424)07-24 13:20:01.023 E/AndroIDRuntime(22997): at java.lang.reflect.Method.invokeNative(Native Method)07-24 13:20:01.023 E/AndroIDRuntime(22997): at java.lang.reflect.Method.invoke(Method.java:511)07-24 13:20:01.023 E/AndroIDRuntime(22997): at com.androID.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:784)07-24 13:20:01.023 E/AndroIDRuntime(22997): at com.androID.internal.os.ZygoteInit.main(ZygoteInit.java:551)07-24 13:20:01.023 E/AndroIDRuntime(22997): at dalvik.system.NativeStart.main(Native Method)07-24 13:20:01.023 E/AndroIDRuntime(22997): Caused by: java.lang.IllegalStateException07-24 13:20:01.023 E/AndroIDRuntime(22997): at androID.media.MediaPlayer._reset(Native Method)07-24 13:20:01.023 E/AndroIDRuntime(22997): at androID.media.MediaPlayer.reset(MediaPlayer.java:1218)07-24 13:20:01.023 E/AndroIDRuntime(22997): at ru.vspr.MyMediaPlayerActivity.loadMusic(MyMediaPlayerActivity.java:156)07-24 13:20:01.023 E/AndroIDRuntime(22997): at ru.vspr.MyMediaPlayerActivity.loadTrack(MyMediaPlayerActivity.java:147)07-24 13:20:01.023 E/AndroIDRuntime(22997): at ru.vspr.MyMediaPlayerActivity.initialize(MyMediaPlayerActivity.java:100)07-24 13:20:01.023 E/AndroIDRuntime(22997): at ru.vspr.MyMediaPlayerActivity.onCreate(MyMediaPlayerActivity.java:58)07-24 13:20:01.023 E/AndroIDRuntime(22997): at androID.app.Activity.performCreate(Activity.java:4492)07-24 13:20:01.023 E/AndroIDRuntime(22997): at androID.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1049)07-24 13:20:01.023 E/AndroIDRuntime(22997): at androID.app.ActivityThread.performlaunchActivity(ActivityThread.java:1920)07-24 13:20:01.023 E/AndroIDRuntime(22997): ... 11 more
package ru.vspr;import java.io.file;import java.io.fileDescriptor;import java.io.fileinputStream;import java.io.IOException;import java.util.ArrayList;import java.util.List;import java.util.Random;import androID.app.Activity;import androID.content.Context;import androID.content.res.AssetfileDescriptor;import androID.content.res.AssetManager;import androID.graphics.drawable.Drawable;import androID.media.audiofx.Visualizer;import androID.media.AudioManager;import androID.media.MediaPlayer;import androID.media.MediaPlayer.OnCompletionListener;import androID.os.Bundle;import androID.os.Environment;import androID.os.PowerManager;import androID.os.PowerManager.WakeLock;import androID.vIEw.Menu;import androID.vIEw.MenuItem;import androID.vIEw.VIEw;import androID.vIEw.Window;import androID.vIEw.WindowManager;import androID.Widget.button;import androID.Widget.ImageVIEw;import androID.Widget.Toast;import androID.util.Log;public class MyMediaPlayerActivity extends Activity implements OnCompletionListener {    WakeLock wakeLock;    private static final String[] EXTENSIONS = { ".mp3",".wav",".ogg" }; //Воспроизводимые форматы    List<String> tracknames; //Названия воспроизводимых треков    List<String> trackArtworks; //Обложки воспроизводимых треков    file path; //Директория,откуда будет загружена музыка    file path2; //Директория,откуда Р±СѓРґСѓС‚ загружены обложки треков    button btnPlay; //Эта РєРЅРѕРїРєР° будет менять СЃРІРѕС‘ изображение РїСЂРё нажатии    Random random; //Рспользовано для случайного воспроизведения    boolean shuffle; //Случайное воспроизведение включено?    boolean isTuning;     int currentTrack; //Рндекс текущего трека    MediaPlayer mediaPlayer; //Плеер    Visualizer mVisualizer; //Визуализатор для него    VisualizerVIEw mVisualizerVIEw; //VIEw для визуализатора    @OverrIDe    public voID onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        requestwindowFeature(Window.FEATURE_NO_Title);        setVolumeControlStream(AudioManager.STREAM_MUSIC);//      PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);//      wakeLock = powerManager.newWakeLock(PowerManager.FulL_WAKE_LOCK,"Powered by YOBA Engine");        setContentVIEw(R.layout.main);         initialize();    }    @OverrIDe    public voID onResume(){        super.onResume();        wakeLock.acquire();    }    @OverrIDe    public voID onPause(){        super.onPause();        wakeLock.release();        if(mediaPlayer != null){            if(isPlaying()){                pause();                isTuning = false;                btnPlay.setBackgroundResource(R.drawable.play);            }            if(isFinishing()){                dispose();                finish();            }        } else{            if(isFinishing()){                finish();            }        }    }    private voID initialize(){        btnPlay = (button) findVIEwByID(R.ID.btnPlay);        btnPlay.setBackgroundResource(R.drawable.play);        tracknames = new ArrayList<String>();        trackArtworks = new ArrayList<String>();        currentTrack = 0;        shuffle = false;        isTuning = false;        random = new Random();        mediaPlayer = new MediaPlayer();        addTracks(getTracks());        loadTrack();    }    //Generate a String Array that represents all of the files found    private String[] getTracks(){            if(Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)                     || Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED_READ_ONLY)){                path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_MUSIC);                path2 = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);                String[] temp = path.List();                return temp;            } else{                Toast.makeText(getBaseContext(),"SD Card is either mounted elsewhere or is unusable",Toast.LENGTH_LONG).show();            }        return null;    }    //Adds the playable files to the tracknames List    private voID addTracks(String[] temp){        if(temp != null){            for(int i = 0; i < temp.length; i++){                //Only accept files that have one of the extensions in the EXTENSIONS array                if(trackChecker(temp[i])){                    tracknames.add(temp[i]);                    trackArtworks.add(temp[i].substring(0,temp[i].length()-4));                }            }            Toast.makeText(getBaseContext(),"Loaded " + Integer.toString(tracknames.size()) + " Tracks",Toast.LENGTH_SHORT).show();        }    }    //Checks to make sure that the track to be loaded has a correct extenson    private boolean trackChecker(String trackToTest){        for(int j = 0; j < EXTENSIONS.length; j++){            if(trackToTest.contains(EXTENSIONS[j])){                return true;            }        }        return false;    }    //Loads the track by calling loadMusic    private voID loadTrack(){        if(mediaPlayer != null){            dispose();        }        if(tracknames.size() > 0){            loadMusic();        }    }    //loads a Music instance using either a built in asset or an external resource    private voID loadMusic(){            try{                fileinputStream fis = new fileinputStream(new file(path,tracknames.get(currentTrack)));                fileDescriptor fileDescriptor = fis.getFD();                mediaPlayer.setDataSource(fileDescriptor);                mediaPlayer.prepare();                mediaPlayer.setonCompletionListener(this);              //              setupVisualizerFxAndUI();                           } catch(IOException e){                e.printstacktrace();                Toast.makeText(getBaseContext(),"Error Loading " + tracknames.get(currentTrack),Toast.LENGTH_LONG).show();            }//          return null;    }    @OverrIDe    public boolean onCreateOptionsMenu(Menu menu){        super.onCreateOptionsMenu(menu);        createMenu(menu);        return true;    }    @OverrIDe    public boolean onoptionsItemSelected(MenuItem item){        switch(item.getItemID()){        case 0:            //Set LooPing            synchronized(this){                if(isLooPing()){                    setLooPing(false);                    Toast.makeText(getBaseContext(),"Playing Tracks Sequentially",Toast.LENGTH_SHORT).show();                } else{                    setLooPing(true);                    Toast.makeText(getBaseContext(),"LooPing " + tracknames.get(currentTrack),Toast.LENGTH_SHORT).show();                }            }            return true;        case 1:            //Set Shuffle            synchronized(this){                if(shuffle){                    setShuffle(false);                } else{                    setShuffle(true);                }            }            return true;        case 2:            //Stop Music            synchronized(this){                switchTracks();                btnPlay.setBackgroundResource(R.drawable.play);            }            return true;        default:            return false;        }    }    private voID createMenu(Menu menu){        MenuItem miLooPing = menu.add(0,"LooPing");{            miLooPing.setIcon(R.drawable.looPing);        }        MenuItem miShuffle = menu.add(0,1,"Shuffle");{            miShuffle.setIcon(R.drawable.shuffle);        }        MenuItem miStop = menu.add(0,2,"Stop");{            miStop.setIcon(R.drawable.stop);        }    }    public voID click(VIEw vIEw){        int ID = vIEw.getID();        switch(ID){        case R.ID.btnPlay:            synchronized(this){                if(isTuning){                    isTuning = false;                    btnPlay.setBackgroundResource(R.drawable.play);                    pause();                } else{                    isTuning = true;                    btnPlay.setBackgroundResource(R.drawable.pause);                    playTrack();                }            }            return;        case R.ID.btnPrevIoUs:            setTrack(0);            loadTrack();            playTrack();            return;        case R.ID.btnNext:            setTrack(1);            loadTrack();            playTrack();            return;        default:            return;        }    }    private voID setTrack(int direction){        if(direction == 0){            currentTrack--;            if(currentTrack < 0){                currentTrack = tracknames.size()-1;            }        } else if(direction == 1){            currentTrack++;            if(currentTrack > tracknames.size()-1){                currentTrack = 0;            }        }        if(shuffle){            int temp = random.nextInt(tracknames.size());            while(true){                if(temp != currentTrack){                    currentTrack = temp;                    break;                }                temp++;                if(temp > tracknames.size()-1){                    temp = 0;                }            }        }    }    //Plays the Track    private voID playTrack(){        if(isTuning && mediaPlayer != null){            play();            Toast.makeText(getBaseContext(),"Playing " + tracknames.get(currentTrack).substring(0,tracknames.get(currentTrack).length()-4),Toast.LENGTH_SHORT).show();        }    }    //Simply sets shuffle to isShuffle and then displays a message for confirmation    private voID setShuffle(boolean isShuffle) {        shuffle = isShuffle;        if(shuffle){            Toast.makeText(getBaseContext(),"Shuffle On",Toast.LENGTH_SHORT).show();        } else{            Toast.makeText(getBaseContext(),"Shuffle Off",Toast.LENGTH_SHORT).show();        }    }    public voID onCompletion(MediaPlayer mediaPlayer) {        synchronized(this){        }    }    public voID play() {        if(mediaPlayer.isPlaying()){            return;        }        try{            synchronized(this){                mediaPlayer.start();            }        } catch(IllegalStateException ex){            ex.printstacktrace();    }    }    public voID stop() {        mediaPlayer.stop();        synchronized(this){        }    }    public voID switchTracks(){        mediaPlayer.seekTo(0);        mediaPlayer.pause();    }    public voID pause() {        mediaPlayer.pause();    }    public boolean isPlaying() {        return mediaPlayer.isPlaying();    }    public boolean isLooPing() {        return mediaPlayer.isLooPing();    }    public voID setLooPing(boolean isLooPing) {        mediaPlayer.setLooPing(isLooPing);    }    public voID setVolume(float volumeleft,float volumeRight) {        mediaPlayer.setVolume(volumeleft,volumeRight);    }    public voID dispose() {        if(mediaPlayer.isPlaying()){            stop();        }        mediaPlayer.release();    }    public voID setupVisualizerFxAndUI() {                mVisualizerVIEw = new VisualizerVIEw(this);                mVisualizerVIEw = (VisualizerVIEw) findVIEwByID(R.ID.visualizerVIEw);                mVisualizer = new Visualizer(mediaPlayer.getAudioSessionID());                mVisualizer.setCaptureSize(Visualizer.getCaptureSizeRange()[1]);                mVisualizer.setDataCaptureListener(new Visualizer.OnDataCaptureListener() {                        public voID onWaveFormDataCapture(Visualizer visualizer,byte[] bytes,int samplingRate) {                            mVisualizerVIEw.updateVisualizer(bytes);                        }                        public voID onfftDataCapture(Visualizer visualizer,int samplingRate) {}                    },Visualizer.getMaxCaptureRate() / 1,true,false);    }}

附:在收到此错误之前,当我按“播放”按钮时,会有声音,但不是可视化.有没有办法来解决这个问题?

P.P.S对不起我的英文

解决方法

java.lang.IllegalStateException

在VM未处于正确状态时尝试执行 *** 作时抛出.

http://developer.android.com/reference/java/lang/IllegalStateException.html

07-24 12:49:27.054 E/AndroIDRuntime(21733): Caused by: java.lang.IllegalStateException 07-24 12:49:27.054 E/AndroIDRuntime(21733): at androID.media.MediaPlayer.setDataSource(Native Method) 07-24 12:49:27.054 E/AndroIDRuntime(21733): at androID.media.MediaPlayer.setDataSource(MediaPlayer.java:889)

你应该调用reset()使其恢复到空闲状态.只有这样才能调用setDataSource()

编辑:

您应该将其余代码放在onCompletion中

public voID onCompletion(MediaPlayer mediaPlayer) {        try {            mediaPlayer.reset();            mediaPlayer.setDataSource(path.getabsolutePath());            mediaPlayer.prepare();            mediaPlayer.setonCompletionListener(this);            mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);        } catch (IllegalArgumentException 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();        }    }
总结

以上是内存溢出为你收集整理的(android)启动我的应用程序时出现错误java.lang.IllegalStateException全部内容,希望文章能够帮你解决(android)启动我的应用程序时出现错误java.lang.IllegalStateException所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/web/1124962.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-30
下一篇 2022-05-30

发表评论

登录后才能评论

评论列表(0条)

保存