我想让我的应用看起来更专业,所以我决定添加一个启动画面。

我应该如何进行实现呢?


当前回答

有时用户打开SplashActivity并立即退出,但应用程序仍然在SPLASH_SCREEN_DISPLAY_LENGTH后转到MainActivity。

为了防止它:在SplashActivity中,你应该在移动到MainActivity之前检查SplashActivity是否结束

public class SplashActivity extends Activity {

    private final int SPLASH_SCREEN_DISPLAY_LENGTH = 2000;

    @Override
    public void onCreate(Bundle icicle) {
        ...
        new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {

                if (!isFinishing()) {//isFinishing(): If the activity is finishing, returns true; else returns false.
                    startActivity(new Intent(SplashActivity.this, MainActivity.class));
                    finish();
                }

            }, SPLASH_SCREEN_DISPLAY_LENGTH);
        }                             
   }                                
}

希望这对你有所帮助

其他回答

启动画面示例:

public class MainActivity extends Activity {
    private ImageView splashImageView;
    boolean splashloading = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        splashImageView = new ImageView(this);
        splashImageView.setScaleType(ScaleType.FIT_XY);
        splashImageView.setImageResource(R.drawable.ic_launcher);
        setContentView(splashImageView);
        splashloading = true;
        Handler h = new Handler();
        h.postDelayed(new Runnable() {
            public void run() {
                splashloading = false;
                setContentView(R.layout.activity_main);
            }

        }, 3000);

    }

}

在Kotlin中编写以下代码:-

 Handler().postDelayed({
            val mainIntent = Intent(this@SplashActivity, LoginActivity::class.java)
            startActivity(mainIntent)
            finish()
        }, 500)

希望这对你有所帮助,谢谢........

在Android Marshmallow之后,我想到的另一个有效使用启动画面的方法是在应用的启动画面中请求必要的Android权限。

似乎大多数应用程序都是这样处理权限请求的。

对话框是糟糕的ui,它们破坏了主要流程,让你决定运行时间,事实上,大多数用户甚至可能不在乎你的应用程序是否想在SD卡上写东西。他们中的一些人甚至不明白我们试图传达什么,直到我们用简单的英语翻译出来。 一次请求权限可以减少每次操作前的“if else”次数,使代码看起来不那么杂乱。

这是一个例子,你可以在你的splash活动中请求运行Android OS 23+的设备的权限。

如果所有权限都被授予或已经授予或应用程序正在Pre Marshmallow上运行,那么只需去显示主要内容,几乎半秒的延迟,以便用户可以欣赏我们在阅读这个问题时所付出的努力,并试图给予我们最好的。

import android.Manifest;
import android.annotation.TargetApi;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.widget.Toast;

