Android Splash Activity Demo


效果图:

  


首先,  在drawable下放入XML splash_animation.xml


	
	
	
	

建立 splash_view.xml




    
    

    




建立 SplashDemoActivity

public class SplashDemoActivity extends Activity {
	public final static String tag = SplashDemoActivity.class.getSimpleName();
	public final static int SPLASH_DURATION = 2000;
	private ImageView imageView = null;	
	private AnimationDrawable animationDrawable = null;	
	private boolean isPressBack = false;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.splash_view);

		imageView = (ImageView) findViewById(R.id.wait_image_view);
		imageView.setBackgroundResource(R.drawable.splash_animation);
		animationDrawable = (AnimationDrawable) imageView.getBackground();
		 
	}

	protected void onResume() {
		super.onResume();
		// 开始动画 -- 用在此处,不能保证每次动画都行运行,
		//because the AnimationDrawable is not yet fully attached to the window
		//startSplashAnimation(SPLASH_DURATION);
	}
	
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		if (hasFocus) {
			// 开始动画
			startSplashAnimation(SPLASH_DURATION);
		}
	}

	/**
	 * Description: Run the splash screen for given time limit
	* @param limit
	 */
	protected void startSplashAnimation(final int limit) {
		Thread splashThread = new Thread() {
			@Override
			public void run() {
				try {	
					//Thread.currentThread().sleep(50);//
					//不能在onCreate中立即执行,because the AnimationDrawable is not yet fully attached to the window
					animationDrawable.start();
					int waited = 0;
					while (waited < limit) {
						sleep(100);
						waited += 100;
					}
				} catch (Exception e) {
					Log.w(tag, e.getMessage().toString());
					finish();
				} finally {
					if (!isPressBack) {//解决在SPLASH_DURATION期间内, 用户点击back键,应用会在再次自动重启						
						forwardActivity();
					}
				}
			}
		};
		splashThread.start();
	}

	@Override
	protected void onDestroy() {
		super.onDestroy();
		imageView = null;
		animationDrawable = null;
	}

	public boolean onKeyDown(int keyCode, KeyEvent event) {
		if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0){
			isPressBack = true;
			finish();
			return true;
		}
		return false;
	}
	
	private void forwardActivity(){
		Intent intent = new Intent(SplashDemoActivity.this, MainActivity.class);
		intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
		startActivity(intent);
		
		finish();
		//SplashDemoActivity.this.overridePendingTransition(R.anim.translucent_enter, R.anim.translucent_exit);
		//SplashDemoActivity.this.overridePendingTransition(R.anim.fade, R.anim.hold);
		//这个overridePendingTransition效果经常不好使, 不知为何???
		overridePendingTransition(R.anim.zoom_enter, R.anim.zoom_exit);
	}
		
}

zoom_enter.xml



    

zoom_exit.xml



    
    





你可能感兴趣的:(Android)