音频android确实强制关闭应用程序

Posted

技术标签:

【中文标题】音频android确实强制关闭应用程序【英文标题】:Audio android does forces closes app 【发布时间】:2012-11-25 18:38:58 【问题描述】:

我已经创建了一个带有歌曲列表视图的音频播放器,当用户点击列表视图中的一个项目时,音乐播放器将启动并按下一个按钮来暂停它,这一切都很好!

我的下一站我实现了一个搜索栏来更新歌曲的进度和两个文本视图,一个用于当前歌曲的持续时间,一个用于歌曲的总持续时间。我已经编写了代码,一切似乎都很好,但每次我运行它都会强制关闭

请帮忙!

.Java 类

public class Nasheeds extends ListActivity implements OnCompletionListener, SeekBar.OnSeekBarChangeListener 
//ArrayList holds the data (as HashMaps) to load into the ListView
ArrayList<HashMap<String,String>> list = new ArrayList<HashMap<String,String>>();
//SimpleAdapter does the work to load the data in to the ListView
private SimpleAdapter sa;
private MediaPlayer mp;
public boolean istrue = true;
 private ImageButton btnPrevious;
 private ImageButton btnNext;

 private SeekBar songProgressBar;
 private TextView songCurrentDurationLabel;
 private TextView songTotalDurationLabel;

 //Handler to update UI timer, progress bar
 private Handler mHandler = new Handler();;
 private Utilities utils;
 private int seekForwardTime = 5000; //500 milliseconds
 private int seekBackwardTime = 5000;

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



    //HashMap links each line of data to the correct TextView
    HashMap<String,String> item;
    for(int i=0;i<Nasheed.length;i++)
      item = new HashMap<String,String>();
      item.put( "line1", Nasheed[i][0]);
      item.put( "line2", Nasheed[i][1]);

      list.add( item );
    

    sa = new SimpleAdapter(this, list,
            R.layout.nasheeds1,
            new String[]  "line1","line2" ,
            new int[] R.id.displayname, R.id.title);

    setListAdapter(sa);



    btnPrevious = (ImageButton) findViewById(R.id.prev);
    btnNext = (ImageButton)findViewById(R.id.next);
    songProgressBar = (SeekBar)findViewById(R.id.seekbar);
    songCurrentDurationLabel = (TextView)findViewById(R.id.songCurrentDurationLabel);
    songTotalDurationLabel = (TextView)findViewById(R.id.songTotalDurationLabel);

    utils = new Utilities();

    songProgressBar.setOnSeekBarChangeListener(this);
    mp.setOnCompletionListener(this);






  getListView().setOnItemClickListener(new OnItemClickListener() 

    public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,
            long arg3) 
        switch (arg2)
        
        case 0:
            System.out.println("User selected option 1");
        //  mp.stop();
            if (mp != null && mp.isPlaying()) 
               mp.stop();
           else
            mp = MediaPlayer.create(Nasheeds.this, R.raw.mok);
            mp.start();

            // MediaPlayer mp = MediaPlayer.create(Nasheeds.this, R.raw.mok);  
            //  mp.start(); 

            TextView tv=(TextView) findViewById(R.id.selectedfile);
            tv.setText("Playing "+ "Mountains of Mekkah, Zain Bikha");

            //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 (IO Exception e)
                e.printStackTrace();
            */

            break;
        case 1:
            System.out.println("User selected option 2");
            if (mp != null && mp.isPlaying()) 
               mp.stop();
           else
            mp = MediaPlayer.create(Nasheeds.this, R.raw.hnim);
            mp.start();

        case 2:

            break;                  
        

    

  );



  View playbtn = findViewById(R.id.play);
playbtn.setOnClickListener(new OnClickListener() 

    public void onClick(View v) 
        // TODO Auto-generated method stub
          if (istrue) 
              mp.pause();
              istrue = false;
           else 
              mp.start();
              istrue = true;
          



          


);


btnPrevious.setOnClickListener(new View.OnClickListener() 

    public void onClick(View arg0) 
       /* if(currentSongIndex > 0)
            playSong(currentSongIndex - 1);
            currentSongIndex = currentSongIndex - 1;
        else
            // play last song
            playSong(list.size() - 1);
            currentSongIndex = list.size() - 1;
        */
        System.out.println("Click Works");

    
);


btnNext.setOnClickListener(new View.OnClickListener() 

    public void onClick(View v) 
        System.out.println("Click Works");
    
);







