Java 线程、MediaPlayer、ProgressDialog和上下文问题

Java 线程、MediaPlayer、ProgressDialog和上下文问题,java,android,android-mediaplayer,android-context,Java,Android,Android Mediaplayer,Android Context,为了解决我的问题,我在互联网上和stackoverflow上读到的所有东西我都试过并做过,但直到现在都没有成功。我试图做的基本上是在MediaPlayer缓冲来自internet的流时单击一个按钮并显示一个ProgressDialog。我遇到了很多类型的错误,包括上下文内容(NullPointerException)和线程问题。以下是有关代码的一些详细信息: 该按钮是一个切换按钮,具有基于事件的背景图像sat(打开、关闭、未连接显示不同的图像按钮) 函数prepareStream()应该在线程中

为了解决我的问题,我在互联网上和stackoverflow上读到的所有东西我都试过并做过,但直到现在都没有成功。我试图做的基本上是在MediaPlayer缓冲来自internet的流时单击一个按钮并显示一个ProgressDialog。我遇到了很多类型的错误,包括上下文内容(
NullPointerException
)和线程问题。以下是有关代码的一些详细信息:

  • 该按钮是一个切换按钮,具有基于事件的背景图像sat(打开、关闭、未连接显示不同的图像按钮)
  • 函数
    prepareStream()
    应该在线程中运行,并在加载流后关闭ProgressDialog。它正在调用BBC广播的http流
  • 我想问题是关于上下文。。。我在代码上添加了一些Log.d标记,以检查问题发生在何处,并在
    mediaPlayer.start()
    method上找到了问题所在
  • 他对小男孩说:

    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;
            }
    
        }
    
    
    }
    
    package com.android.iFocus;
    导入android.app.Activity;
    导入android.app.ProgressDialog;
    导入android.content.Context;
    导入android.content.Intent;
    导入android.media.MediaPlayer;
    导入android.net.ConnectivityManager;
    导入android.net.NetworkInfo;
    导入android.net.Uri;
    导入android.os.Bundle;
    导入android.util.Log;
    导入android.view.view;
    导入android.view.view.OnClickListener;
    导入android.widget.Button;
    导入android.widget.CompoundButton;
    导入android.widget.ToggleButton;
    导入com.insightoverflow.iFocus.R;
    公共类iFocusActivity扩展了活动实现OnClickListener{
    //声明控件
    公共整数计数=0;
    公共整数x=1;
    public MediaPlayer=null;
    ToggleButton toggleRain=null;
    按钮buttonAbout=null;
    按钮方法=空;
    按钮链接=空;
    公共进程对话;
    公共静态最终字符串标记=“getFocused”;
    公共布尔isOnline(){
    //检查互联网是否已连接
    ConnectivityManager ConnectivityManager=(ConnectivityManager)getSystemService(Context.CONNECTIVITY_服务);
    NetworkInfo activeNetworkInfo=connectivityManager.getActiveNetworkInfo();
    返回activeNetworkInfo!=null;
    }
    public void prepareStream(最终上下文){
    if(isOnline()){
    //初始化播放器
    新线程()
    {
    公开募捐
    {
    试一试{
    睡眠(1500);
    //progressDialog.show();
    mediaPlayer=mediaPlayer.create(上下文,Uri.parse(“http://vprbbc.streamguys.net:80/vprbbc24.mp3(“”,空);
    x=2;
    }捕获(例外e){
    x=3;
    }
    //关闭progressdialog
    progressDialog.disclose();
    }
    }.start();
    }否则{
    x=3;
    }
    }
    /**在首次创建活动时调用*/
    @凌驾
    创建时的公共void(Bundle savedInstanceState){
    //负载布局
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    //负载控制
    toggleRain=(ToggleButton)findViewById(R.id.toggleRain);
    buttonAbout=(按钮)findViewById(R.id.buttonAbout);
    buttonMethod=(Button)findViewById(R.id.buttonMethod);
    buttonLink=(Button)findViewById(R.id.buttonLink);
    //定义侦听器(单击事件处理程序)
    切换rain.setOnClickListener(此);
    setOnClickListener(这个);
    buttonMethod.setOnClickListener(此);
    buttonLink.setOnClickListener(此);
    //玩家的初始状态
    计数=0;
    //上下文应用程序
    //Context-appContext=this.getApplicationContext();
    如果(!isOnline()){
    切换rain.setBackgroundDrawable(getResources().getDrawable(R.drawable.notconnectedbutton));
    x=3;
    }
    }
    公共void onClick(视图v){
    如果(切换rain.getId()==((按钮)v.getId()){
    //当设备处于脱机状态时,请执行此操作
    做{
    切换rain.setBackgroundDrawable(getResources().getDrawable(R.drawable.notconnectedbutton));
    试一试{
    Thread.currentThread();
    //睡觉前做你想做的事
    Thread.sleep(1000);//睡眠1000毫秒
    //睡觉后做你想做的事
    }捕获(例外情况即){}
    继续;
    }而(!isOnline());
    //如果设备处于联机状态,请执行此操作
    如果(((复合按钮)切换RAIN).isChecked()){
    toggleRain.setBackgroundDrawable(getResources().getDrawable(R.drawable.stopbutton));
    }否则{
    toggleRain.setBackgroundDrawable(getResources().getDrawable(R.drawable.playbutton));
    }
    
    //---->我认为问题出在这里您必须在
    runOnUiThread()
    方法中运行
    ProgressDialog.show()
    (不在主UI线程中)。请参阅Android文档

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

    runOnUiThread(new Runnable(){
                @Override
                public void run() {
                    dialog.show();
                }
            });
    
    另外,调用
    prepareStream()
    mediaplayer.start()
    应该进入一个单独的线程,而不是主UI线程


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

    我实现了我最终实现的方法:runOnUiThread((Runnable)(progressDialog=progressDialog.show(v.getContext(),“Load”,“Loading”));现在logcat显示了一个不太详细的错误:E/AndroidRuntime(7105):java.lang.ClassCastException:android.app.ProgressDialog.你认为我做错了什么?