Android启动画面与服务器通信

发布于 2024-12-27 20:04:15 字数 1968 浏览 0 评论 0原文

我正在android中开发一个应用程序,我需要在其中显示启动屏幕,同时会有服务器通信。这里的问题是当我启动应用程序时,第一个应用程序与服务器通信,然后显示启动屏幕。我想同时进行服务器通信和启动画面。

以下是我的代码:

 protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.splash_screen);

    try {

        Thread thread = new Thread(this);

        thread.start();

        thread.join();

        //Attractions
        CommonMethods.getSystemOutput("Response Json Array String Attractions:::"+jArrayMobileAttractions);

        attractionsDate = JsonParsing.getLatestDate(jArrayMobileAttractions);

        attractionsDate = getDate(attractionsDate);

        CommonMethods.getSystemOutput("Attractions Date:::::"+attractionsDate);

        //Categories
        CommonMethods.getSystemOutput("Response Json Array String Categories:::"+jArrayCategories);

        categoryDate = JsonParsing.getLatestDate(jArrayCategories);

        categoryDate = getDate(categoryDate);

        CommonMethods.getSystemOutput("Category date:::"+categoryDate);

        //Contacts
        CommonMethods.getSystemOutput("Response Json Array String Contacts:::"+jArrayContacts);

        contactsDate = JsonParsing.getLatestDate(jArrayContacts);

        contactsDate = getDate(contactsDate);

        CommonMethods.getSystemOutput("Contacts Date:::"+contactsDate);

    } catch (Exception e) {

        CommonMethods.getSystemOutput("Exception in Splash screen thread:::"+e);
    }

}

public void run() {

//      if (attractionsDate == null) {

        jArrayMobileAttractions = RequestHandler.getJSONfromURL(Constants.MOBILE_ATTRACTIONS_URL);

        jArrayCategories = RequestHandler.getJSONfromURL(Constants.CATEGORY_URL);

        jArrayContacts = RequestHandler.getJSONfromURL(Constants.CONTACTS_URL);


//      } else {

//          jArrayMobileAttractions = RequestHandler.getJSONfromURL(Constants.MOBILE_ATTRACTIONS_URL+"?lastupdateddate="+attractionsDate);

//      }

}

I am developing an application in android, where i need to display a splash screen and at the same time there will be server communication. The problem here is when i launch the app, first application is communicating with the server and then it is displaying the splash screen. I want to both server communication and splash screen at the same time.

The following is my code:

 protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.splash_screen);

    try {

        Thread thread = new Thread(this);

        thread.start();

        thread.join();

        //Attractions
        CommonMethods.getSystemOutput("Response Json Array String Attractions:::"+jArrayMobileAttractions);

        attractionsDate = JsonParsing.getLatestDate(jArrayMobileAttractions);

        attractionsDate = getDate(attractionsDate);

        CommonMethods.getSystemOutput("Attractions Date:::::"+attractionsDate);

        //Categories
        CommonMethods.getSystemOutput("Response Json Array String Categories:::"+jArrayCategories);

        categoryDate = JsonParsing.getLatestDate(jArrayCategories);

        categoryDate = getDate(categoryDate);

        CommonMethods.getSystemOutput("Category date:::"+categoryDate);

        //Contacts
        CommonMethods.getSystemOutput("Response Json Array String Contacts:::"+jArrayContacts);

        contactsDate = JsonParsing.getLatestDate(jArrayContacts);

        contactsDate = getDate(contactsDate);

        CommonMethods.getSystemOutput("Contacts Date:::"+contactsDate);

    } catch (Exception e) {

        CommonMethods.getSystemOutput("Exception in Splash screen thread:::"+e);
    }

}

public void run() {

//      if (attractionsDate == null) {

        jArrayMobileAttractions = RequestHandler.getJSONfromURL(Constants.MOBILE_ATTRACTIONS_URL);

        jArrayCategories = RequestHandler.getJSONfromURL(Constants.CATEGORY_URL);

        jArrayContacts = RequestHandler.getJSONfromURL(Constants.CONTACTS_URL);


//      } else {

//          jArrayMobileAttractions = RequestHandler.getJSONfromURL(Constants.MOBILE_ATTRACTIONS_URL+"?lastupdateddate="+attractionsDate);

//      }

}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(3

久而酒知 2025-01-03 20:04:15

您可以使用 AsynchTask Manager,其中有一个方法

 private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        // Do Server Interaction Here
        return response;
    }


@Override
    protected void onPreExecute(String result) {
        //Show your Splash Screen  
    }

    @Override
    protected void onPostExecute(String result) {
        //Gone the Splash Screen view
    }
}