public void updateProgressBar()
    mHandler.postDelayed(mUpdateTimeTask, 100);
  

 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));
          songProgressBar.setProgress(progress);

          //running this thread after 100 milliseconds
          mHandler.postDelayed(this, 100);
      
  ;
public void onProgressChanged(SeekBar seekBar, int progress,
        boolean fromUser) 
    // TODO Auto-generated method stub


public void onStartTrackingTouch(SeekBar seekBar) 
    mHandler.removeCallbacks(mUpdateTimeTask);

public void onStopTrackingTouch(SeekBar seekBar) 
    mHandler.removeCallbacks(mUpdateTimeTask);
    int totalDuration = mp.getDuration();
    int currentPosition = utils.progressToTimer(seekBar.getProgress(), totalDuration);

    mp.seekTo(currentPosition);
    updateProgressBar();


   private String[][] Nasheed =
        "Mountains of Mekkah","Zain Bikha",
        "His name is Mohammed","Kamal Uddin",
        "Hadith 3",".....add hadith",;

public void onCompletion(MediaPlayer mp) 





Utils 类

package com.example.fuelfinder;

public class Utilities 
 /**
 * Function to convert milliseconds time to
 * Timer Format
 * Hours:Minutes:Seconds
 * */
public String milliSecondsToTimer(long milliseconds)
    String finalTimerString = "";
    String secondsString = "";

    // Convert total duration into time
       int hours = (int)( milliseconds / (1000*60*60));
       int minutes = (int)(milliseconds % (1000*60*60)) / (1000*60);
       int seconds = (int) ((milliseconds % (1000*60*60)) % (1000*60) / 1000);
       // Add hours if there
       if(hours > 0)
           finalTimerString = hours + ":";
       

       // Prepending 0 to seconds if it is one digit
       if(seconds < 10)
           secondsString = "0" + seconds;
       else
           secondsString = "" + seconds;

       finalTimerString = finalTimerString + minutes + ":" + secondsString;

    // return timer string
    return finalTimerString;


/**
 * Function to get Progress percentage
 * @param currentDuration
 * @param totalDuration
 * */
public int getProgressPercentage(long currentDuration, long totalDuration)
    Double percentage = (double) 0;

    long currentSeconds = (int) (currentDuration / 1000);
    long totalSeconds = (int) (totalDuration / 1000);

    // calculating percentage
    percentage =(((double)currentSeconds)/totalSeconds)*100;

    // return percentage
    return percentage.intValue();


/**
 * Function to change progress to timer
 * @param progress -
 * @param totalDuration
 * returns current duration in milliseconds
 * */
public int progressToTimer(int progress, int totalDuration) 
    int currentDuration = 0;
    totalDuration = (int) (totalDuration / 1000);
    currentDuration = (int) ((((double)progress) / 100) * totalDuration);

    // return current duration in milliseconds
    return currentDuration * 1000;


xml 文件 1

    <TextView
            android:layout_
            android:layout_
            android:id="@+id/displayname"
            android:textSize="18dip"
            android:textStyle="bold"
            android:singleLine="true"
            android:ellipsize="end"/>

    <LinearLayout
            android:orientation="horizontal"
            android:layout_
            android:layout_>

            <TextView
                    android:layout_
                    android:layout_
                    android:id="@+id/title"
                    android:textSize="15dip"
                    android:singleLine="true"
                    android:ellipsize="end"
                    android:layout_weight="1.0"/>

            <TextView
                    android:layout_
                    android:layout_
                    android:id="@+id/duration"
                    android:gravity="right"
                    android:textSize="15dip"
                    android:singleLine="true"
                    android:ellipsize="end"/>
    </LinearLayout>

</LinearLayout>

第二个xml文件:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_
android:layout_>

    <ListView 
        android:layout_
        android:layout_
        android:id="@android:id/list"
        android:layout_weight="1.0"
        />

    <LinearLayout
            android:orientation="vertical"
    android:layout_
    android:layout_
    android:background="@android:drawable/screen_background_light"
    android:padding="10dip">

    <TextView
            android:layout_
            android:layout_
            android:id="@+id/selectedfile"
            android:text="Not file selected"
            android:textColor="@android:color/black"
            android:gravity="center_horizontal"
            android:singleLine="true"
            android:ellipsize="middle"/>

    <SeekBar
            android:layout_
            android:layout_
            android:id="@+id/seekbar"
            android:max="100"
            android:paddingBottom="10dip"/>

    <LinearLayout
                    android:orientation="horizontal"
            android:layout_
            android:layout_
            android:gravity="center"
            android:background="@android:drawable/screen_background_light">

        <TextView
            android:id="@+id/songCurrentDurationLabel"
            android:layout_
            android:layout_
            android:text="TextView" />

            <ImageButton
                    android:layout_
                    android:layout_
                    android:id="@+id/prev"
                    android:src="@android:drawable/ic_media_previous"
                    android:onClick="doClick"/>

            <ImageButton
                    android:layout_
                    android:layout_
                    android:id="@+id/play"
                    android:src="@android:drawable/ic_media_play"
                    android:onClick="onClick"/>

            <ImageButton
                    android:layout_
                    android:layout_
                    android:id="@+id/next"
                    android:src="@android:drawable/ic_media_next"
                    android:onClick="doClick"/>

            <TextView
                android:id="@+id/songTotalDurationLabel"
                android:layout_
                android:layout_
                android:text="TextView" />

    </LinearLayout> 
    </LinearLayout> 