import com.c2h5oh.beer.R;
import com.c2h5oh.beer.utils.Animatrix;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SplashActivity extends AppCompatActivity {

    final private int REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS = 124;

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

        //show animations 
        Animatrix.scale(findViewById(R.id.title_play), 100);
        Animatrix.scale(findViewById(R.id.title_edit), 100);
        Animatrix.scale(findViewById(R.id.title_record), 100);
        Animatrix.scale(findViewById(R.id.title_share), 100);

        if (Build.VERSION.SDK_INT >= 23) {

            // Marshmallow+ Permission APIs
            fuckMarshMallow();

        } else {

            // Pre-Marshmallow
            ///Display main contents
            displaySplashScreen();
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        switch (requestCode) {
            case REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS: {
                Map<String, Integer> perms = new HashMap<String, Integer>();
                // Initial
                perms.put(Manifest.permission.READ_EXTERNAL_STORAGE, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.RECORD_AUDIO, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.MODIFY_AUDIO_SETTINGS, PackageManager.PERMISSION_GRANTED);
                perms.put(Manifest.permission.VIBRATE, PackageManager.PERMISSION_GRANTED);
                // Fill with results
                for (int i = 0; i < permissions.length; i++)
                    perms.put(permissions[i], grantResults[i]);

                // Check for ACCESS_FINE_LOCATION
                if (perms.get(Manifest.permission.READ_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.RECORD_AUDIO) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.MODIFY_AUDIO_SETTINGS) == PackageManager.PERMISSION_GRANTED
                        && perms.get(Manifest.permission.VIBRATE) == PackageManager.PERMISSION_GRANTED) {
                    // All Permissions Granted

                    // Permission Denied
                    Toast.makeText(SplashActivity.this, "All Permission GRANTED !! Thank You :)", Toast.LENGTH_SHORT)
                            .show();

                    displaySplashScreen();

                } else {
                    // Permission Denied
                    Toast.makeText(SplashActivity.this, "One or More Permissions are DENIED Exiting App :(", Toast.LENGTH_SHORT)
                            .show();

                    finish();
                }
            }
            break;
            default:
                super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        }
    }


    @TargetApi(Build.VERSION_CODES.M)
    private void fuckMarshMallow() {
        List<String> permissionsNeeded = new ArrayList<String>();

        final List<String> permissionsList = new ArrayList<String>();
        if (!addPermission(permissionsList, Manifest.permission.READ_EXTERNAL_STORAGE))
            permissionsNeeded.add("Read SD Card");
        if (!addPermission(permissionsList, Manifest.permission.RECORD_AUDIO))
            permissionsNeeded.add("Record Audio");
        if (!addPermission(permissionsList, Manifest.permission.MODIFY_AUDIO_SETTINGS))
            permissionsNeeded.add("Equilizer");
        if (!addPermission(permissionsList, Manifest.permission.VIBRATE))
            permissionsNeeded.add("Vibrate");

        if (permissionsList.size() > 0) {
            if (permissionsNeeded.size() > 0) {

                // Need Rationale
                String message = "App need access to " + permissionsNeeded.get(0);

                for (int i = 1; i < permissionsNeeded.size(); i++)
                    message = message + ", " + permissionsNeeded.get(i);

                showMessageOKCancel(message,
                        new DialogInterface.OnClickListener() {

                            @Override
                            public void onClick(DialogInterface dialog, int which) {
                                requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                                        REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
                            }
                        });
                return;
            }
            requestPermissions(permissionsList.toArray(new String[permissionsList.size()]),
                    REQUEST_CODE_ASK_MULTIPLE_PERMISSIONS);
            return;
        }

        Toast.makeText(SplashActivity.this, "No new Permission Required- Launching App .You are Awesome!!", Toast.LENGTH_SHORT)
                .show();

        displaySplashScreen();
    }


    private void showMessageOKCancel(String message, DialogInterface.OnClickListener okListener) {
        new AlertDialog.Builder(SplashActivity.this)
                .setMessage(message)
                .setPositiveButton("OK", okListener)
                .setNegativeButton("Cancel", null)
                .create()
                .show();
    }

    @TargetApi(Build.VERSION_CODES.M)
    private boolean addPermission(List<String> permissionsList, String permission) {

        if (checkSelfPermission(permission) != PackageManager.PERMISSION_GRANTED) {
            permissionsList.add(permission);
            // Check for Rationale Option
            if (!shouldShowRequestPermissionRationale(permission))
                return false;
        }
        return true;
    }

    /**
     * Display main content with little delay just so that user can see
     * efforts I put to make this page
     */
    private void displaySplashScreen() {
        new Handler().postDelayed(new Runnable() {

        /*
         * Showing splash screen with a timer. This will be useful when you
         * want to show case your app logo / company
         */

            @Override
            public void run() {
                startActivity(new Intent(SplashActivity.this, AudioPlayerActivity.class));
                finish();
            }
        }, 500);
    }


}
public class MainActivity extends Activity {

@Override

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    Thread t=new Thread()
    {

        public void run()
        {   

            try {

                sleep(2000);
                finish();
                Intent cv=new Intent(MainActivity.this,HomeScreen.class/*otherclass*/);
                startActivity(cv);
            } 

            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    };
    t.start();
}

在我的例子中,我不想创建一个新的活动只是为了显示2秒的图像。当启动我的MainActivity,图像被加载到持有者使用毕加索,我知道这需要大约1秒的加载,所以我决定做以下在我的MainActivity OnCreate:

splashImage = (ImageView) findViewById(R.id.spllll);

    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);

    int secondsDelayed = 1;
    new Handler().postDelayed(new Runnable() {
        public void run() {
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
            splashImage.setVisibility(View.GONE);

        }
    }, secondsDelayed * 2000);

当启动应用程序时,发生的第一件事是显示ImageView,并通过将窗口标志设置为全屏来删除状态栏。然后我使用Handler运行2秒,2秒后我清除全屏标志,并设置ImageView的可见性为GONE。简单,简单,有效。