You can use the AsynchTask Manager in which it has a method

 private class DownloadWebPageTask extends AsyncTask<String, Void, String> {
    @Override
    protected String doInBackground(String... urls) {
        // Do Server Interaction Here
        return response;
    }


@Override
    protected void onPreExecute(String result) {
        //Show your Splash Screen  
    }

    @Override
    protected void onPostExecute(String result) {
        //Gone the Splash Screen view
    }
}
牛↙奶布丁 2025-01-03 20:04:15

为此,最好从“SplashActivity”开始 - 在 onCreate() 中启动新的 Thread 与服务器通信,当所有通信完成时 - 调用 startActivityForResult (mainActivityIntent)。为了正确的行为,后退按钮在完成主要活动时完成启动活动。大概代码:

public class SplashActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setup view for activity
        new Thread(new Runnable() {
            public void run() {
                // do here some long operation

                startActivityForResult(new Intent(SplashActivity.this, MainActivity.class), 0);
            }
        }).start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        finish();
    }
}

For this purpose it will be better start from "SplashActivity" - in onCreate() start new Thread for communication with server, and when all communication finished - call startActivityForResult(mainActivityIntent). For correct behavior back button finish splash activity on finish main activity. Approximate code:

public class SplashActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //setup view for activity
        new Thread(new Runnable() {
            public void run() {
                // do here some long operation

                startActivityForResult(new Intent(SplashActivity.this, MainActivity.class), 0);
            }
        }).start();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        finish();
    }
}
我不在是我 2025-01-03 20:04:15

我也有同样的事情要做,我就是这样做的,而且效果很好。我必须显示启动画面并从服务器下载一些文件,解压缩,将文件移动到正确的目录中,然后启动应用程序主屏幕。这是代码,我使用了AsyncTask。

因此,您有三个 AsyncTask 类,每个任务一个,在 onPostExecute() 中我调用下一个 AsyncTask。我不能说这是否是最好的方法,但它对我有用。

我删除了不必要的代码,但为了清楚起见,我留下了一个对对话框的调用,在该对话框中我询问用户他是否想要继续下载,因为这可能需要一段时间。另外,我检查 FIRST_RUN 是否为 true,这样我就知道是否应该下载该软件包,因为对于我的应用程序,我只需要第一次执行此操作,因此,如果为 true,则执行闪屏活动,如果为 false,则继续执行 MAINAPP活动。

希望有帮助。

public class SplashScreen extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splashscreen);

    SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
    boolean firstRun = settings.getBoolean("FIRST_RUN", true);
    if (firstRun) {
        showDialog(INITIAL_DLG);
    } else {
        startActivity(new Intent(appContext, MAINAPP.class));
    }
}

/***
 * First entry after YES on Dialog!
 */
protected void initialize() {
    messageTV.setVisibility(TextView.VISIBLE);
    progressBar.setVisibility(ProgressBar.VISIBLE);
    downloadThread = new DownloadFiles();
    downloadThread.execute();
}

protected void rollback() {

}

@Override
protected Dialog onCreateDialog(int id) {
    AlertDialog.Builder builder;
    switch (id) {
    case INITIAL_DLG:
        builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.app_setup)
        .setCancelable(false)
        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                initialize();
            }
        })
        .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        alertDlg = builder.create();
        return alertDlg;
    default:
        return null;    
    }
}

protected class DownloadFiles extends AsyncTask<String, Integer, Boolean> {

    @Override
    protected Boolean doInBackground(String... params) {
        try {
            //file download
        } catch (Exception e) {
            result = false;
        }
        return true;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressBar.setProgress(values[0]);
    }

    @Override
    protected void onPostExecute(Boolean result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        unzipThread = new DecompressZipFile();
        unzipThread.execute();
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        messageTV.setText("Step 1/4:Downloading data...");
        progressBar.setProgress(0);
        progressBar.setMax(100);
        super.onPreExecute();
    }
}

protected class DecompressZipFile extends AsyncTask<String, Integer, Boolean> {
    @Override
    protected Boolean doInBackground(String... params) {
        try {
            //unzip files
            return true;    
        } catch(Exception e) {
            return false;
        }
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        if (values[0]<0) progressBar.setMax(values[0]*-1);
        else progressBar.setProgress(values[0]);
    }

    @Override
    protected void onPostExecute(Boolean result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        moveDBThread = new MoveDBFile();
        moveDBThread.execute();
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        messageTV.setText("Step 2/4:Decompressing data...");
        progressBar.setProgress(0);
        progressBar.setMax(100);
        super.onPreExecute();
    }
}

