我想让我的应用看起来更专业,所以我决定添加一个启动画面。
我应该如何进行实现呢?
我想让我的应用看起来更专业,所以我决定添加一个启动画面。
我应该如何进行实现呢?
当前回答
注意这个解决方案不会让用户等待更长的时间:启动画面的延迟取决于应用程序的启动时间。
当你打开任何android应用程序时,默认情况下你会看到一个黑屏,上面是应用程序的标题和图标,你可以通过使用样式/主题来改变这种情况。
首先,在values文件夹中创建一个style.xml,并向其添加一个样式。
<style name="splashScreenTheme" parent="@android:style/Theme.DeviceDefault.Light.NoActionBar">
<item name="android:windowBackground">@drawable/splash_screen</item>
</style>
而不是使用@android:style/Theme.DeviceDefault.Light。NoActionBar你可以使用任何其他主题作为父主题。
其次,在你的应用Manifest.xml中添加android:theme="@style/splashScreenTheme"到你的主活动。
<activity
android:name="MainActivity"
android:label="@string/app_name"
android:theme="@style/splashScreenTheme" >
第三,在onCreate()启动活动中更新主题。
protected void onCreate(Bundle savedInstanceState) {
// Make sure this is before calling super.onCreate
setTheme(R.style.mainAppTheme);
super.onCreate(savedInstanceState);
}
更新 看看这篇文章。
感谢@mat1h和@adelriosantiago
其他回答
在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);
}
}
一个超级灵活的启动屏幕如何,可以使用相同的代码,并在AndroidManifest.xml中定义,因此代码永远不需要更改。我通常开发代码库,不喜欢定制代码,因为它很草率。
<activity
android:name=".SplashActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data android:name="launch_class" android:value="com.mypackage.MyFirstActivity" />
<meta-data android:name="duration" android:value="5000" />
</activity>
然后SpashActivity本身查找“launch_class”的元数据,然后创建Intent本身。元数据“持续时间”定义了启动画面持续的时间。
public class SplashActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.activity_splash);
ComponentName componentName = new ComponentName(this, this.getClass());
try {
Bundle bundle = null;
bundle = getPackageManager().getActivityInfo(componentName, PackageManager.GET_META_DATA).metaData;
String launch_class = bundle.getString("launch_class");
//default of 2 seconds, otherwise defined in manifest
int duration = bundle.getInt("duration", 2000);
if(launch_class != null) {
try {
final Class<?> c = Class.forName(launch_class);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
Intent intent = new Intent(SplashActivity.this, c);
startActivity(intent);
finish();
}
}, duration);
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
} catch (PackageManager.NameNotFoundException e) {
e.printStackTrace();
}
}
}
启动画面不应该从布局文件加载,加载时可能仍然有一些延迟。
最好的方法是为你的SplashScreenActivity创建一个主题,并设置android:windowBackground为一个可绘制的资源。
https://www.bignerdranch.com/blog/splash-screens-the-right-way/
简而言之:
在manifest中声明你的SplashScreenActivity:
<activity
android:name=".activities.SplashScreenActivity"
android:theme="@style/SplashTheme"
android:screenOrientation="portrait">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
在SplashScreenActivity.java中:
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = new Intent(this, MainActivity_.class);
startActivity(intent);
finish();
}
接下来创建主题背景窗口的资源:
<style name="SplashTheme" parent="Theme.Bumpfie.Base">
<item name="android:windowBackground">@drawable/splash</item>
</style>
可绘制文件splash.xml:
<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="@android:color/white"/>
<item>
<bitmap
android:gravity="center"
android:src="@drawable/app_logo"/>
</item>
</layer-list>
Create an Activity SplashScreen.java public class SplashScreen extends Activity { protected boolean _active = true; protected int _splashTime = 3000; // time to display the splash screen in ms @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.splashscreen); Thread splashTread = new Thread() { @Override public void run() { try { int waited = 0; while (_active && (waited < _splashTime)) { sleep(100); if (_active) { waited += 100; } } } catch (Exception e) { } finally { startActivity(new Intent(SplashScreen.this, MainActivity.class)); finish(); } }; }; splashTread.start(); } } splashscreen.xml will be like this <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="600px" android:layout_height="1024px" android:background="#FF0000"> </RelativeLayout>