LogCat:

12-07 14:43:02.262: E/AndroidRuntime(1009): FATAL EXCEPTION: main
12-07 14:43:02.262: E/AndroidRuntime(1009): java.lang.RuntimeException: Unable to start     activity ComponentInfocom.example.fuelfinder/com.example.fuelfinder.Nasheeds:  java.lang.NullPointerException
12-07 14:43:02.262: E/AndroidRuntime(1009):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2059)
12-07 14:43:02.262: E/AndroidRuntime(1009):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2084)
12-07 14:43:02.262: E/AndroidRuntime(1009):     at android.app.ActivityThread.access$600(ActivityThread.java:130)
12-07 14:43:02.262: E/AndroidRuntime(1009):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1195)
12-07 14:43:02.262: E/AndroidRuntime(1009):     at android.os.Handler.dispatchMessage(Handler.java:99)
12-07 14:43:02.262: E/AndroidRuntime(1009):     at android.os.Looper.loop(Looper.java:137)
12-07 14:43:02.262: E/AndroidRuntime(1009):     at android.app.ActivityThread.main(ActivityThread.java:4745)
12-07 14:43:02.262: E/AndroidRuntime(1009):     at java.lang.reflect.Method.invokeNative(Native Method)
12-07 14:43:02.262: E/AndroidRuntime(1009):     at java.lang.reflect.Method.invoke(Method.java:511)
12-07 14:43:02.262: E/AndroidRuntime(1009):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:786)
12-07 14:43:02.262: E/AndroidRuntime(1009):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
12-07 14:43:02.262: E/AndroidRuntime(1009):     at dalvik.system.NativeStart.main(Native Method)
12-07 14:43:02.262: E/AndroidRuntime(1009): Caused by: java.lang.NullPointerException
12-07 14:43:02.262: E/AndroidRuntime(1009):     at com.example.fuelfinder.Nasheeds.onCreate(Nasheeds.java:79)
12-07 14:43:02.262: E/AndroidRuntime(1009):     at android.app.Activity.performCreate(Activity.java:5008)
12-07 14:43:02.262: E/AndroidRuntime(1009):     at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1079)
12-07 14:43:02.262: E/AndroidRuntime(1009):     at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2023)
12-07 14:43:02.262: E/AndroidRuntime(1009):     ... 11 more

【问题讨论】:

在您的 com.example.fuelfinder.Nasheeds.OnCreate(第 79 行)中,抛出了一个空异常。可能是你的 SongProgressBar 没找到! 【参考方案1】:

由于 *** 没有行号,因此很难具体说明发生了什么,但异常中的违规行相当清楚:

12-07 14:43:02.262:E/AndroidRuntime(1009):原因:java.lang.NullPointerException 12-07 14:43:02.262: E/AndroidRuntime(1009): at com.example.fuelfinder.Nasheeds.onCreate(Nasheeds.java:79)

我有一种感觉,如果你在那里设置一个断点,你将能够很快找到问题。

【讨论】:

mp.setOnCompletionListener(this);我还没有学会使用 Eclipse 进行调试,在此行上放置断点后,我单击调试,但我无法找到 Eclipse 上显示此行发生的情况 找到了我要找的东西,这是你提到的快速修复行,onCompletion 方法没有做任何事情,所以在里面添加了完成后转到下一个轨道

以上是关于音频android确实强制关闭应用程序的主要内容,如果未能解决你的问题,请参考以下文章

从睡眠模式唤醒时不会播放音频(android)

Android强制HDMI音频

ipad上的背景音频不会停止

Android:如何在“强制关闭”后自动重启应用程序?

android“强制关闭”内存到底发生了啥

如何确定Android应用程序是不是被强制关闭?