protected class MoveDBFile extends AsyncTask<String, Integer, Boolean> {
    @Override
    protected Boolean doInBackground(String... params) {
        try {
            //moving files
            return true;
        } catch (Exception e) {
            globalE = e;
            finish();
            return false;
        }
    }

    @Override
    protected void onPreExecute() {
        messageTV.setText("Step 3/4:Shufflin'...");
        progressBar.setProgress(0);
        progressBar.setMax(100);
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressBar.setProgress(values[0]);
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        if (result) {
            getSharedPreferences(PREFS_NAME,0).edit().putBoolean("FIRST_RUN", false).commit();
            startActivity(new Intent(appContext, MAINAPP.class));
        } else {
            rollback();
        }
    }
}

}

I had the same thing to do and I did it this way and it works just fine. I had to show the splashscreen and download some file from the server, unzip it, move files insto proper directories and then start the apps main screen. Here is the code, I used AsyncTask.

So, you have three AsyncTask classes, one for each task and in the onPostExecute() I call the next AsyncTask. I can't say if this is the best way but it works for me.

I removed unneccessary code but for clarity I left a call to a dialog where I ask a user ih he wants to proceed with downloading as it may take a while. Also I check if FIRST_RUN is true just so I know if I should download the package since for my app I need to do it only the first time, so if it is true I do the spashscreen activities and if it is false I proceed to MAINAPP activity.

Hope it helps.

public class SplashScreen extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.splashscreen);

    SharedPreferences settings = getSharedPreferences(PREFS_NAME,0);
    boolean firstRun = settings.getBoolean("FIRST_RUN", true);
    if (firstRun) {
        showDialog(INITIAL_DLG);
    } else {
        startActivity(new Intent(appContext, MAINAPP.class));
    }
}

/***
 * First entry after YES on Dialog!
 */
protected void initialize() {
    messageTV.setVisibility(TextView.VISIBLE);
    progressBar.setVisibility(ProgressBar.VISIBLE);
    downloadThread = new DownloadFiles();
    downloadThread.execute();
}

protected void rollback() {

}

@Override
protected Dialog onCreateDialog(int id) {
    AlertDialog.Builder builder;
    switch (id) {
    case INITIAL_DLG:
        builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.app_setup)
        .setCancelable(false)
        .setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                initialize();
            }
        })
        .setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                finish();
            }
        });
        alertDlg = builder.create();
        return alertDlg;
    default:
        return null;    
    }
}

protected class DownloadFiles extends AsyncTask<String, Integer, Boolean> {

    @Override
    protected Boolean doInBackground(String... params) {
        try {
            //file download
        } catch (Exception e) {
            result = false;
        }
        return true;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressBar.setProgress(values[0]);
    }

    @Override
    protected void onPostExecute(Boolean result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        unzipThread = new DecompressZipFile();
        unzipThread.execute();
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        messageTV.setText("Step 1/4:Downloading data...");
        progressBar.setProgress(0);
        progressBar.setMax(100);
        super.onPreExecute();
    }
}

protected class DecompressZipFile extends AsyncTask<String, Integer, Boolean> {
    @Override
    protected Boolean doInBackground(String... params) {
        try {
            //unzip files
            return true;    
        } catch(Exception e) {
            return false;
        }
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        if (values[0]<0) progressBar.setMax(values[0]*-1);
        else progressBar.setProgress(values[0]);
    }

    @Override
    protected void onPostExecute(Boolean result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        moveDBThread = new MoveDBFile();
        moveDBThread.execute();
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        messageTV.setText("Step 2/4:Decompressing data...");
        progressBar.setProgress(0);
        progressBar.setMax(100);
        super.onPreExecute();
    }
}

protected class MoveDBFile extends AsyncTask<String, Integer, Boolean> {
    @Override
    protected Boolean doInBackground(String... params) {
        try {
            //moving files
            return true;
        } catch (Exception e) {
            globalE = e;
            finish();
            return false;
        }
    }

    @Override
    protected void onPreExecute() {
        messageTV.setText("Step 3/4:Shufflin'...");
        progressBar.setProgress(0);
        progressBar.setMax(100);
        super.onPreExecute();
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        super.onProgressUpdate(values);
        progressBar.setProgress(values[0]);
    }

    @Override
    protected void onPostExecute(Boolean result) {
        super.onPostExecute(result);
        if (result) {
            getSharedPreferences(PREFS_NAME,0).edit().putBoolean("FIRST_RUN", false).commit();
            startActivity(new Intent(appContext, MAINAPP.class));
        } else {
            rollback();
        }
    }
}

}

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文