0

我正在开发一个在启动时具有空白默认屏幕的应用程序。我想显示一个启动画面,同时在后台启动主要活动。当主要活动中的某些过程完成时,例如加载 web 视图,然后终止启动屏幕并显示主要活动。

我已经搜索了如何实现启动画面,但所有示例都是延迟几秒钟然后开始主要活动。它们都是结果。

我想在后台启动主要活动,直到创建和构建完成。


我的情况是:

  1. 我的 MainActivity 使用 actionbar 和 pagerAdapter 实现选项卡片段。
  2. 对于每个片段,都有一些 webviews 和 asynctasks 解析 json 等,
  3. 当我启动应用程序时,它首先显示一个带有标题栏的白屏(带有应用程序图标和应用程序名称)。几秒钟后,它变为实际活动(带有选项卡)。
  4. 所以,我猜白屏是默认的加载屏幕。
  5. 我想要的是将白屏替换为全屏图像。
4

4 回答 4

1

可以根据应用程序的要求使用启动画面,例如:

1.下载数据并存储。2.解析json等

当您想为此在后台运行主要活动时,您应该使用 AsyncTask 或 Service:

例如

public class SplashScreen extends Activity {

String now_playing, earned;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_splash);

    /**
     * Showing splashscreen while making network calls to download necessary
     * data before launching the app Will use AsyncTask to make http call
     */
    new PrefetchData().execute();

}

/**
 * Async Task to make http call
 */
private class PrefetchData extends AsyncTask<Void, Void, Void> {

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
        // before making http calls        

    }

    @Override
    protected Void doInBackground(Void... arg0) {
        /*
         * Will make http call here This call will download required data
         * before launching the app
         * example:
         * 1. Downloading and storing in SQLite
         * 2. Downloading images
         * 3. Fetching and parsing the xml / json
         * 4. Sending device information to server
         * 5. etc.,
         */
        JsonParser jsonParser = new JsonParser();
        String json = jsonParser
                .getJSONFromUrl("http://api.androidhive.info/game/game_stats.json");

        Log.e("Response: ", "> " + json);

        if (json != null) {
            try {
                JSONObject jObj = new JSONObject(json)
                        .getJSONObject("game_stat");
                now_playing = jObj.getString("now_playing");
                earned = jObj.getString("earned");

                Log.e("JSON", "> " + now_playing + earned);

            } catch (JSONException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }

        return null;
    }

    @Override
    protected void onPostExecute(Void result) {
        super.onPostExecute(result);
        // After completing http call
        // will close this activity and lauch main activity
        Intent i = new Intent(SplashScreen.this, MainActivity.class);//Here Main activity is the splash screen.
        i.putExtra("now_playing", now_playing);
        i.putExtra("earned", earned);
        startActivity(i);

        // close this activity
        finish();
    }

}

}

有关更多信息,您可以查看在启动画面服务AsyncTask中使用 asynctask 的示例。

如果我理解您的要求,那么您应该查看在启动画面中使用 asynctask 的示例,一次。

上述编码过程:

  1. onCreate setContentView(R.layout.activity_splash); 调用启动画面并调用PrefetchData()
  2. prefetch()中,异步任务在这里执行后台操作,从给定的 url 解析一个 json。
  3. onPostExecute() MainActivity 被调用。提醒 onPostExecute() 在 AsyncTask 中用于表示后台处理已完成,因此在上面的示例中,finish() 函数结束时显示启动画面。

希望它可以帮助你。

于 2013-08-06T04:57:50.003 回答
0

您可以使用处理程序来更新 UI,请参阅以下示例代码。

public class ThreadsLifecycleActivity extends Activity {
  // Static so that the thread access the latest attribute
  private static ProgressDialog dialog;
  private static Bitmap downloadBitmap;
  private static Handler handler;
  private ImageView imageView;
  private Thread downloadThread;


/** Called when the activity is first created. */


  @Override
  public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    // Create a handler to update the UI
    handler = new Handler() {
      @Override
      public void handleMessage(Message msg) {
        imageView.setImageBitmap(downloadBitmap);
        dialog.dismiss();
      }

    };
    // get the latest imageView after restart of the application
    imageView = (ImageView) findViewById(R.id.imageView1);
    Context context = imageView.getContext();
    System.out.println(context);
    // Did we already download the image?
    if (downloadBitmap != null) {
      imageView.setImageBitmap(downloadBitmap);
    }
    // Check if the thread is already running
    downloadThread = (Thread) getLastNonConfigurationInstance();
    if (downloadThread != null && downloadThread.isAlive()) {
      dialog = ProgressDialog.show(this, "Download", "downloading");
    }
  }

  public void resetPicture(View view) {
    if (downloadBitmap != null) {
      downloadBitmap = null;
    }
    imageView.setImageResource(R.drawable.icon);
  }

  public void downloadPicture(View view) {
    dialog = ProgressDialog.show(this, "Download", "downloading");
    downloadThread = new MyThread();
    downloadThread.start();
  }

  // Save the thread
  @Override
  public Object onRetainNonConfigurationInstance() {
    return downloadThread;
  }

  // dismiss dialog if activity is destroyed
  @Override
  protected void onDestroy() {
    if (dialog != null && dialog.isShowing()) {
      dialog.dismiss();
      dialog = null;
    }
    super.onDestroy();
  }

  // Utiliy method to download image from the internet
  static private Bitmap downloadBitmap(String url) throws IOException {
    HttpUriRequest request = new HttpGet(url);
    HttpClient httpClient = new DefaultHttpClient();
    HttpResponse response = httpClient.execute(request);

    StatusLine statusLine = response.getStatusLine();
    int statusCode = statusLine.getStatusCode();
    if (statusCode == 200) {
      HttpEntity entity = response.getEntity();
      byte[] bytes = EntityUtils.toByteArray(entity);

      Bitmap bitmap = BitmapFactory.decodeByteArray(bytes, 0,
          bytes.length);
      return bitmap;
    } else {
      throw new IOException("Download failed, HTTP response code "
          + statusCode + " - " + statusLine.getReasonPhrase());
    }
  }

  static public class MyThread extends Thread {
    @Override
    public void run() {
      try {
        // Simulate a slow network
        try {
          new Thread().sleep(5000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
        downloadBitmap = downloadBitmap("http://www.devoxx.com/download/attachments/4751369/DV11");
        // Updates the user interface
        handler.sendEmptyMessage(0);
      } catch (IOException e) {
        e.printStackTrace();
      } finally {

      }
    }
  }

} 
于 2013-08-06T04:52:53.443 回答
0

一个活动就是一个屏幕。您不能在后台运行活动。请改用服务AsyncTasks

由于我不开发游戏,因此我对启动画面没有太多经验,但是您似乎正在寻找更多的加载屏幕而不是启动屏幕。然而,我的猜测是你可以启动一个 AsyncTask,给它一些变量,比如“progress”,然后设置一个计时器每隔几秒检查一次。

在 SO 上快速搜索“加载屏幕”会得到更多结果。

于 2013-08-06T04:45:55.533 回答
0

使用AsyncTask类。并覆盖一些方法,如 -

onPreExecute(); //For loading splash screen
doInBackground();//For loading content-
onPostExecute();//for close splash screen & start new activty.
于 2013-08-06T04:47:16.760 回答