这一篇文章专门整理一下研究过的Android面试题,内容会随着学习不断的增加,如果答案有错误,希望大家可以指正
1.简述Activity的生命周期
当Activity开始启动的时候,首先调用onCreate(),onStart(),onResume()方法,此时Activity对用户来说,是可见的状态
当Activity从可见状态变为被Dialog遮挡的状态的时候,会调用onPause()方法,此时的Activity对用户可见,但是不能相
应用户的点击事件
当Activity从可见状态变为被其他的Activity完全覆盖或者是点击Home进入后台的时候,会依次调用onPause(),onStop()方法,如果在这个期间,系统内存不足,导致Activity被回收的话,还会调用onDestory()方法
当Activity从被Dialog遮挡的状态恢复的时候,会调用onResume()方法,从而恢复可以点击的状态
当Activity从被其他Activity遮挡或者是进入后台状态恢复,而且没有被系统回收的时候,会依次调用onRestart(),onStart(),onResume(),恢复到可以与用户进行交互的状态
当Activity从被其他Activity遮挡或者进入后台,而且被系统回收的时候,相当于重新打开一个Activity,既调用onCreate(),onStart(),onResume()方法,从而可以与用户进行交互
在onPause()方法执行后,系统会停止动画等消耗 CPU 的操作,同时我们应该在这里保存数据,因为这个时候程序的优先级降低,有可能被系统收回。在这里保存的数据,应该在 onResume 里读出来,帮用户恢复之前的状态。
在onDestroy()执行后,activity就被真的
干掉,可以用 isFinishing()来判断它,如果此时有 Progress Dialog显示,我们应该在onDestroy()里 cancel 掉,否则线程结束的时候,调用Dialog 的 cancel 方法会抛异常。
2.Intent启动Activity有几种方式,如何实现?
Intent启动Activity有两种方式,分别为显式意图,隐式意图
第一种,显示意图的实现。
- Intent intent = new Intent(this,OtherActivity.class);
- startActivity(intent);
- Intent intent = new Intent();
- ComponentName component = new ComponentName(this, OtherActivity.class);
- intent.setComponent(component);
- startActivity(intent);
- public Intent(Context packageContext, Class<?> cls) {
- mComponent = new ComponentName(packageContext, cls);
- }
第二种,是隐式意图的实现。
首先我们看一下隐式意图的调用方式
- Intent intent = new Intent();
- intent.setAction("other");
- startActivity(intent);
- <activity android:name="com.example.lifecicledemo.OtherActivity" >
- <intent-filter>
- <action android:name="other" />
- <category android:name="android.intent.category.DEFAULT" />
- </intent-filter>
- </activity>
这样当我们使用setAction的时候,就可以知道我们到底是想跳转到哪一个页面了。
3.Android中获取图片有哪几种方式
方式一
- Drawable drawable = getResources().getDrawable(R.drawable.ic_launcher);
- img.setImageDrawable(drawable);
方式二
- Bitmap bitmap = BitmapFactory.decodeResource(getResources(),
- R.drawable.ic_launcher);
- img.setImageBitmap(bitmap);
方式三
- AssetManager assetManager = getResources().getAssets();
- try {
- InputStream is = assetManager.open("ic_launcher.png");
- Bitmap bitmap = BitmapFactory.decodeStream(is);
- img.setImageBitmap(bitmap);
- } catch (IOException e) {
- e.printStackTrace();
- }
方式四
- AssetManager assetManager = getResources().getAssets();
- try {
- InputStream is = assetManager.open("ic_launcher.png");
- Drawable drawable = Drawable.createFromStream(is, null);
- img.setImageDrawable(drawable);
- } catch (IOException e) {
- e.printStackTrace();
- }