Android - 执行异步任务和执行线程时出现问题

时间:2011-06-18 00:59:04

标签: android

有人可以帮我这个代码吗?我要做的就是确定设备的互联网连接是否在带有异步任务的单独Connection类中可用,并将结果返回到我的启动画面活动。如果连接未激活,我想抛出一个对话框警告,说它不活动,然后终止应用程序。我无法触发asynch任务并返回非null结果。

Splash.java:

package com.nwp;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.os.Bundle;



public class Splash extends Activity {

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

    }

private void initSplash()
{    
     final ProgressDialog dialog = ProgressDialog.show(this, 
             getResources().getString(R.string.splashCheckInterenetConnection), 
             getResources().getString(R.string.splashPleaseWait), true);  

     Connection.context = this;
     if(!Connection.isOnline());
     {   
         AlertDialog.Builder dlgAlert  = new AlertDialog.Builder(this);
         dlgAlert.setMessage(R.string.splashNoInternetConnection);
         dlgAlert.setCancelable(true);
         dlgAlert.setNeutralButton("Ok", 
                 new DialogInterface.OnClickListener() {                 
             // click listener on the alert box                
             public void onClick(DialogInterface arg0, int arg1)      {                    
                 // the button was clicked                    
                 dialog.dismiss();
                 finish();               
                 }            
             });

         dlgAlert.create().show();



     }

}


}

Connection.java:

package com.nwp;

import android.content.Context;  
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
public class Connection {

public static Context context;
private static Boolean connectedInternet;

public static Boolean isOnline()
{

     new isOnlineAsync().execute(context);
     return Connection.connectedInternet;
}


// Check Internet Connection 
 private static class isOnlineAsync extends AsyncTask<Context, String, Boolean> {

    @Override
    protected Boolean doInBackground(Context... contexts) {

        try {
            ConnectivityManager cm = (ConnectivityManager) contexts[0].getSystemService(Context.CONNECTIVITY_SERVICE); 
            NetworkInfo netInfo = cm.getActiveNetworkInfo(); 
            boolean OnlineState = netInfo != null && netInfo.isConnected();
            return OnlineState;
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            return false;
        }

    }

    @Override
    protected void onPostExecute(Boolean result) {
      super.onPostExecute(result);

      Connection.connectedInternet = result;



    }  

 }


}

2 个答案:

答案 0 :(得分:2)

这是你的问题:

 new isOnlineAsync().execute(context);
 return Connection.connectedInternet;

这两行一个接一个地运行,AsyncTask异步运行(惊讶,惊讶)。这意味着在Connection.connectedInternet完成之前调用AsyncTask。我能想到的最简单的处理方法是让AsyncTask成为Activity的内部类,并在if(!Connection.isOnline())中执行onPostExecute等内容。如果要在许多地方重用AsyncTask,可能需要在将被调用的构造函数中传递回调。

<强>更新

实际上,在回过头来之后,对我来说没有通过回调是有道理的,而只是将其烘焙到AsyncTask中。而不是做:

new isOnlineAsync().execute(context);

做的:

new isOnlineAsync(){
    protected void onPostExecute(String result)
    {
        super.onPostExecute(result);

        if(!Connection.isOnline())
        {
            // ...   
        }
    }
}.execute(context);

就像旁注一样,用大写字母开始你的课程,所以称之为IsOnlineAsync而不是isOnlineAsync

答案 1 :(得分:1)

private class BackgroundTask extends AsyncTask<String,Void,String> 
    {
        private ProgressDialog progress;
        private Context context;
        public BackgroundTask(Context context) 
        {
            this.context=context;
            progress=new ProgressDialog(context);
        }
        @Override
        protected String doInBackground(String... params) 
        {
                        ConnectivityManager connectivity = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
        if (connectivity == null) 
        {
            //boitealerte(this.getString("No Internet Connection"),"getSystemService rend null");
        }
        else
        {
            NetworkInfo[] info = connectivity.getAllNetworkInfo();
            if (info != null) 
            {
                for (int i = 0; i < info.length; i++) 
                {
                    if (info[i].getState() == NetworkInfo.State.CONNECTED) 
                    {
                        return true;
                    }
                 }
            }
        }
        return false;
          }
     protected void onPreExecute()
        {
            progress.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
            progress = ProgressDialog.show(context, "Checking...", "Please Wait", true,true);
        }
        protected void onPostExecute(String result)
        {
            progress.dismiss();
            Toast.makeText(Update.this,"Show result here",Toast.LENGTH_LONG).show();
            Update.this.finish();
        }

你可以从onPostExecute()返回false,然后在调用类中检查它,并根据返回值显示警告对话框。