繁体   English   中英

线程,MediaPlayer,ProgressDialog和上下文问题

[英]thread, MediaPlayer, ProgressDialog and context issues

我已经尝试并完成了我在互联网上以及此处在stackoverflow上阅读的所有内容,以解决我的问题,但到目前为止没有成功。 我想做的基本上是在MediaPlayer缓冲来自Internet的流时单击一个按钮并显示一个ProgressDialog。 我有很多带有上下文内容( NullPointerException )和线程问题的错误。 以下是有关代码的一些详细信息:

  1. 该按钮是一个切换按钮,具有基于事件的背景图像(打开,关闭,未连接显示不同的图像按钮);
  2. 函数prepareStream()是应在线程中运行并在加载流后关闭ProgressDialog的函数。 它正在呼叫BBC广播的http流;
  3. 我猜问题出在上下文上……我在代码上放了一些Log.d标记,以检查问题出在哪里,O弄清楚了那是在mediaPlayer.start()方法上。

他去了那个小男孩:

package com.android.iFocus;


import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.media.MediaPlayer;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.ToggleButton;

import com.insightoverflow.iFocus.R;

public class iFocusActivity extends Activity implements OnClickListener {


    //Declare Controls
    public int count = 0;
    public int x = 1;
    public MediaPlayer mediaPlayer = null;
    ToggleButton toggleRain = null;
    Button buttonAbout = null;
    Button buttonMethod = null;
    Button buttonLink = null;
    public ProgressDialog progressDialog;
    public static final String TAG = "getFocused";



    public boolean isOnline() {
        //Check if internet is connected
        ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
        return activeNetworkInfo != null;

    }

    public void prepareStream(final Context context){
        if(isOnline()){
            // init player


            new Thread() 
            {
                public void run() 
                {

                    try {

                        sleep(1500);
                        //progressDialog.show();
                        mediaPlayer = MediaPlayer.create(context, Uri.parse("http://vprbbc.streamguys.net:80/vprbbc24.mp3"), null);
                        x=2;

                    } catch (Exception e){
                    x=3;
                }

                //dismiss the progressdialog   
                progressDialog.dismiss();
                }
            }.start();


        } else {
            x=3;
        }
    }

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        // load layout
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);


        // load controls
        toggleRain = (ToggleButton)findViewById(R.id.toggleRain);
        buttonAbout = (Button)findViewById(R.id.buttonAbout);
        buttonMethod = (Button)findViewById(R.id.buttonMethod);
        buttonLink = (Button)findViewById(R.id.buttonLink);


        //Define Listeners (click event handler)
        toggleRain.setOnClickListener(this);
        buttonAbout.setOnClickListener(this);
        buttonMethod.setOnClickListener(this);
        buttonLink.setOnClickListener(this);


        // init state for player
        count = 0;

        //Context APP
        //Context appContext = this.getApplicationContext();

        if (!isOnline()){
            toggleRain.setBackgroundDrawable(getResources().getDrawable(R.drawable.notconnectedbutton));
            x=3;
        }

    }


    public void onClick(View v) {


        if( toggleRain.getId() == ((Button)v).getId() ){

            //meanwhile device is offline, do this
            do {
                toggleRain.setBackgroundDrawable(getResources().getDrawable(R.drawable.notconnectedbutton));
                try{
                      Thread.currentThread();
                    //do what you want to do before sleeping
                      Thread.sleep(1000);//sleep for 1000 ms
                      //do what you want to do after sleeptig
                } catch(Exception ie){}

                continue;
            }while (!isOnline());

            //If device is online, go for this
            if (((CompoundButton) toggleRain).isChecked()) {
                toggleRain.setBackgroundDrawable(getResources().getDrawable(R.drawable.stopbutton));
            } else {
                toggleRain.setBackgroundDrawable(getResources().getDrawable(R.drawable.playbutton));
            }

                    //----> HERE GOES WHERE I THINK IS THE PROBLEM <-----
                    //---------------------------------------------------
            if (isOnline()){
                //If music is not playing, start music
                if(count==0){

                    Log.d(TAG, "START PROGRESS DIALOG");
                    progressDialog = ProgressDialog.show(v.getContext(), "Load", "Loading");
                    //progressDialog = ProgressDialog.show(, "Load", "Loading...", true, false);
                    Log.d(TAG, "END PROGRESS DIALOG");
                    Log.d(TAG, "START PREPARE STREAM");
                    Context context = v.getContext();
                    prepareStream(context);
                    Log.d(TAG, "END PREPARE STREAM");
                    Log.d(TAG, "START MEDIA PLAYER START");

                            //LOG CAT START AND END ALL OF THE OTHER LOG TAGS, EXCEPT THIS mediaplayer.start()
                    mediaPlayer.start();
                    Log.d(TAG, "END MEDIAPLAYER START");
                    count = 1;
                } else {
                    mediaPlayer.pause();
                    count = 0;
                }
            }               

    } else if( buttonAbout.getId() == ((Button)v).getId() ){

        Intent i = new Intent(iFocusActivity.this, AboutActivity.class);
        startActivity(i);

    }

    else if ( buttonMethod.getId() == ((Button)v).getId() ){

        Intent o = new Intent(iFocusActivity.this, MethodActivity.class);
        startActivity(o);
    }

    else if ( buttonLink.getId() == ((Button)v).getId() ){

        Uri uri = Uri.parse( "http://getFocused.in" );
        startActivity( new Intent( Intent.ACTION_VIEW, uri ) );
    }


}

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(mediaPlayer != null) {
            mediaPlayer.stop();
            mediaPlayer.release();
            mediaPlayer = null;
        }

    }


}

所以logcat告诉我mediaPlayer.start()被称为NullPointerException

您必须在runOnUiThread()方法中运行ProgressDialog.show() (不在主UI线程中)。 这里查看Android文档

创建一个进度对话框对象,然后编写此代码。

runOnUiThread(new Runnable(){
            @Override
            public void run() {
                dialog.show();
            }
        });

同样,调用prepareStream()mediaplayer.start()应当进入一个单独的线程,而不是主UI线程。

整理出与线程相关的问题,您应该已完成。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM