Android面试题【初级工程师版】

Android 基础(2016.01.20 更新)(★★).
一、 Activity
1、 什么是 Activity?
2、 请描述一下 Activity 生命周期
3、 常见的 Activity 类型
4、 如何保存 Activity 的状态?
5、 两个 Activity 之间跳转时必然会执行的是哪几个方法?
6、 横竖屏切换时 Activity 的生命周期
7、 如何将一个 Activity 设置成窗口的样式
8、 如何退出 Activity?如何安全退出已调用多个 Activity 的Application?
9、 Activity 的四种启动模式
10、 Android 中的 Context, Activity,Appliction 有什么区别?
11、 两个 Activity 之间传递数据,除了 intent,广播接收者,content provider 还有啥?

12、 Context是什么?
13、 如果后台的 Activity 由于某原因被系统回收了,如何在被系统回收之前保存当前状态?
14、你后台的 Activity 被系统回收怎么办?【较难】
15、怎么在启动一个 Activity 时就启动一个 service?
16、同一个程序,但不同的 Activity 是否可以放在不同的 Task 任务栈中?
17  Activity 怎么和 service 绑定,怎么在 activity 中启动自己对应的 service? 


二、 Service
1、 Service 是否在 main thread 中执行, service 里面是否能执行耗时的操作?
2、 Activity 怎么和Service 绑定,怎么在 Activity 中启动自己对应的 Service?
3、 请描述一下 Service 的生命周期
4、 什么是 IntentService?有何优点?
5、 说说 Activity、Intent、Service 是什么关系
6、 Service 和 Activity 在同一个线程吗
7、 Service 里面可以弹吐司么
8、 什么是 Service 以及描述下它的生命周期。Service 有哪些启动方法,有什么区别,怎样停用 Service?

9、 在 service 的生命周期方法 onstartConmand()可不可以执行网络操作?如何在 service 中执行网络操作?
10 不用 service,B 页面为音乐播放, 跳转到 B,再返回,如何使音乐继续播放11  什么时候使用 Service?


三、 Broadcast Receiver
1、 请描述一下 BroadcastReceiver
2、 在 manifest 和代码中如何注册和使用 BroadcastReceiver
3、 BroadCastReceiver的生命周期
四、 ContentProvider
1、 请介绍下 ContentProvider 是如何实现数据共享的
2、 请介绍下 Android 的数据存储方式
3、 为什么要用 ContentProvider?它和sql 的实现上有什么差别?
4、 说说 ContentProvider、ContentResolver、ContentObserver 之间的关系


五、 ListView
1、 ListView 如何提高其效率?
2、 当 ListView 数据集改变后,如何更新 ListView.
3、 ListView 如何实现分页加载
4、 ListView 可以显示多种类型的条目吗
5、 ListView 如何定位到指定位置
6、 如何在 ScrollView 中如何嵌入 ListView
7、 ListView 中如何优化图片
8、 ListView 中图片错位的问题是如何产生的
9、 如何刷新 ListView 中单个 item 的数据,不刷新整个ListView 的数据?


六、 Intent
1、 Intent 传递数据时,可以传递哪些类型数据?
2、 Serializable 和 Parcelable 的区别
3、 请描述一下 Intent 和 IntentFilter
七、 Fragment
1、 Fragment 跟 Activity 之间是如何传值的
2、 描述一下 Fragment 的生命周期
3、 Fragment 的 replace 和 add 方法的区别
4、 Fragment 如何实现类似 Activity 栈的压栈和出栈效果的?
5、 Fragment 在你们项目中的使用
6、 如何切换 fragement,不重新实例化



一、 Activity
1、什么是Activity?
四大组件之一,一般的,一个用户交互界面对应一个 activity
setContentView() ,// 要显示的布局
button.setOnclickLinstener{
}, activity 是Context的子类,同时实现了window.callback和keyevent.callback, 可以处理与窗体
用户交互的事件.
我开发常用的的有FragmentActivitiyListActivity ,PreferenceActivity ,TabAcitivty 等…


2、请描述一下 Activity 生命周期
Activity 从创建到销毁有多种状态,从一种状态到另一种状态时会激发相应的回调方法,这些回
调方法包括:onCreate onStart onResume onPause onStop onDestroy
其实这些方法都是两两对应的,onCreate创建与 onDestroy 销毁;
onStart 可见与onStop 不可见;onResume可编辑(即焦点)与onPause;
如果界面有共同的特点或者功能的时候,还会自己定义一个 BaseActivity.
进度对话框的显示与销毁


3、常 见 的 Activity 类 型 有 FragmentActivitiy , ListActivity ,
TabAcitivty 等。请描述一下Activity 生命周期
Activity 从创建到销毁有多种状态,从一种状态到另一种状态时会激发相应的回调方法,这些回调方法包括:onCreate onStart onResume onPause onStop onDestroy
其实这些方法都是两两对应的,onCreate创建与 onDestroy 销毁;
onStart 可见与onStop 不可见;onResume可编辑(即焦点)与onPause

扫描二维码关注公众号,回复: 1490849 查看本文章


4、如何保存Activity 的状态?
Activity 的状态通常情况下系统会自动保存的,只有当我们需要保存额外的数据时才需要使用到这样的功能。
一般来说, 调用onPause()和onStop()方法后的activity实例仍然存在于内存中, activity的所有信息和状态数据不会消失, 当activity 重新回到前台之后, 所有的改变都会得到保留。
但是当系统内存不足时, 调用 onPause()和 onStop()方法后的 activity 可能会被系统摧毁, 此时内存中就不会存有该 activity 的实例对象了。如果之后这个 activity 重新回到前台, 之前所作的改变就 会 消 失 。 为 了 避 免 此 种 情 况 的 发 生 , 我 们 可 以 覆 写 onSaveInstanceState() 方 法 。
onSaveInstanceState()方法接受一个 Bundle 类型的参数, 开发者可以将状态数据存储到这个Bundle对象中, 这样即使activity被系统摧毁, 当用户重新启动这个activity而调用它的onCreate()方法时, 上述的 Bundle 对象会作为实参传递给 onCreate()方法, 开发者可以从 Bundle 对象中取出保存的数据, 然后利用这些数据将activity 恢复到被摧毁之前的状态。
需要注意的是, onSaveInstanceState()方法并不是一定会被调用的, 因为有些场景是不需要保存状态数据的. 比如用户按下BACK键退出activity时, 用户显然想要关闭这个activity, 此时是没有必要保存数据以供下次恢复的, 也就是 onSaveInstanceState()方法不会被调用. 如果调用onSaveInstanceState()方法, 调用将发生在 onPause()或 onStop()方法之前。
@Override
protected void onSaveInstanceState(Bundle outState) {
// TODO Auto-generated method stub
super.onSaveInstanceState(outState);
}


5、两个 Activity 之间跳转时必然会执行的是哪几个方法?
一般情况下比如说有两个activity,分别叫A,B,当在A里面激活B组件的时候, A会调用 onPause()
方法,然后 B 调用 onCreate() ,onStart(), onResume()。
这个时候B 覆盖了窗体, A 会调用 onStop()方法. 如果 B 是个透明的,或者是对话框的样式, 就
不会调用A的 onStop()方法。


6、横竖屏切换时Activity 的生命周期
此时的生命周期跟清单文件里的配置有关系。
1.不设置Activity 的 android:configChanges时, 切屏会重新调用各个生命周期默认首先销毁
当前 activity,然后重新加载。
2.设置 Activity android:configChanges="orientation|keyboardHidden|screenSize"时,切
屏不会重新调用各个生命周期,只会执行onConfigurationChanged 方法。
通常在游戏开发, 屏幕的朝向都是写死的。


7、如何将一个 Activity 设置成窗口的样式
只需要给我们的Activity 配置如下属性即可。
android:theme="@android:style/Theme.Dialog"


8、如 何退 出 Activity ? 如何 安全 退出 已 调用 多个 Activity 的Application?
1、通常情况用户退出一个 Activity 只需按返回键,我们写代码想退出activity 直接调用 finish()方法就行。
2、记录打开的 Activity:
每打开一个 Activity,就记录下来。在需要退出时,关闭每一个Activity 即可。
//伪代码
List<Activity> lists ;// 在 application 全局的变量里面
lists = new ArrayList<Activity>();
lists.add(this);
for(Activity activity: lists)
{
activity.finish();
}
lists.remove(this);
3、发送特定广播:
在需要结束应用时,发送一个特定的广播,每个Activity 收到广播后,关闭即可。
//给某个 activity 注册接受接受广播的意图
registerReceiver(receiver, filter)
//如果过接受到的是 关闭 activity 的广播 就调用 finish()方法 把当前的 activity finish()掉
4、递归退出
在打开新的 Activity 时使用 startActivityForResult,然后自己加标志,在 onActivityResult 中
处理,递归关闭。
5、其实 也可以通过 intent的 flag 来实现 intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP)
激活一个新的activity。此时如果该任务栈中已经有该Activity,那么系统会把这个Activity 上面的所有 Activity 干掉。其实相当于给Activity 配置的启动模式为 SingleTop。


9、Activity 的四种启动模式,singletop 和 singletask 区别是什么?
一般书签的使用模式是 singletop,那为什么不使用 singletask?
singleTop 跟 standard 模式比较类似。唯一的区别就是,当跳转的对象是位于栈顶的activity(应
该可以理解为用户眼前所 看到的 activity)时,程序将不会生成一个新的activity 实例,而是直接跳
到现存于栈顶的那个activity 实例。拿上面的例子来说,当 Act1 为 singleTop 模式时,执行跳转
后栈里面依旧只有一个实例,如果现在按返回键程序将直接退出。
singleTask模式和 singleInstance 模式都是只创建一个实例的。在这种模式下,无论跳转的对
象是不是位于栈顶的activity,程序都不会生成一个新的实例(当然前提是栈里面已经有这个实例)。
这种模式相当有用,在以后的多activity 开发中,常会因为跳转的关系导致同个页面生成多个实例,
这个在用户体验上始终有点不好,而如果你将对应的activity 声明为 singleTask 模式,这种问题将
不复存在。在主页的Activity 很常用


10、Android 中的 Context, Activity,Appliction 有什么区别?
相同:Activity 和Application都是 Context的子类。
Context从字面上理解就是上下文的意思, 在实际应用中它也确实是起到了管理上下文环境中各个参
数和变量的总用,方便我们可以简单的访问到各种资源。
不同:维护的生命周期不同。 Context维护的是当前的 Activity 的生命周期,Application维护
的是整个项目的生命周期。
使用 context的时候,小心内存泄露,防止内存泄露,注意一下几个方面:
1. 不要让生命周期长的对象引用activity context,即保证引用 activity 的对象要与 activity 本身
生命周期是一样的。
2. 对于生命周期长的对象,可以使用application,context。
3. 避免非静态的内部类,尽量使用静态类,避免生命周期问题,注意内部类对外部对象引用导致
的生命周期变化。


11、两个Activity 之间传递数据,除了intent,广播接收者,content provider 还有啥?
1)利用 static静态数据,public static成员变量
2)利用外部存储的传输,
例如 File 文件存储
SharedPreferences首选项
Sqlite 数据库


12、Context 是什么?
1、它描述的是一个应用程序环境的信息,即上下文。
2、该类是一个抽象(abstract class)类,Android 提供了该抽象类的具体实现类(ContextIml)。
3、 通过它我们可以获取应用程序的资源和类, 也包括一些应用级别操作, 例如: 启动一个 Activity,
发送广播,接受Intent,信息,等。


二、 Service
1、Service 是否在 main thread 中执行, service 里面是否能执行耗时的操
作?
默认情况,如果没有显示的指 servic所运行的进程, Service 和 activity 是运行在当前 app 所在进
程的 main thread(UI主线程)里面。
service 里面不能执行耗时的操作(网络请求,拷贝数据库,大文件 )
特殊情况 ,可以在清单文件配置 service 执行所在的进程 ,让 service 在另外的进程中执行
<service
android:name="com.baidu.location.f"
android:enabled="true"
android:process=":remote" >
</service>


2、Activity 怎么和 Service 绑定,怎么在 Activity 中启动自己对应的Service?
Activity 通过 bindService(Intent service, ServiceConnection conn, int flags)跟 Service进行
绑定,当绑定成功的时候 Service 会将代理对象通过回调的形式传给 conn,这样我们就拿到了
Service 提供的服务代理对象。
在Activity 中可以通过 startService 和 bindService 方法启动 Service。一般情况下如果想获取
Service 的服务对象那么肯定需要通过 bindService()方法,比如音乐播放器,第三方支付等。如
果仅仅只是为了开启一个后台任务那么可以使用startService()方法。


3、请描述一下 Service 的生命周期
Service 有绑定模式和非绑定模式,以及这两种模式的混合使用方式。不同的使用方法生命周期
方法也不同。
非 绑 定 模 式 : 当 第 一 次 调 用 startService 的 时 候 执 行 的 方 法 依 次 为 onCreate() 、
onStartCommand(),当 Service 关闭的时候调用onDestory 方法。
绑定模式:第一次 bindService()的时候,执行的方法为 onCreate()、onBind()解除绑定的
时候会执行 onUnbind()、onDestory()。
上面的两种生命周期是在相对单纯的模式下的情形。我们在开发的过程中还必须注意Service 实
例只会有一个,也就是说如果当前要启动的Service 已经存在了那么就不会再次创建该 Service 当然
也不会调用 onCreate()方法。
一个 Service 可以被多个客户进行绑定,只有所有的绑定对象都执行了 onBind()方法后该
Service 才会销毁,不过如果有一个客户执行了 onStart()方法,那么这个时候如果所有的 bind 客户
都执行了unBind()该 Service 也不会销毁。
Service 的生命周期图如下所示,帮助大家记忆。


4、什么是 IntentService?有何优点?
我们通常只会使用 Service,可能 IntentService 对大部分同学来说都是第一次听说。那么看了
下面的介绍相信你就不再陌生了。 如果你还是不了解那么在面试的时候你就坦诚说没用过或者不了解
等。并不是所有的问题都需要回答上来的。
一、IntentService 简介
IntentService 是 Service 的子类,比普通的 Service 增加了额外的功能。先看 Service 本身存在
两个问题:
Service 不会专门启动一条单独的进程,Service 与它所在应用位于同一个进程中;传智播客武汉校区就业部出品 务实、创新、质量、分享、专注、责任
18
Service 也不是专门一条新线程,因此不应该在 Service 中直接处理耗时的任务;
二、IntentService 特征
会创建独立的worker线程来处理所有的Intent请求;
会创建独立的worker线程来处理onHandleIntent()方法实现的代码,无需处理多线程问题;
所有请求处理完成后,IntentService 会自动停止,无需调用stopSelf()方法停止 Service;
为Service 的onBind()提供默认实现,返回null;
为Service 的onStartCommand提供默认实现,将请求 Intent添加到队列中;
使用IntentService
本人写了一个 IntentService 的使用例子供参考。该例子中一个 MainActivity 一个
MyIntentService,这两个类都是四大组件当然需要在清单文件中注册。这里只给出核心代码:


MainActivity.java:
public void click(View view){
Intent intent = new Intent(this, MyIntentService.class);
intent.putExtra("start", "MyIntentService");
startService(intent);
}


MyIntentService.java

public class MyIntentService extends IntentService {
private String ex = "";
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
Toast.makeText(MyIntentService.this, "-e " + ex,
Toast.LENGTH_LONG).show();
}
};
public MyIntentService(){
super("MyIntentService");
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
ex = intent.getStringExtra("start");
return super.onStartCommand(intent, flags, startId);
}
@Override
protected void onHandleIntent(Intent intent) {
/**
* 模拟执行耗时任务
* 该方法是在子线程中执行的,因此需要用到handler 跟主线程进行通信
*/
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
mHandler.sendEmptyMessage(0);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
运行后效果如下:


5、说说 Activity、Intent、Service 是什么关系
他们都是 Android 开发中使用频率最高的类。其中 Activity 和 Service 都是 Android 四大组件
之一。他俩都是 Context类的子类 ContextWrapper的子类,因此他俩可以算是兄弟关系吧。不过
兄弟俩各有各自的本领, Activity 负责用户界面的显示和交互, Service 负责后台任务的处理。 Activity
和 Service 之间可以通过Intent传递数据,因此可以把Intent看作是通信使者。


6、Service 和Activity 在同一个线程吗
对于同一app 来说默认情况下是在同一个线程中的,main Thread (UI Thread)。


7、Service 里面可以弹吐司么
可以的。弹吐司有个条件就是得有一个 Context 上下文,而 Service 本身就是 Context 的子类,因此在 Service 里面弹吐司是完全可以的。比如我们在 Service 中完成下载任务后可以弹一个吐司通知用户。


8、什么是 Service 以及描述下它的生命周期。Service 有哪些启动方法,有什么区别,怎样停用Service?
在 Service 的生命周期中,被回调的方法比Activity 少一些,只有 onCreate, onStart, onDestroy,
onBind和 onUnbind。
通常有两种方式启动一个Service,他们对 Service 生命周期的影响是不一样的。
1. 通过startService
Service会经历 onCreate 到onStart, 然后处于运行状态, stopService的时候调用onDestroy
方法。
如果是调用者自己直接退出而没有调用stopService 的话,Service 会一直在后台运行。
2. 通过bindService
Service 会运行onCreate,然后是调用onBind, 这个时候调用者和 Service 绑定在一起。调
用者退出了,Srevice就会调用 onUnbind->onDestroyed方法。
所谓绑定在一起就共存亡了。调用者也可以通过调用unbindService 方法来停止服务,这时候
Srevice就会调用onUnbind->onDestroyed方法。
需要注意的是如果这几个方法交织在一起的话,会出现什么情况呢?
一个原则是 Service 的 onCreate的方法只会被调用一次,就是你无论多少次的startService 又
bindService,Service 只被创建一次。
如果先是bind了, 那么 start 的时候就直接运行Service 的 onStart 方法, 如果先是 start, 那么 bind
的时候就直接运行onBind方法。
如果 service 运行期间调用了bindService,这时候再调用 stopService 的话,service 是不会调用
onDestroy 方法的,service 就 stop不掉了,只能调用 UnbindService, service 就会被销毁
如果一个service 通过 startService 被 start 之后,多次调用startService 的话,service 会多次调
用 onStart 方法。多次调用stopService 的话,service 只会调用一次 onDestroyed方法。
如果一个service 通过 bindService 被 start 之后,多次调用 bindService 的话,service 只会调用
一次 onBind方法。多次调用unbindService 的话会抛出异常。


9、在 service 的生命周期方法 onstartConmand()可不可以执行网络操作?如何在 service 中执行网络操作?
可以直接在 Service 中执行网络操作,在 onStartCommand()方法中可以执行网络操作


三、 Broadcast Receiver
1、请描述一下 BroadcastReceiver
BroadCastReceiver是 Android四大组件之一,主要用于接收系统或者app 发送的广播事件。
广播分两种:有序广播和无序广播。
内部通信实现机制:通过Android 系统的 Binder机制实现通信。
无序广播:完全异步,逻辑上可以被任何广播接收者接收到。优点是效率较高。缺点是一个接收者不
能将处理结果传递给下一个接收者,并无法终止广播intent的传播。
有序广播:按照被接收者的优先级顺序,在被接收者中依次传播。比如有三个广播接收者 A,B,C,
优先级是A > B > C。那这个消息先传给 A,再传给 B,最后传给 C。每个接收者有权终止广播,比
如 B终止广播,C就无法接收到。此外 A接收到广播后可以对结果对象进行操作,当广播传给 B 时,
B可以从结果对象中取得 A 存入的数据。
在通过 Context.sendOrderedBroadcast(intent, receiverPermission, resultReceiver, scheduler,
initialCode, initialData, initialExtras)时我们可以指定 resultReceiver广播接收者,这个接收者我们
可以认为是最终接收者,通常情况下如果比他优先级更高的接收者如果没有终止广播,那么他的
onReceive会被执行两次,第一次是正常的按照优先级顺序执行,第二次是作为最终接收者接收。
如果比他优先级高的接收者终止了广播,那么他依然能接收到广播。
在我们的项目中经常使用广播接收者接收系统通知,比如开机启动、sd 挂载、低电量、外播电话、
锁屏等。
如果我们做的是播放器,那么监听到用户锁屏后我们应该将我们的播放之暂停等。


2、在 manifest和代码中如何注册和使用 BroadcastReceiver
在清单文件中注册广播接收者称为静态注册,在代码中注册称为动态注册。静态注册的广播接收者只要 app 在系统中运行则一直可以接收到广播消息,动态注册的广播接收者当注册的 Activity 或
者 Service 销毁了那么就接收不到广播了。
静态注册:在清单文件中进行如下配置
<receiver android:name=".BroadcastReceiver1" >
<intent-filter>
<action android:name="android.intent.action.CALL" >
</action>
</intent-filter>
</receiver>
动态注册:在代码中进行如下注册
receiver = new BroadcastReceiver();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(CALL_ACTION);
context.registerReceiver(receiver, intentFilter);


3、BroadCastReceiver 的生命周期
a. 广播接收者的生命周期非常短暂的,在接收到广播的时候创建,onReceive()方法结束之后销
毁;
b. 广播接收者中不要做一些耗时的工作,否则会弹出Application No Response 错误对话框;
c. 最好也不要在广播接收者中创建子线程做耗时的工作, 因为广播接收者被销毁后进程就成为了
空进程,很容易被系统杀掉;
d. 耗时的较长的工作最好放在服务中完成;


4、Android引入广播机制的用意
a. 从 MVC的角度考虑(应用程序内) 其实回答这个问题的时候还可以这样问,android 为什么要有
那 4大组件,现在的移动开发模型基本上也是照搬的web 那一套 MVC架构,只不过是改了点
嫁妆而已。android 的四大组件本质上就是为了实现移动或者说嵌入式设备上的 MVC架构,它们之间有时候是一种相互依存的关系,有时候又是一种补充关系,引入广播机制可以方便几大组
件的信息和数据交互。
b. 程序间互通消息(例如在自己的应用程序内监听系统来电)
c. 效率上(参考UDP的广播协议在局域网的方便性)
d. 设计模式上(反转控制的一种应用,类似监听者模式)


四、 ContentProvider
1、请介绍下 ContentProvider 是如何实现数据共享的
在 Android 中如果想将自己应用的数据(一般多为数据库中的数据)提供给第三发应用,那么
我们只能通过ContentProvider来实现了。
ContentProvider 是应用程序之间共享数据的接口。使用的时候首先自定义一个类继承
ContentProvider,然后覆写 query、insert、update、delete 等方法。因为其是四大组件之一因
此必须在AndroidManifest文件中进行注册。
把自己的数据通过uri的形式共享出去
android 系统下 不同程序 数据默认是不能共享访问
需要去实现一个类去继承ContentProvider
public class PersonContentProvider extends ContentProvider{
public boolean onCreate(){
}
query(Uri, String[], String, String[], String)
insert(Uri, ContentValues)
update(Uri, ContentValues, String, String[])
delete(Uri, String, String[])
}
<provider
android:exported="true"
android:name="com.itheima.contenProvider.provider.PersonContentPro
vider"android:authorities="com.itheima.person" />
第三方可以通过ContentResolver来访问该 Provider。


2、请介绍下 Android 的数据存储方式
a. File存储
b. SharedPreference存储
c. ContentProvider存储
d. SQLiteDataBase 存储
e. 网络存储


3、为什么要用 ContentProvider?它和sql 的实现上有什么差别?
ContentProvider 屏蔽了数据存储的细节,内部实现对用户完全透明,用户只需要关心操作数据的
uri就可以了,ContentProvider可以实现不同app 之间共享。
Sql也有增删改查的方法,但是 sql 只能查询本应用下的数据库。而 ContentProvider 还可
以去增删改查本地文件. xml 文件的读取等。


4、说说 ContentProvider、ContentResolver、ContentObserver 之间的关系
a. ContentProvider 内容提供者,用于对外提供数据
b. ContentResolver.notifyChange(uri)发出消息
c. ContentResolver 内容解析者,用于获取内容提供者提供的数据
d. ContentObserver 内容监听器,可以监听数据的改变状态传智播客武汉校区就业部出品 务实、创新、质量、分享、专注、责任
26
e. ContentResolver.registerContentObserver()监听消息。


五、 ListView
1、ListView 如何提高其效率?
当 convertView 为空时,用 setTag()方法为每个 View 绑定一个存放控件的 ViewHolder 对象。当
convertView不为空, 重复利用已经创建的view的时候, 使用getTag()方法获取绑定的ViewHolder
对象,这样就避免了findViewById对控件的层层查询,而是快速定位到控件。
① 复用ConvertView,使用历史的view,提升效率200%
② 自定义静态类ViewHolder,减少findViewById 的次数。提升效率50%
③ 异步加载数据,分页加载数据。
④ 使用WeakRefrence引用ImageView对象


2、当 ListView 数据集改变后,如何更新 ListView
使用该ListView的 adapter的 notifyDataSetChanged()方法。 该方法会使 ListView 重新绘制。


3、ListView 如何实现分页加载
① 设置 ListView的滚动监听器:setOnScrollListener(new OnScrollListener{….})
在监听器中有两个方法: 滚动状态发生变化的方法(onScrollStateChanged)和 listView 被滚动
时调用的方法(onScroll)
② 在滚动状态发生改变的方法中,有三种状态:
手指按下移动的状态: SCROLL_STATE_TOUCH_SCROLL: // 触摸滑动
惯性滚动(滑翔(flgin)状态): SCROLL_STATE_FLING: // 滑翔
静止状态: SCROLL_STATE_IDLE: // 静止
对不同的状态进行处理:
分批加载数据,只关心静止状态:关心最后一个可见的条目,如果最后一个可见条目就是数据适
配器(集合)里的最后一个,此时可加载更多的数据。在每次加载的时候,计算出滚动的数量,当滚
动的数量大于等于总数量的时候,可以提示用户无更多数据了。


4、ListView 可以显示多种类型的条目吗
这个当然可以的,ListView 显示的每个条目都是通过 baseAdapter 的 getView(int position,
View convertView, ViewGroup parent)来展示的, 理论上我们完全可以让每个条目都是不同类型的
view。
比如:从服务器拿回一个标识为id=1,那么当 id=1 的时候,我们就加载类型一的条目,当 id=2
的时候,加载类型二的条目。常见布局在资讯类客户端中可以经常看到。
除此之外 adapter还提供了 getViewTypeCount()和 getItemViewType(int position)两个方
法。在 getView方法中我们可以根据不同的viewtype 加载不同的布局文件。


5、ListView 如何定位到指定位置
可以通过ListView提供的 lv.setSelection(listView.getPosition());方法。


6、如何在 ScrollView 中如何嵌入 ListView
通常情况下我们不会在 ScrollView 中嵌套 ListView,但是如果面试官非让我嵌套的话也是可以
的。
在ScrollView 添加一个ListView 会导致 listview 控件显示不全,通常只会显示一条,这是因为两个控件的滚动事件冲突导致。所以需要通过listview 中的 item数量去计算 listview 的显示高度,
从而使其完整展示,如下提供一个方法供大家参考。
lv = (ListView) findViewById(R.id.lv);
adapter = new MyAdapter();
lv.setAdapter(adapter);
setListViewHeightBasedOnChildren(lv);
----------------------------------------------------
public void setListViewHeightBasedOnChildren(ListView listView) {
ListAdapter listAdapter = listView.getAdapter();
if (listAdapter == null) {
return;
}
int totalHeight = 0;
for (int i = 0; i < listAdapter.getCount(); i++) {
View listItem = listAdapter.getView(i, null, listView);
listItem.measure(0, 0);
totalHeight += listItem.getMeasuredHeight();
}
ViewGroup.LayoutParams params = listView.getLayoutParams();
params.height = totalHeight + (listView.getDividerHeight() *
(listAdapter.getCount() - 1));
params.height += 5;// if without this statement,the listview will be a
// little short
listView.setLayoutParams(params);
}
现阶段最好的处理的方式是: 自定义 ListView,重载 onMeasure()方法,设置全部显示。传智播客武汉校区就业部出品 务实、创新、质量、分享、专注、责任
29
package com.meiya.ui;
import android.widget.ListView;
/**
*
* @Description: scrollview 中内嵌listview 的简单实现
*
* @File: ScrollViewWithListView.java
*
*
* @Version
*/
public class ScrollViewWithListView extends ListView {
public ScrollViewWithListView(android.content.Context context,
android.util.AttributeSet attrs) {
super(context, attrs);
}
/**
* Integer.MAX_VALUE >> 2,如果不设置,系统默认设置是显示两条
*/
public void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int expandSpec = MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
MeasureSpec.AT_MOST);
super.onMeasure(widthMeasureSpec, expandSpec);
}
}


7、ListView 中如何优化图片
图片的优化策略比较多。
1、处理图片的方式:
如果ListView中自定义的 Item中有涉及到大量图片的,一定要对图片进行细心的处理,因为图片占的内存是ListView项中最头疼的,处理图片的方法大致有以下几种:
①、不要直接拿路径就去循环 BitmapFactory.decodeFile;使用 Options保存图片大小、不要加
载图片到内存去。
②、对图片一定要经过边界压缩尤其是比较大的图片,如果你的图片是后台服务器处理好的那就
不需要了
③、在 ListView 中取图片时也不要直接拿个路径去取图片,而是以 WeakReference(使用
WeakReference 代替强引用。比如可以使用 WeakReference mContextRef)、SoftReference、
WeakHashMap 等的来存储图片信息。
④、在 getView中做图片转换时,产生的中间变量一定及时释放
2、异步加载图片基本思想:
1)、 先从内存缓存中获取图片显示(内存缓冲)
2)、获取不到的话从 SD卡里获取(SD卡缓冲)
3)、都获取不到的话从网络下载图片并保存到 SD 卡同时加入内存并显示(视情况看是否要显
示)
原理:
优化一:先从内存中加载,没有则开启线程从 SD卡或网络中获取,这里注意从 SD 卡获取图片
是放在子线程里执行的,否则快速滑屏的话会不够流畅。
优化二:于此同时,在 adapter里有个 busy 变量,表示 listview 是否处于滑动状态,如果是滑
动状态则仅从内存中获取图片,没有的话无需再开启线程去外存或网络获取图片。
优化三:ImageLoader 里的线程使用了线程池,从而避免了过多线程频繁创建和销毁,如果每
次总是 new一个线程去执行这是非常不可取的,好一点的用的 AsyncTask类,其实内部也是用到了
线程池。在从网络获取图片时,先是将其保存到sd 卡,然后再加载到内存,这么做的好处是在加载到内存时可以做个压缩处理,以减少图片所占内存。


8、ListView 中图片错位的问题是如何产生的
图片错位问题的本质源于我们的listview使用了缓存convertView, 假设一种场景, 一个listview
一屏显示九个item,那么在拉出第十个item 的时候,事实上该 item 是重复使用了第一个 item,也
就是说在第一个 item 从网络中下载图片并最终要显示的时候,其实该 item 已经不在当前显示区域
内了,此时显示的后果将可能在第十个 item上输出图像,这就导致了图片错位的问题。所以解决之
道在于可见则显示,不可见则不显示。
9、如何刷新 ListView 中单个 item 的数据,不刷新整个 ListView 的数
据?
修改单个Item的数据,然后调用适配器的 notifyDataSetChanged()方法


六、Intent
1、Intent 传递数据时,可以传递哪些类型数据?
Intent可以传递的数据类型非常的丰富, java的基本数据类型和 String以及他们的数组形式
都可以,除此之外还可以传递实现了Serializable和 Parcelable接口的对象。


2、Serializable 和Parcelable 的区别
在使用内存的时候,Parcelable 类比 Serializable 性能高,所以推荐使用 Parcelable类。
1.Serializable在序列化的时候会产生大量的临时变量,从而引起频繁的GC。传智播客武汉校区就业部出品 务实、创新、质量、分享、专注、责任
32
2.Parcelable 不能使用在要将数据存储在磁盘上的情况。尽管 Serializable 效率低点,但在这
种情况下,还是建议你用Serializable 。
实现:
1.Serializable 的实现,只需要继承 Serializable 即可。这只是给对象打了一个标记,系统会
自动将其序列化。
2.Parcelabel 的实现,需要在类中添加一个静态成员变量 CREATOR,这个变量需要继承
Parcelable.Creator 接口。
public class MyParcelable implements Parcelable {
private int mData;
public int describeContents() {
return 0;
}
public void writeToParcel(Parcel out, int flags) {
out.writeInt(mData);
}
public static final Parcelable.Creator<MyParcelable> CREATOR
= new Parcelable.Creator<MyParcelable>() {
public MyParcelable createFromParcel(Parcel in) {
return new MyParcelable(in);
}
public MyParcelable[] newArray(int size) {
return new MyParcelable[size];
}
};
private MyParcelable(Parcel in) {
mData = in.readInt();
}
}


3、请描述一下 Intent 和 IntentFilter
Android 中通过 Intent 对象来表示一条消息,一个 Intent 对象不仅包含有这个消息的目的
地,还可以包含消息的内容,这好比一封 Email,其中不仅应该包含收件地址,还可以包含具体的内
容。对于一个 Intent 对象,消息“目的地”是必须的,而内容则是可选项。
通过Intent 可以实现各种系统组件的调用与激活.
IntentFilter: 可以理解为邮局或者是一个信笺的分拣系统…
这个分拣系统通过3个参数来识别
Action: 动作 view
Data: 数据 uri uri
Category : 而外的附加信息
Action 匹配
Action 是一个用户定义的字符串, 用于描述一个 Android 应用程序组件, 一个 IntentFilter 可
以包含多个 Action。在 AndroidManifest.xml 的 Activity 定义时可以在其 <intent-filter >节点
指定一个 Action 列表用于标示 Activity 所能接受的“动作”,例如:
<intent-filter >
<action android:name="android.intent.action.MAIN" />
<action android:name="cn.itheima.action" />
……
</intent-filter>
如果我们在启动一个 Activity 时使用这样的 Intent 对象:
Intent intent =new Intent();
intent.setAction("cn.itheima.action");
那么所有的 Action 列表中包含了“cn.itheima”的 Activity 都将会匹配成功。
Android 预定义了一系列的 Action 分别表示特定的系统动作。这些 Action 通过常量的方式
定义在 android.content. Intent中,以“ACTION_”开头。我们可以在 Android 提供的文档中找
到它们的详细说明。
URI 数据匹配
一个 Intent 可以通过 URI 携带外部数据给目标组件。在 <intent-filter >节点中,通过
<data/>节点匹配外部数据。
mimeType 属性指定携带外部数据的数据类型,scheme 指定协议,host、port、path 指定
数据的位置、端口、和路径。如下:
<data android:mimeType="mimeType" android:scheme="scheme"
android:host="host" android:port="port" android:path="path"/>
电话的uri tel: 12345
http://www.baidu.com
自己定义的 uri itcast://cn.itcast/person/10
如果在 Intent Filter 中指定了这些属性, 那么只有所有的属性都匹配成功时 URI 数据匹配才会
成功。
Category 类别匹配
<intent-filter >节点中可以为组件定义一个 Category 类别列表,当 Intent 中包含这个列表
的所有项目时 Category 类别匹配才会成功。


七、Fragment
1、Fragment 跟 Activity 之间是如何传值的
当 Fragment 跟 Activity 绑定之后,在 Fragment 中可以直接通过 getActivity()方法获取到
其绑定的Activity 对象,这样就可以调用Activity 的方法了。在 Activity 中可以通过如下方法获取到
Fragment实例
FragmentManager fragmentManager = getFragmentManager();
Fragment fragment = fragmentManager.findFragmentByTag(tag);
Fragment fragment = fragmentManager.findFragmentById(id);
获取到 Fragment之后就可以调用Fragment的方法。也就实现了通信功能。


2、描述一下 Fragment 的生命周期


3、Fragment 的 replace 和 add方法的区别
Fragment本身并没有replace和add方法, 这里的理解应该为使用FragmentManager的replace
和 add 两种方法切换Fragment时有什么不同。
我们经常使用的一个架构就是通过 RadioGroup 切换 Fragment,每个 Fragment 就是一个功能模块。
case R.id.rb_1:
rb_1.setBackgroundColor(Color.RED);
transaction.show(fragment1);
// transaction.replace(R.id.fl, fragment1, "Fragment1");
break;
case R.id.rb_2:
rb_2.setBackgroundColor(Color.YELLOW);
// transaction.replace(R.id.fl, fragment2, "Fragment2");
transaction.show(fragment2);
break;
case R.id.rb_3:
rb_3.setBackgroundColor(Color.BLUE);
// transaction.replace(R.id.fl, fragment3, "Fragment3");
transaction.show(fragment3);
break;
实现这个功能可以通过replace 和 add 两种方法。
Fragment 的容器一个 FrameLayout,add 的时候是把所有的 Fragment 一层一层的叠加到了
FrameLayout上了, 而replace的话首先将该容器中的其他Fragment去除掉然后将当前Fragment
添加到容器中。
一个 Fragment 容器中只能添加一个 Fragment 种类,如果多次添加则会报异常,导致程序终止,
而 replace 则无所谓,随便切换。
因为通过 add 的方法添加的 Fragment,每个 Fragment 只能添加一次,因此如果要想达到切换效
果需要通过 Fragment 的的 hide 和 show 方法结合者使用。将要显示的 show 出来,将其他 hide
起来。这个过程Fragment的生命周期没有变化。
通过 replace 切换 Fragment,每次都会执行上一个 Fragment 的 onDestroyView,新 Fragment
的 onCreateView、onStart、onResume 方法。
基于以上不同的特点我们在使用的使用一定要结合着生命周期操作我们的视图和数据。


4、Fragment 如何实现类似 Activity 栈的压栈和出栈效果的?
Fragment 的事物管理器内部维持了一个双向链表结构,该结构可以记录我们每次 add 的
Fragment和 replace 的 Fragment, 然后当我们点击 back 按钮的时候会自动帮我们实现退栈操作。
Add this transaction to the back stack. This means that the transaction will be remembered after it is committed,
and will reverse its operation when later popped off the stack.
Parameters:
name An optional name for this back stack state, or null.
transaction.addToBackStack("name");
//实现源码 在 BackStackRecord 中
public FragmentTransaction addToBackStack(String name) {
if (!mAllowAddToBackStack) {
throw new IllegalStateException(
"This FragmentTransaction is not allowed to be added to the back
stack.");
}
mAddToBackStack = true;
mName = name;
return this;
}
//上面的源码仅仅做了一个标记
除此之外因为我们要使用FragmentManger用的是FragmentActivity, 因此FragmentActivity
的 onBackPress方法必定重新覆写了。打开看一下,发现确实如此。
/**
* Take care of popping the fragment back stack or finishing the activity
* as appropriate.
*/
public void onBackPressed() {
if (!mFragments.popBackStackImmediate()) {
finish();
}
}
//mFragments 的原型是 FragmentManagerImpl,看看这个方法都干嘛了
@Override
public boolean popBackStackImmediate() {
checkStateLoss();
executePendingTransactions();
return popBackStackState(mActivity.mHandler, null, -1, 0);
}
//看看 popBackStackState 方法都干了啥,其实通过名称也能大概了解 只给几个片段吧,代码太多

while (index >= 0) {
//从后退栈中取出当前记录对象
BackStackRecord bss = mBackStack.get(index);
if (name != null && name.equals(bss.getName())) {
break;
}
if (id >= 0 && id == bss.mIndex) {
break;
}
index--;
}


5、Fragment 在你们项目中的使用
Fragment 是 android3.0 以后引入的的概念,做局部内容更新更方便,原来为了到达这一点要
把多个布局放到一个 activity 里面,现在可以用多 Fragment 来代替,只有在需要的时候才加载Fragment,提高性能。
Fragment的好处:
(1)Fragment 可以使你能够将 activity 分离成多个可重用的组件,每个都有它自己的生命周期和
UI。
(2)Fragment可以轻松得创建动态灵活的 UI 设计,可以适应于不同的屏幕尺寸。从手机到平板电
脑。
(3)Fragment是一个独立的模块,紧紧地与 activity 绑定在一起。可以运行中动态地移除、加入、
交换等。
(4)Fragment提供一个新的方式让你在不同的安卓设备上统一你的UI。
(5)Fragment 解决 Activity 间的切换不流畅,轻量切换。
(6)Fragment 替代 TabActivity 做导航,性能更好。
(7)Fragment 在 4.2.版本中新增嵌套fragment使用方法,能够生成更好的界面效果。


6、如何切换 fragement,不重新实例化
翻看了 Android 官方 Doc,和一些组件的源代码,发现 replace()这个方法只是在上一个 Fragment
不再需要时采用的简便方法.
正确的切换方式是 add(),切换时hide(),add()另一个 Fragment;再次切换时,只需hide()当前,
show()另一个。
这样就能做到多个Fragment切换不重新实例化:
public void switchContent(Fragment from, Fragment to) {
if (mContent != to) {
mContent = to;
FragmentTransaction transaction
=mFragmentMan.beginTransaction().setCustomAnimations(android.R.anim.fad
e_in, R.anim.slide_out);
if (!to.isAdded()) { // 先判断是否被add 过
transaction.hide(from).add(R.id.content_frame, to).commit(); // 隐藏
当前的 fragment,add下一个到Activity中
} else {
transaction.hide(from).show(to).commit(); // 隐藏当前的
fragment,显示下一个
}
}
}
}



1:Android中五种数据存储方式分别是什么?他们的特点?



(1)SharedPreference,存放较少的五种类型的数据,只能在同一个包内使
            用,生成XML的格式存放在设备中
(2) SQLite数据库,存放各种数据,是一个轻量级的嵌入式数据库
(3) File文件,通过读取写入方式生成文件存放数据
(4) ContentProvider,主要用于让其他应用程序使用保存的数据
(5) 通过网络获取数据和写入数据到网络存储空间


        答:Android提供了五种存取数据的方式


2:说说 android 中 mvc 的具体体现


mvc是model,view,controller的缩写,mvc包含三个部分:
模型(model)对象:是应用程序的主体部分,所有的业务逻辑都应该写在该层。
视图(view)对象:是应用程序中负责生成用户界面的部分。也是在整个mvc架构中用户唯一可以看到的一层,接收用户的输入,显示处理结果。
控制器(control)对象:是根据用户的输入,控制用户界面数据显示及更新model对象状态的部分,控制器更重要的一种导航功能,响应用户出发的相关事件,交给m层处理。
android鼓励弱耦合和组件的重用,在android中mvc的具体体现如下:
(1)视图(view):一般采用xml文件进行界面的描述,使用的时候可以非常方便的引入。
(2)控制层(controller):android的控制层的重任通常落在了众多的acitvity的肩上,这句话也就暗含了不要在acitivity中写过多的代码,要通过activity交割model业务逻辑层 处理,这样做的另外一个原因是android中的acitivity的响应时间是5s,如果耗时的操作放在这里,程序就很容易被回收掉。
(3)模型层(model):对数据库的操作、对网络等的操作都应该在model里面处理,当然对业务计算等操作也是必须放在的该层的。


3:简述SharedPreferences存储方式以及SharedPreferences与SQLite数据库的区别


SharedPreferences也是一种轻型的数据存储方式,它的本质是基于XML文件存储key-value键值对数据,通常用来存储一些简单的配置信息。其存储位置在/data/data/<包名 >/shared_prefs目录下。SharedPreferences对象本身只能读取数据而不支持写入数据,存储修改是通过Editor对象实现。SharedPreferences对象与SQLite数据库相比,免去了创建 数据库,创建表,写SQL语句等诸多操作,相对而言更加方便,简洁。但是SharedPreferences也有其自身缺陷,比如其职能存储boolean,int,float,long和String五种简单的数据 类型,比如其无法进行条件查询等。所以不论SharedPreferences的数据存储操作是如何简单,它也只能是存储方式的一种补充,而无法完全替代如SQLite数据库这样的其他数据存储 方式。



4:描述handler 机制的原理


andriod提供了 Handler 和 Looper 来满足线程间的通信。
Handler 先进先出原则。
Looper类用来管理特定线程内对象之间的消息交换(Message Exchange)。 
(1)Looper: 一个线程可以产生一个Looper对象,由它来管理此线程里的Message Queue(消息队列)。 
(2)Handler: 你可以构造Handler对象来与Looper沟通,以便push新消息到Message Queue里;或者接收Looper从Message Queue取出)所送来的消息。 
(3) Message Queue(消息队列):用来存放线程放入的消息。 
(4)线程:UI thread 通常就是main thread,而Android启动程序时会替它建立一个Message Queue。
 

 
5:显式intent和隐式intent的区别是什么(android)


答:Intent定义:Intent是一种在不同组件之间传递的请求消息,是应用程序发出的请求和意图。作为一个完整的消息传递机制,Intent不仅需要发送端,还需要接收端。
显式Intent定义:对于明确指出了目标组件名称的Intent,我们称之为显式Intent。
隐式Intent定义:对于没有明确指出目标组件名称的Intent,则称之为隐式Intent。
说明:Android系统使用IntentFilter 来寻找与隐式Intent相关的对象。


6:如何优化ListView


1、如果自定义适配器,那么在getView方法中要考虑方法传进来的参数contentView是否为null,如果为null就创建contentView并返回,如果不为null则直接使用。在这个方法中尽 可能少创建view。
2、给contentView设置tag(setTag()),传入一个viewHolder对象,用于缓存要显示的数据,可以达到图像数据异步加载的效果。
3、如果listview需要显示的item很多,就要考虑分页加载。比如一共要显示100条或者更多的时候,我们可以考虑先加载20条,等用户拉到列表底部的时候再去加载接下来的20条。


7:简述通过contentResolver获取ContentProvider内容的基本步骤


第一:得到ContentResolver类对象:ContentResolver cr = getContentResolver();
第二:定义要查询的字段String数组。
第三:使用cr.query();返回一个Cursor对象。
第四:使用while循环得到Cursor里面的内容。


8:描述4 种 activity 的启动模式


(1)standard :系统的默认模式,一次跳转即会生成一个新的实例。假设有一个activity命名为MainActivity,执行语句:
startActivity(new Intent(MainActivity.this, MainActivity.class))后,MainActivity将跳转到另外一个MainActivity,也就是现在的Task栈里面有MainActivity的两个实例。 按返回键后你会发现仍然是在MainActivity(第一个)里面。
(2)singleTop:singleTop 跟standard 模式比较类似。如果已经有一个实例位于Activity栈的顶部时,就不产生新的实例,而只是调用Activity中的newInstance()方法。如果不位 于栈顶,会产生一个新的实例。例:当MainActivity为 singleTop 模式时,执行跳转后栈里面依旧只有一个实例,如果现在按返回键程序将直接退出。
(3)singleTask: singleTask模式和后面的singleInstance模式都是只创建一个实例的。在这种模式下,无论跳转的对象是不是位于栈顶的activity,程序都不会生成一个新的实例 (当然前提是栈里面已经有这个实例)。这种模式相当有用,在以后的多activity开发中,经常会因为跳转的关系导致同个页面生成多个实例,这个在用户体验上始终有点不好,而 如果你将对应的activity声明为 singleTask 模式,这种问题将不复存在。
(4)singleInstance: 设置为 singleInstance 模式的 activity 将独占一个task(感觉task可以理解为进程),独占一个task的activity与其说是activity,倒不如说是一个应用, 这个应用与其他activity是独立的,它有自己的上下文activity。


9:Android中如何访问自定义ContentProvider?


通过ContentProvider的Uri访问开放的数据。
(1)ContenResolver对象通过Context提供的方法getContenResolver()来获得。
(2)ContenResolver提供了以下方法来操作:insert  delete  update  query这些方法分别会调用ContenProvider中与之对应的方法并得到返回的结果。

10:android中的动画有哪几类,它们的特点和区别是什么?


答:Android中动画可以分为两大类:帧动画、补间动画
(1)补间动画:你定义一个开始和结束,中间的部分由程序运算得到。主要有:旋转、平移、放缩和渐变;AlphaAnimation(渐变型动画)、scaleAnimation(缩放型动画)、 TranslateAnimation(平移型动画)、 RotateAnimation(旋转型动画)、

(2)逐帧动画:Frame(把一连串的图片进行系列化连续播放,如同放电影的效果),它是通过播放一张一张图片来达到动画的效果;


11  There are four Java classes related to the use of sensors on the Android platform. List them and explain the purpose of each.

The four Java classes related to the use of sensors on the Android platform areL

  • Sensor: Provides methods to identify which capabilities are available for a specific sensor.
  • SensorManager: Provides methods for registering sensor event listeners and calibrating sensors.
  • SensorEvent: Provides raw sensor data, including information regarding accuracy.
  • SensorEventListener: Interface that defines callback methods that will receive sensor event notifications.

To learn more about sensors, refer to Android developer’s guide.

12  What is a ContentProvider and what is it typically used for?

ContentProvider manages access to a structured set of data. It encapsulates the data and provide mechanisms for defining data security. ContentProvider is the standard interface that connects data in one process with code running in another process.

More information about content providers can be found here in the Android Developer’s Guide.

13  Under what condition could the code sample below crash your application? How would you modify the code to avoid this potential problem? Explain your answer.

    Intent sendIntent = new Intent();
    sendIntent.setAction(Intent.ACTION_SEND);
    sendIntent.putExtra(Intent.EXTRA_TEXT, textMessage);
    sendIntent.setType(HTTP.PLAIN_TEXT_TYPE); // "text/plain" MIME type
    startActivity(sendIntent);

An implicit intent specifies an action that can invoke any app on the device able to perform the action. Using an implicit intent is useful when your app cannot perform the action, but other apps probably can. If there is more than one application registered that can handle this request, the user will be prompted to select which one to use.

However, it is possible that there are no applications that can handle your intent. In this case, your application will crash when you invoke startActivity(). To avoid this, before calling startActivity() you should first verify that there is at least one application registered in the system that can handle the intent. To do this use resolveActivity() on your intent object:

    // Verify that there are applications registered to handle this intent
    // (resolveActivity returns null if none are registered)
    if (sendIntent.resolveActivity(getPackageManager()) != null) {
        startActivity(sendIntent);
    } 

See the Android developer’s guide for more information about implicit intents.

14  The last callback in the lifecycle of an activity is onDestroy(). The system calls this method on your activity as the final signal that your activity instance is being completely removed from the system memory. Usually, the system will call onPause() and onStop()before calling onDestroy(). Describe a scenario, though, where onPause() and onStop()would not be invoked.

onPause() and onStop() will not be invoked if finish() is called from within the onCreate() method. This might occur, for example, if you detect an error during onCreate() and call finish() as a result. In such a case, though, any cleanup you expected to be done in onPause() and onStop() will not be executed.

Although onDestroy() is the last callback in the lifecycle of an activity, it is worth mentioning that this callback may not always be called and should not be relied upon to destroy resources. It is better have the resources created in onStart() and onResume(), and have them destroyed in onStop() and onPause, respectively.

See the Android developer’s guide for more information about the activity lifecycle.

15   Which of the code snippets below is the correct way to check if a Compass sensor is present on the system? Explain your answer.

Answer 1:

    PackageManager m = getPackageManager();
    if (!m.hasSystemFeature(PackageManager.FEATURE_SENSOR_COMPASS)) {
        // This device does not have a compass, turn off the compass feature
    }

Answer 2:

    SensorManager m = getSensorManager();
    if (!m.hasSystemFeature(SensorManager.FEATURE_SENSOR_COMPASS)) {
        // This device does not have a compass, turn off the compass feature
    }

Answer 3:

    Sensor s = getSensor();
    if (!s.hasSystemFeature(Sensor.FEATURE_SENSOR_COMPASS)) {
        // This device does not have a compass, turn off the compass feature
    }

The correct answer is Answer 1, the version that uses PackageManager.

SensorManager and Sensor are part of Android Sensor Framework and are used for direct access and acquisition of raw sensor data. These classes do not provide any method like hasSystemFeature() which is used for evaluation of system capabilities.

Android defines feature IDs, in the form of ENUMs, for any hardware or software feature that may be available on a device. For instance, the feature ID for the compass sensor is FEATURE_SENSOR_COMPASS.

If your application cannot work without a specific feature being available on the system, you can prevent users from installing your app with a <uses-feature> element in your app’s manifest file to specify a non-negotiable dependency.

However, if you just want to disable specific elements of your application when a feature is missing, you can use the PackageManagerclass. PackageManager is used for retrieving various kinds of information related to the application packages that are currently installed on the device.

To learn more about compatibility and handling different types of devices or sensors please refer to the Android developer’s guide.

16  Describe three common use cases for using an Intent.

Common use cases for using an Intent include:

  • To start an activity: You can start a new instance of an Activity by passing an Intent to startActivity() method.
  • To start a service: You can start a service to perform a one-time operation (such as download a file) by passing an Intent to startService().
  • To deliver a broadcast: You can deliver a broadcast to other apps by passing an Intent to sendBroadcast()sendOrderedBroadcast(), or sendStickyBroadcast().

More information about intents can be found in Android developer’s guide.

17   Suppose that you are starting a service in an Activity as follows:

Intent service = new Intent(context, MyService.class);             
startService(service);

where MyService accesses a remote server via an Internet connection.

If the Activity is showing an animation that indicates some kind of progress, what issue might you encounter and how could you address it?

Responses from a remote service via the Internet can often take some time, either due to networking latencies, or load on the remote server, or the amount of time it takes for the remote service to process and respond to the request.

As a result, if such a delay occurs, the animation in the activity (and even worse, the entire UI thread) could be blocked and could appear to the user to be “frozen” while the client waits for a response from the service. This is because the service is started on the main application thread (or UI thread) in the Activity.

The problem can (and should) be avoided by relegating any such remote requests to a background thread or, when feasible, using an an asynchronous response mechanism.

Note well: Accessing the network from the UI thread throws a runtime exception in newer Android versions which causes the app to crash.

18  Normally, in the process of carrying out a screen reorientation, the Android platform tears down the foreground activity and recreates it, restoring each of the view values in the activity’s layout.

In an app you’re working on, you notice that a view’s value is not being restored after screen reorientation. What could be a likely cause of the problem that you should verify, at a minimum, about that particular view?

You should verify that it has a valid id. In order for the Android system to restore the state of the views in your activity, each view must have a unique ID, supplied by the android:id attribute.

More information is available here.

19  What is DDMS? Describe some of its capabilities.

DDMS is the Dalvik Debug Monitor Server that ships with Android. It provides a wide array of debugging features including:

  • port-forwarding services
  • screen capture
  • thread and heap information
  • network traffic tracking
  • incoming call and SMS spoofing
  • simulating network state, speed, and latency
  • location data spoofing

20  What is the relationship between the life cycle of an AsyncTask and an Activity? What problems can this result in? How can these problems be avoided?

An AsyncTask is not tied to the life cycle of the Activity that contains it. So, for example, if you start an AsyncTask inside an Activity and the user rotates the device, the Activity will be destroyed (and a new Activity instance will be created) but the AsyncTask willnot die but instead goes on living until it completes.

Then, when the AsyncTask does complete, rather than updating the UI of the new Activity, it updates the former instance of the Activity (i.e., the one in which it was created but that is not displayed anymore!). This can lead to an Exception (of the type java.lang.IllegalArgumentException: View not attached to window manager if you use, for instance, findViewById to retrieve a view inside the Activity).

There’s also the potential for this to result in a memory leak since the AsyncTask maintains a reference to the Activty, which prevents the Activity from being garbage collected as long as the AsyncTask remains alive.

For these reasons, using AsyncTasks for long-running background tasks is generally a bad idea . Rather, for long-runningbackground tasks, a different mechanism (such as a service) should be employed.

21  What is an Intent? Can it be used to provide data to a ContentProvider? Why or why not?

The Intent object is a common mechanism for starting new activity and transferring data from one activity to another. However, you cannot start a ContentProvider using an Intent.

When you want to access data in a ContentProvider, you must instead use the ContentResolver object in your application’s Contextto communicate with the provider as a client. The ContentResolver object communicates with the provider object, an instance of a class that implements ContentProvider. The provider object receives data requests from clients, performs the requested action, and returns the results.

22  What is the difference between a fragment and an activity? Explain the relationship between the two.

An activity is typically a single, focused operation that a user can perform (such as dial a number, take a picture, send an email, view a map, etc.). Yet at the same time, there is nothing that precludes a developer from creating an activity that is arbitrarily complex.

Activity implementations can optionally make use of the Fragment class for purposes such as producing more modular code, building more sophisticated user interfaces for larger screens, helping scale applications between small and large screens, and so on. Multiple fragments can be combined within a single activity and, conversely, the same fragment can often be reused across multiple activities. This structure is largely intended to foster code reuse and facilitate economies of scale.

A fragment is essentially a modular section of an activity, with its own lifecycle and input events, and which can be added or removed at will. It is important to remember, though, that a fragment’s lifecycle is directly affected by its host activity’s lifecycle; i.e., when the activity is paused, so are all fragments in it, and when the activity is destroyed, so are all of its fragments.

More information is available here in the Android Developer’s Guide.

23  What is difference between Serializable and Parcelable ? Which is best approach in Android ?

Serializable is a standard Java interface. You simply mark a class Serializable by implementing the interface, and Java will automatically serialize it in certain situations.

Parcelable is an Android specific interface where you implement the serialization yourself. It was created to be far more efficient than Serializable, and to get around some problems with the default Java serialization scheme.

24  What are “launch modes”? What are the two mechanisms by which they can be defined? What specific types of launch modes are supported?

A “launch mode” is the way in which a new instance of an activity is to be associated with the current task.

Launch modes may be defined using one of two mechanisms:

  • Manifest file. When declaring an activity in a manifest file, you can specify how the activity should associate with tasks when it starts. Supported values include:

    • standard (default). Multiple instances of the activity class can be instantiated and multiple instances can be added to the same task or different tasks. This is the common mode for most of the activities.
    • singleTop. The difference from standard is, if an instance of the activity already exists at the top of the current task and the system routes the intent to this activity, no new instance will be created because it will fire off an onNewIntent() method instead of creating a new object.
    • singleTask. A new task will always be created and a new instance will be pushed to the task as the root. However, if any activity instance exists in any tasks, the system routes the intent to that activity instance through the onNewIntent() method call. In this mode, activity instances can be pushed to the same task. This mode is useful for activities that act as the entry points.
    • singleInstance. Same as singleTask, except that the no activities instance can be pushed into the same task of the singleInstance’s. Accordingly, the activity with launch mode is always in a single activity instance task. This is a very specialized mode and should only be used in applications that are implemented entirely as one activity.
  • Intent flags. Calls to startActivity() can include a flag in the Intent that declares if and how the new activity should be associated with the current task. Supported values include:

    • FLAG_ACTIVITY_NEW_TASK. Same as singleTask value in Manifest file (see above).
    • FLAG_ACTIVITY_SINGLE_TOP. Same as singleTop value in Manifest file (see above).
    • FLAG_ACTIVITY_CLEAR_TOP. If the activity being started is already running in the current task, then instead of launching a new instance of that activity, all of the other activities on top of it are destroyed and this intent is delivered to the resumed instance of the activity (now on top), through onNewIntent()There is no corresponding value in the Manifest file that produces this behavior.

More information about launch modes is available here.

25   What is the difference between Service and IntentService? How is each used?

Service is the base class for Android services that can be extended to create any service. A class that directly extends Serviceruns on the main thread so it will block the UI (if there is one) and should therefore either be used only for short tasks or should make use of other threads for longer tasks.

IntentService is a subclass of Service that handles asynchronous requests (expressed as “Intents”) on demand. Clients send requests through startService(Intent) calls. The service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work. Writing an IntentService can be quite simple; just extend the IntentService class and override the onHandleIntent(Intent intent) method where you can manage all incoming requests.

26  What is Android?

Android is a stack of software for mobile devices which includes an Operating System, middleware and some key applications. The application executes within its own process and its own instance of Dalvik Virtual Machine.

27  Describe Android application Architecture?

Android application architecture has the following components.They are as follows −

Services − It will perform background functionalities

Intent − It will perform the inter connection between activities and the data passing mechanism

Resource Externalization − strings and graphics

Notification − light,sound,icon,notification,dialog box,and toast

Content Providers − It will share the data between applications

28  What is An Activity?

Activity performs actions on the screen.If you want to do any operations, we can do with activity

29  What is the APK format?

The Android packaging key is compressed with classes,UI's, supportive assets and manifest.All files are compressed to a single file is called APK.

30  What is An Intent?

It is connected to either the external world of application or internal world of application ,Such as, opening a pdf is an intent and connect to the web browser.etc.

31  What is an explicit Intent?

Android Explicit intent specifies the component to be invoked from activity. In other words, we can call another activity in android by explicit intent.

32  What is an implicit Intent?

Implicit Intent doesn't specifiy the component. In such case, intent provides information of available components provided by the system that is to be invoked.

33  What is An android manifest file?

Every application must have an AndroidManifest.xml file (with precisely that name) in its root directory. The manifest file presents essential information about your app to the Android system, information the system must have before it can run any of the app's code.

34  What language does android support to develop an application?

Android applications has written using the java(Android SDK) and C/C++(Android NDK).

35  What do ADT stands for?

ADT stands for Android development tool,This is useful to develop the applications and test the applications.

36  What are the tools are placed in An Android SDK?

Android SDK collaborated with Android Emulator,DDMS(Dalvik Debug Monitoring Services),AAPT(Android Asset Packaging tool) and ADB(Android debug bridge)

37  What is viewGroup in android?

View group is a collection of views and other child views, it is an invisible part and the base class for layouts.

38  What is a service in android?

The Service is like as an activity to do background functionalities without UI interaction.

39  What is a content provider in android?

A content provider component supplies data from one application to others on request. Such requests are handled by the methods of the ContentResolver class. A content provider can use different ways to store its data and the data can be stored in a database, in files, or even over a network.

40  What are the notifications available in android?

Toast Notification − It will show a pop up message on the surface of the window

Status Bar Notification − It will show notifications on status bar

Dialogue Notification − It is an activity related notification.

41  What is container in android?

The container holds objects,widgets,labels,fields,icons,buttons.etc.

42  What is ADB in android?

It is acts as bridge between emulator and IDE, it executes remote shell commands to run applications on an emulator

43  What is ANR in android?

ANR stands for application is not responding, basically it is a dialog box that appears when the application is not responding.

44  What is an Adapter in android?

The Adapter is used to create child views to represent the parent view items.

45  What is shared preferences in android?

Shared preferences are the simplest mechanism to store the data in XML documents.

46  What are the key components in android architecture?
  • Linux Kernel
  • Libraries
  • Android Framework
  • Android applications.
47  What does the intent filter do in android?

Intent filters are filter out the intents.

48  Where layouts are placed in android?

In The Layout folder, layouts are placed as XML files

49  What is nine-patch images tool in android?

We can change bitmap images in nine sections as four corners,four edges and an axis

50  How many dialog boxes do support in android?

AlertDialog, ProgressDialog,DatePickerDialog, and TimePickerDialog

51  What are the exceptions available in android?

InflateException,Surface.OutOfResourceException,SurfaceHolder.BadSurfaceTypeException,and WindowManager.BadTokenException

52  What is the order of dialog-box in android?

Positive, Neutral, Negative.

53  What is the order of dialogbox in android?

Positive, Neutral, Negative.

54   What are the different storages available in android?

Shared Preferences,Internal Storage,External Storage,SQLite Databases and Network Connection

55  What is a Sticky Intent in android?

Sticky Intent is also a type of intent which allows the communication between a function and a service for example,sendStickyBroadcast() is perform the operations after completion of intent also.

56  How to Translate in Android?

Android uses Google translator to translate data from one language into another language and placed as a string while development

57   How is the use of web view in Android?

WebView is UI component that can display either remote web-pages or static HTML

58   Why can't you run java byte code on Android?

Android uses DVM (Dalvik Virtual Machine ) rather using JVM(Java Virtual Machine), if we want, we can get access to .jar file as a library.

59   How does android track the application on process?

Android provides a Unique ID to all applications is called as Linux ID,this ID is used to track each application.

60  How to change application name after its deployment?

It's not truly recommended to change application name after it's deployment, if we change, it will impact on all other internal components.

61  Define the application resource file in android?

JSON,XML bitmap.etc are application resources.You can injected these files to build process and can load them from the code.

62   How to launch an activity in android?

Using with intent, we can launch an activity.

Intent intent = new Intent(this, MyTestActivity.class);

        startActivity(intent);
How do you pass the data to sub-activities android?

Using with Bundle, we can pass the data to sub activities.

Bundle bun = new Bundle();

        bun.putString("EMAIL", "[email protected]");
63  What is singleton class in android?

A class which can create only an object, that object can be share able to all other classes.

64   What is fragment in android?

Fragment is a piece of activity, if you want to do turn your application 360 degrees, you can do this by fragment.

65  What is sleep mode in android?

Sleep mode mean CPU will be sleeping and it doesn't accept any commands from android device except Radio interface layer and alarm.

66  Which kernal is used in android?

Android is customized Linux 3.6 kernel.

67   How to update UI from a service in android?

Use a dynamic broadcast receiver in the activity, and send a broadcast from the service. Once the dynamic receiver is triggered update UI from that receiver.

68   What folders are impotent in android project?

AndroidManifest.xml

build.xml

bin/

src/

res/

assets/

69   What are application Widgets in android?

App Widgets are miniature application views that can embedded in other applications (such as the Home screen) and receive periodic updates. These views has referred to as Widgets in the user interface, and you can publish one with an App Widget provider.

70  How do you find any view element into your program?

Using with findViewById we can find view element.

71  What is drawable folder in android?

A compiled visual resource that can used as a backgrounds,banners, icons,splash screen etc.

72   What are the type of flags to run an application in android?

FLAG_ACTIVITY_NEW_TASK

FLAG_ACTIVITY_CLEAR_TOP.



73   Explain in brief about the important file and folder when you create new android application.

When you create android application the following folders are created in the package explorer in eclipse which are as follows:

src:  Contains the .java source files for your project. You write the code for your application in this file. This file is available under the package name for your project.

gen:  This folder contains the R.java file. It is compiler-generated file that references all the resources found in your project. You should not modify this file.

Android 4.0 library:  This folder contains android.jar file, which contains all the class libraries needed for an Android application.

assets:  This folder contains all the information about HTML file, text files, databases, etc.

bin:  It contains the .apk file (Android Package) that is generated by the ADT during the build process. An .apk file is the application binary file. It contains everything needed to run an Android application.

res:  This folder contains all the resource file that is used by android application. It contains subfolders as: drawable, menu, layout, and values etc.

74   Explain AndroidManifest.xmlfile in detail.

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android" package="com.example.careerride" android:versionCode="1" android:versionName="1.0">

<uses-sdk android:minSdkVersion="8" android:targetSdkVersion="18" />

<application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme">

<activity android:name="com.example.careerride.MainActivity" android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>


The AndroidManifest.xml file contains the following information about the application:

- It contains the package name of the application.
- The version code of the application is 1.This value is used to identify the version number of your application.
- The version name of the application is 1.0
- The android:minSdkVersion attribute of the element defines the minimum version of the OS on which the application will run.
- ic_launcher.png is the default image that located in the drawable folders.
- app_name defines the name of applicationand available in the strings.xml file.
- It also contains the information about the activity. Its name is same as the application name.

75   Describe android Activities in brief.

Activity provides the user interface. When you create an android application in eclipse through the wizard it asks you the name of the activity. Default name is MainActivity. You can provide any name according to the need. Basically it is a class (MainActivity) that is inherited automatically from Activity class. Mostly, applications have oneor more activities; and the main purpose of an activity is to interact with the user. Activity goes through a numberof stages, known as an activity’s life cycle.

Example:
packagecom.example.careerride; //Application name careerride

importandroid.os.Bundle; // Default packages
importandroid.app.Activity; // Default packages
importandroid.view.Menu;

public class MainActivity extends Activity 
{
        @Override
        protected void onCreate(Bundle savedInstanceState) 
{
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
}
@Override
publicbooleanonCreateOptionsMenu(Menu menu) 
{
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
}
}

When you run the application onCreate method is called automatically.

76   Describe Intents in detail.

An Android application can contain zero or more activities. If you want to navigate fromone activity to another then android provides you Intent class. This class is available inandroid.content.Intent package.One of the most common uses for Intents is to start new activities.

There are two types of Intents.

1) Explicit Intents
2) Implicit Intents

Intents works in pairs: actionand data. The action defines what you want to do, such as editing an item, viewingthe content of an item etc. The dataspecifies what is affected,such as a person in the Contacts database. The data is specified as anUri object.

Explicitly starting an Activity
Intent intent = newIntent (this, SecondActivity.class);

startActivity(intent);
Here SecondActivity is the name of the target activity that you want to start.

Implicitly starting an Activity

If you want to view a web page with the specified URL then you can use this procedure.
Intent i = newIntent(android.content.Intent.ACTION_VIEW,Uri.parse(“http://www.amazon.com”));

startActivity(i);
if you want to dial a telephone number then you can use this method by passing the telephone number in the data portion
Intent i = newIntent (android.content.Intent.ACTION_DIAL,Uri.parse(“tel:+9923.....”));

startActivity(i);
In the above method the user must press the dial button to dial the number. If you want to directly call the number without user intervention, change the action as follows:
Intent i = newIntent (android.content.Intent.ACTION_CALL,Uri.parse(“tel:+9923.....”));

startActivity(i);
If you want to dial tel no or use internet then write these line in AndroidManifest.xml
<uses-permissionandroid:name=”android.permission.CALL_PHONE”/>
<uses-permissionandroid:name=”android.permission.INTERNET”/>

77   How to send SMS in android? Explain with example.

SMS messaging is one of the basic and important applications on a mobile phone. Now days every mobile phone has SMS messaging capabilities, and nearly all users of any age know how to send and receive such messages. Mobile phones come with a built-in SMS application that enables you to send and receive SMS messages. If you want to send the SMS programmatically then follow the following steps.

Sending SMS Messages Programmatically

Take a button on activity_main.xml file as follows.
<Button android:id="@+id/btnSendSMS" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerHorizontal="true" android:layout_centerVertical="true" android:onClick=”sendmySMS” android:text="sendSMS" />
According to above code when user clicks the button sendmySMS method will be called. sendmySMS is user defined method.

In the AndroidManifest.xml file, add the following statements
<uses-permissionandroid:name=”android.permission.SEND_SMS”/>
Now we write the final step. Write the given below method in MainActivity,java file
publicvoidsendmySMS(View v)
{
     SmsManagersms = SmsManager.getDefault();
     sms.sendTextMessage("5556", null, "Hello from careerRide", null, null);
}
In this example I have used two emulator. On the first Android emulator (5554), click the Send SMSbutton to send an SMS message to the second emulator(5556).

78   Describe the SmsManager class in android.

SmsManager class is responsible for sending SMS from one emulator to another or device.

You cannot directly instantiate this class; instead, you call the getDefault() static method to obtain an SmsManager object. You then send the SMS message using the sendTextMessage() method:
SmsManagersms = SmsManager.getDefault();

sms.sendTextMessage("5556", null, "Hello from careerRide", null, null);

sendTextMessage() method takes five argument.

- destinationAddress — Phone number of the recipient.
- scAddress — Service center address; you can use null also.
- text — Content of the SMS message that you want to send.
- sentIntent — Pending intent to invoke when the message is sent.
- deliveryIntent — Pending intent to invoke when the message has been delivered.

79   How you can use built-in Messaging within your application?

You can use an Intent object to activate the built-in Messaging service. You have to pass MIME type “vnd.android-dir/mms-sms”, in setType method of Intent as shown in the following given below code.
Intent intent = new Intent (android.content.Intent.ACTION_VIEW);
intent.putExtra("address", "5556; 5558;");// Send the message to multiple recipient.
itent.putExtra("sms_body", "Hello my friends!");
intent.setType("vnd.android-dir/mms-sms");
startActivity(intent);

80   What are different data storage options are available in Android?

Different data storage options are available in Android are:

- SharedPreferences
- SQlite
- ContentProvider
- File Storage
- Cloud Storage

81  Describe SharedPreference storage option with example.

SharedPreference is the simplest mechanism to store the data in android. You do not worry about creating the file or using files API.It stores the data in XML files. SharedPreference stores the data in key value pair.The SharedPreferences class allows you to save and retrieve key-value pairs of primitive data types. You can use SharedPreferences to save any primitive data: boolean, floats, int, longs, and strings.The data is stored in XML file in the directory data/data//shared-prefs folder.

Application of SharedPreference

- Storing the information about number of visitors (counter).
- Storing the date and time (when your Application is updated).
- Storing the username and password.
- Storing the user settings.

Example:


For storing the data we will write the following code in main activity on save button:
SharedPreferences sf=getSharedPreferences("MyData", MODE_PRIVATE);
SharedPreferences.Editored= sf.edit();
ed.putString("name", txtusername.getText().toString());
ed.putString("pass", txtpassword.getText().toString());
ed.commit();

In this example I have taken two activities. The first is MainActivity and the second one is SecondActivity.When user click on save button the user name and password that you have entered in textboxes, will be stored in MyData.xml file.

Here MyData is the name of XML file .It will be created automatically for you.

MODE_PRIVATE means this file is used by your application only.

txtusernameand txtpassword are two EditText control in MainActivity.

For retrieving the data we will write the following code in SecondActiviy when user click on Load button:

Public static final String DEFAULT=”N? A”;

DEFAULT is a String type user defined global variable.If the data is not saved in XML file and user click on load button then your application will not give the error. It will show message “No Data is found”. Here name and pass are same variable that I have used in MainActivity.
SharedPreferences sf=getSharedPreferences("MyData", Context.MODE_PRIVATE);

String Uname=sf.getString("name", DEFAULT);

String UPass=sf.getString("pass", DEFAULT);

if(name.equals(DEFAULT)||Pass.equals(DEFAULT))
{
    Toast.makeText(this, "No data is found", Toast.LENGTH_LONG).show();
}

else

{
    Txtusername.setText(Uname);
    Txtpassword.setText(UPass) ;
}


高级工程师面试题

1、 Service两种方式的区别
2、 Handler在项目怎么用的,线程间如何通信的
3、 AsyncTask和AsyncQueryHandler
4、 HttpClient,HttpUrlConnection的区别
5、 消息推送机制xmpp协议,客户端发送服务器好处理,只要知道服务器IP就可以,服务器如何给客户端推送消息呢
6、 oauth认证
7、 HTML和XML的区别、
8、 多线程断点续传下载如何实现续传的
9、 TCP、UDP的区别
10、 aidl开发
11、 Android中JNI和NDK的使用,了解WebService调用技术
12、 Android安全机制,垃圾回收机制
14、 屏幕适配
15、 android ui的几个概念:px,dip(dp),sp,dpi,分辨率等,dpi是在Android资源随着不同手机的分辨率自动进行适配,res-》drawable-hdpi
16、 Launcher如何设置壁纸
17、 baiduMap如何用,用百度地图的坐标为甚么显示pc会出现很大的偏差,如何避免呢?
18、 哪个项目是你印象最深

1.为了降低android程序的内存使用峰值和APK文件的大小,我们一般使用_____________工具对资源图进行额外处理。

2.Android系统会自动派发各种事件,事件从触发到相应的程序相应的派发顺序是_________。

3.发布Android程序时,APK文件要先签名,再用Zipalign做4字节对齐。( )

4.实现多个进程共享数据的时候,只要设置AndroidManifest文件的shareUserId属性即可,签名可以不一致( )。

5.在JNI的实现代码中,如果要实现跨线程调用JNI接口,我们需要先调用jni.h中的_________函数,跨线程调用JNI接口完毕后,再调用jni.h中的____________________函数来善后。

6.如果一个Activity被设置为“singleTop”模式并且还驻留在后台,此时再通过startActivity启动这个Activity时,Activity的_______________成员函数会被最先回调到,我们一般在这个回调函数中来处理相关逻辑。


PS:3、4题是判断题,其它是填空题

********************************************************

个人稍微回答下。可能有很多不足之处,仅作借鉴

问题1
为了降低android程序的内存使用峰值和APK文件的大小,我们一般使用_____________工具对资源图进行额外处理。
  答:这个估计一般人都知道了,就是9图工具。而且这个工具真的很好用,就我几个阶段反编译一些apk文件来看。比如一年前的时候的应用,基本没有用到这块,除了几个大型公司做的app,用到了工具。2011年末的几个应用,9妹就来势汹汹了。而且发现9图后图片除了能更好的适配防拉伸效果等,还微微减小了图片大小。同时因为能做多适配和大小缩放不失真的调整,间接的就减少了做多套适配图片而增减资源包的臃肿。

问题2:
Android系统会自动派发各种事件,事件从触发到相应的程序相应的派发顺序是_________。
  答:这个涉及到Framework层了。本人没怎么接触。看关于这个帖子的这个题有人给出过两种答案:
  1.EventHub->KeyInputQueue->WindowManagerService->ViewRoot->...
  2.WindowsManager->phoneWiondw->Activity

  其实两个想表达的意思是差不多的。就是一个服务队列,接受到事件。从队列中将该事件分发给WindowManagerService也就是窗口管理类服务,然后分发个对应的窗口Window,窗口中有个主View,主View又分由上而下子View。这里就要提到两个函数,也是刚开始我搞晕了的两个函数:第一个是dispatchXXXXEvent和onXXXX(onTouchEvent,onKeyDown);以前对这个onxxxx的重写时很多的,这个dispatchXXX基本是没用过。然后我一直也没明白这个派发机制的干嘛的。后来看下了源代码会发现,dispatch分发传递到最后一层时,就执行了onxx事件。说白了就是dispatch是发送事件,onxx是处理事件。
  1.   public boolean dispatchTouchEvent(MotionEvent event) {
  2.         if (mOnTouchListener != null && (mViewFlags & ENABLED_MASK) == ENABLED &&
  3.                 mOnTouchListener.onTouch(this, event)) {
  4.             return true;
  5.         }
  6.         return onTouchEvent(event);
  7.     }
复制代码

  这是View中的一段代码。

  具体关于分发事件的可以查考该博文:Android FrameWork——Touch事件派发过程详解。不太明白的也没事。可以看个大致流程,呵呵。

问题3:
发布Android程序时,APK文件要先签名,再用Zipalign做4字节对齐。( )
  答:这个是判断题,无论你知不知道,好歹还能蒙一个。先说下答案,对的。以我的了解。这题出的其实比较偏门,偏门的意思是大部分人都不会关心这个。我也是在最近弄Ant自动打包时,才是熟悉了下这个问题。因为ant脚本这玩意我也是第一次玩,看了下资料,以及基本语法和书写方式。一般我们打包可能直接用adt工具了,说白了它就是集成了一个打包工具。ant只不过就是我们自己来写而已,里面涉及到很多javac,zipalign和proguard什么的,就是把一些工具的命令行操作语句窜起来。然后接触到要使用一个zipalign优化工具简答了解下:这是一个归档对其工具,对资源做了优化,对未压缩的数据做了某种意义上的4字节对其。
  具体为什么这个顺序是对的呢。不知道这图算不算一种说明方式:



  这是我打完一个未签名包后,工具的提示。
  对于为什么出这样的题,估计是是想看应聘者是否去接触过一些细节和工具,或是对于ant打包的接触?

问题4:
实现多个进程共享数据的时候,只要设置AndroidManifest文件的shareUserId属性即可,签名可以不一致( )。
  答:/***是。具体原因就不知了。**/
  这里先谢谢下面评论中那个哥们,确实对于我可能测试过的几个问题我都做了详细回答。这个因为没有测试,就完全是copy了那会论坛下的几个答案,以为做个总体答案的记录就行了。这是刚测试后的答案。答;不能。因为设置了shareUserId后,在你应用安装的时候系统在对读取配置文件安装信息时就会检测这个问题,既你的A应用和B应用实现了shareUserId一样。
但是在安装时签名不一样的话,安装过程就是失败的。


问题5:
在JNI的实现代码中,如果要实现跨线程调用JNI接口,我们需要先调用jni.h中的_________函数,跨线程调用JNI接口完毕后,再调用jni.h中的_____函数来善后。
  答案:/****   网上查了一下,第五题应该是GetJavaVM, DestroyJavaVM() .copy来的答案。。也不是很懂。****/
  答:这个问题原来只是copy过来的一份答案。谢谢 Innost 前辈对错误指出。涉及到底层的,有很多不足,首先也说下做这块总结只要是想把这几个问题有个还算靠谱的答案,因为现在google或是百度下这几个问题,都只是给出了题目,下面有回答和讨论的。我这边只是想做个简单归档,可能有很多不足,希望指正或是给下更好的答案。上班抽闲大致花了1-2小时看了下这方面的资料。因为本人对C这块不熟,看的其实有点吃力。JavaVM和JavaEnv的概念。
  (因为答案基本围绕了这两个在讨论, Innost 也提到说看下这个概念)。JavaVM即java虚拟机,主要是一个进程(也就是多个线程来访问),简单说就是在一个应用进程启动后背创建。JavaEnv,虚拟机环境,这个是只能被他创建的线程来访问,里面持有该线程访问的数据。利用jvm可以获取当前线程的env。然后通过两个函数,来实现环境依附跨线程的访问和访问完后的释放。
  1. [java] view plaincopy

  2. jint AttachCurrentThread(void **penv, void *args) {
  3.        return functions->AttachCurrentThread(this, penv, args);
  4.    }
复制代码
  1. [java] view plaincopy



  2. jint DetachCurrentThread() {
  3.        return functions->DetachCurrentThread(this);
  4.    }
复制代码

  这两个函数定义可以在jni.h中找到。

  这边其实有考虑到两个参数 _jvm和_env.因为看下上面的代码是通过jvm调用 AttachCurrentThread来获取_env,那_jvm这个参数又是何时获取,怎么获取的。
这个是网上copy的一份解说:
/----------------------------------------------------
JavaVM接口
第一种方式,在加载动态链接库的时候,JVM会调用JNI_OnLoad(JavaVM* jvm, void* reserved)(如果定义了该函数)。第一个参数会传入JavaVM指针。
第二种方式,在native code中调用JNI_CreateJavaVM(&jvm, (void**)&env, &vm_args)可以得到JavaVM指针。
两种情况下,都可以用全局变量,比如JavaVM* g_jvm来保存获得的指针以便在任意上下文中使用。
Android系统是利用第二种方式Invocation interface来创建JVM的。

JNIEnv接口
JNI开发最常见的错误就是滥用了JNIEnv接口。需要强调的是JNIEnv是跟线程相关的。
在native method中,JNIEnv作为第一个参数传入。那么在JNIEnv不作为参数传入的时候,该如何获得它?JNI提供了两个函数:(*jvm)->AttachCurrentThread(jvm, (void**)&env, NULL)和(*jvm)->GetEnv(jvm, (void**)&env, JNI_VERSION_1_2)。两个函数都利用JavaVM接口获得JNIEnv接口。
----------------------------------------------------/
其实这块挺晕的:
看jni.h中对于jvm好env获取是这样的定义。
env->GetJavaVM(&g_vm);
jvm->AttachCurrentThread(&e, &thread_args);
就是通过env获取虚拟机,通过虚拟机获取env。。。。有点先有蛋还是鸡的味道。
对于Android调用了jni几块,比如mediaPlayer模块。我看下了,发现env这个都是自己传进去。
其实还是很不懂。
只是先把这个错误答案改过来。
其实对于上面这个先调用获取jvm理论上也是对的,获取jvm后在获取env。对于后面这个空说销毁jvm可能就不对了。
本题的中心可能主要还是围绕env这个来说事。
更多详情可以看下下面老兄的建议。

问题6:
如果一个Activity被设置为“singleTop”模式并且还驻留在后台,此时再通过startActivity启动这个Activity时,Activity的___成员函数会被最先回调到,我们一般在这个回调函数中来处理相关逻辑。
  答案:onNewIntent().singTask模式的亦是如此。这个因为刚接触过。想singleTop和singleTask除了一般说的防止产生大量的相同的Activity对象,产生内存中的冗余,
同时也可以很巧妙的解决一些问题。我有一个固定的Activity,比如简单的某个购物应用的购物栏界面。即,用户在每个购物界面点击添加购买后都会跳转到这个界面然后添加相应的购买商品条目。如果是一般的启动模式,我每次点击添加购买,就重新启动了一个购物车界面,并且在这个界面中也没有前面几次已经购买的商品条目,于我们的思路相违背。因此这个购物栏界面,理论上我就可以设计成一个单例。这样也就同样很容易的解释了这个题目的初衷了吧。因为一般面试官不可能只是看下你的答案,更多的会问下你几种启动模式的运用场景。这里也顺便提及下4种启动模式。这个不算冷门也很实用的知识,可以注意下,同时也可以大致的了解Android中关于Task的知识。

以上即是整理的一部分面试题,做了下记录和如果是我的话来做的一些看法
*********************************************************************************************/
以下是我最近觉得自己想到的几个问题。

  因为最近说招人的时候,可能部分有2年左右工作经验,1年以上Android开发经验的应聘者,基本薪资都要求在1w上了。于是对于面试的问题也不能仅仅只局限于笔试题这些做烂了的题目或是对方说下某个项目产品的流程框架模块实现什么的。可能更多会要问一下,对于应用界面功能,交互设计的看法,以及如何编码实现一个不失优雅的和功能性的首页面。然后是对于应用常见异常和错误的分析以及解决方式,再简单和细分点就是对于资源代码的优化,自动打包和测试,应用的防篡改和反编译。

题目一;
功能性界面的实现,比如记住用户名这个功能。
  答:当然,对于初级可能会问按钮按下非按下的效果的实现,也就是选择器的应用。(但是真的,还有人会回答你,监听按钮事件然后代码来实现setbackground。。。)
言归正传,这个其实应该是很常见功能性界面。一般都是知道大致的思路的,用个偏好设置,保存一下就ok了。那么再细点呢。这个偏好设置要保存的基友几个参数,用户名,密码,然后呢?对了,那就是是否选折记住用户名密码的这个checkbox。因为我一开始做的时候忘记保存这个了。每次无论是否是checkbox是何种状态,我都保存和读取用户名和密码去了。。。
因此简单的:

图画的比较搓。。因为不太会用。
当你能把大致思路理清后,那么面试的就知道,这事你能解决,而不是笼统的说,用偏好设置啊。这就好比,在论坛中常看到这样的帖子和问答。
这个界面布局怎么实现。回答:相对布局。
好忧郁的回答。。
当然,最后也要看出题人出的题目,对提问人的要求,首先,该功能性代码量和思路要竟可能的能在短时间完成,并且不是模糊性的。

问题二:
代码混淆和压缩优化打包输出。
  答:说白了,就是想问下你对progurad是否熟悉以及接触过。问这个问题其实是我自己也不懂,只会最简单的一句话傻瓜配置。但是又想做自定义的配置。
然后老大说了:对于面试时,你可以问下你自己遇到的,不能解决的问题。呵呵。
对于第三方jar包加入报错的处理,混淆后应用运行的异常。
当然,这块问题其实也是渐渐的必须要了解的东西,因为现在的大部分应用基本都重视被反编译的问题了。
问这个,第一点看面试者是否接触过,如果很熟悉,在原来的项目运用过,自定义配置过,那最好了。
第二点,如果没有,那么没事,可能却是没用到,那么就看对方是不是自己主动去了解过,简单说,是否有所谓热爱追求新技术,知识的汲取不仅仅局限于当前,有善于发现和进取的心。

问题三:
代码测试以及优化的了解?
  答:这个可能就觉得这面试官比较傻逼和笼统了。确实,这问题闻到有点蛋疼。
其实稍微转化下可以问面试者对于原来项目完成后,是否做过测试框架和代码优化调试。
当然,这个是比较高层次了,因为对于自动化测试什么的,我知道的国内可能就一些大型公司会刻意去定制一套测试机制和框架。
问这个问题,其实也是自己的私心,因为我也想了解下一般,功能性测试框架或是界面交互性测试框架,个位大牛是如何实现。
对于代码优化,是否有一套自己成熟的方案。让我也入入门呗。
对于这个问题,其实你只要能说出自己的想法就可以了,如果你切好做过,那就更棒了。以及碰巧说你简单的用过sdktools下的monkey(测试工具)或是TraceViewer(性能追踪工具),那也不错,说明你知道自己去接触。而不是纯粹在那一味写代码。

问题四:
自定义的UI设计。
  答:问这个问题其实每个公司可以参考自己产品的用户体验和视觉体验来问。
当然,既然问的是高手,你就不能傻乎乎的问,比如一个半透明或是dialog风格的的Activity的实现。
简单点的可以问下如何自定一个界面的加载动画,自定义的dialog。。
然后如果联系到自身的产品:第一点,由于目前我们的产品的某一个Activity的界面要展示的内容比较多,又不想简单的说用一个scrollView拖拉来实现,如何最有效的的利用有限的界面空间 1>.使用折叠效果的textView,这个也是一个朋友提到的,具体可以产考目前各大app商店,点击某个应用后,产品简介的那个空间。 2>.抽屉效果,这个其实是个不错的效果,具体代码其实网上大把的有,只要你能说出个思路就差不多,因为其实面试人也不是太懂,或者也只是借鉴网上而实现过。
第二点:自定义的首界面元素。因为我们应用可能下个版本要实现用户自定义的首界面。这个可以参考手机桌面图标拖拉,添加删除效果。这个效果其实有点难度,长按后的界面浮动效果,用户自定义后的配置保存。活着还带点什么特效,自动排序。对于这个涉及到的知识可能就多了,首先可能要对Window和windowmanager这几个对象有很好的了解,配置保存格式或是表单的处理。

问题五:
Http和Socket协议,xml/json
  答:网络模块这个基本是每个公司都会问的一个问题。因为一个 互联网应用,不可能不处理这块内容。
然后这个问题也是很笼统的,http可能会问下常用的头参数。这个其实没多大意义,但是也是很必要。按意义来说,正的写过很多次网络处理的人,其实也很少去真正了解下各个参数 的含义,可能就字符集,内容类型。其实深入点的可以这么问,是否在原来公司或是项目中f封装过自己的网络处理jar。因为很多公司的网络处理都不是说每个项目重新写起来的。然后对于传输格式的解析。xml就不说了,json这个对于普通对象的处理,对于数组对象的处理,以及是否自己修改过或是简单搞过自己的json解析器。因为Android自带的json解析,就那么九个类,还不带直接解析对象。用起来比较局限。
问这个问题,主要也不过是看看面试者是否真正接触和书写过网络模块。对于简历中的一句熟悉http xxxx,现在互联网应用基本没几个应用不使用网络模块吧,你的项目中是有这块内容,但是真正的你了解或是做过处理过的,那又有多少呢。

问题六:
3D动画特效或是游戏方面的
  答:3D动画。首先我觉得会做游戏的人脑子都是比较清晰的,那么多x,y坐标,中心点,旋转点,长,宽,高,角度。参数多的晕人。
对于简单的2D特效,可能都会,3D能?需要那几个辅助类,Camera 吧。游戏的话View和surfaceView框架的选择。通用的游戏模块分类(这里纯粹是私心哈哈)。我目前也真在学习接触。
百度 Android开发面试题 
 
本文来自安卓航班网整理搜集     www.apkway.com 
 
原文地址:http://www.apkway.com/forum.php?mod=viewthread&tid=2057 
1、 Android dvm的进程和Linux的进程, 应用程序的进程是否为同一个概念 
  DVM指dalivk的虚拟机。每一个Android应用程序都在它自己的进程中运行,
都拥有一个独立的Dalvik虚拟机实例。而每一个DVM都是在Linux 中的一个进
程,所以说可以认为是同一个概念。 
  2、sim卡的EF 文件有何作用 
  sim卡的文件系统有自己规范,主要是为了和手机通讯,sim本 
身可以有自己的操作系统,EF就是作存储并和手机通讯用的 
   
3、嵌入式操作系统内存管理有哪几种,各有何特性 ?   
  页式,段式,段页,用到了MMU,虚拟空间等技术 
   
  4、什么是嵌入式实时操作系统, Android 操作系统属于实时操作系统吗? 
     
嵌入式实时操作系统是指当外界事件或数据产生时,能够接受并以足够快的速度
予以处理,其处理的结果又能在规定的时间之内来控制生产过程或对处理系统作
出快速响应,并控制所有实时任务协调一致运行的嵌入式操作系统。主要用于工
业控制、军事设备、 
航空航天等领域对系统的响应时间有苛刻的要求,这就需要使用实时系统。又可
分为软实时和硬实时两种,而android是基于 linux内核的,因此属于软实时。  
     
5、一条最长的短信息约占多少byte? 
  中文70(包括标点),英文160个字节 
     6、 android中的动画有哪几类,它们的特点和区别是什么? 
  两种,一种是Tween动画、还有一种是Frame动画。Tween动画,这种实现方
式可以使视图组件移动、放大、缩小以及产生透明度的变化;另一种 Frame动画,
传统的动画方法,通过顺序的播放排列好的图片来实现,类似电影。 
     
7、handler机制的原理 
  andriod提供了 Handler 和 Looper 来满足线程间的通信。Handler 先进先
出原则。 Looper类用来管理特定线程内对象之间的消息交换(Message Exchange)。  
  1)Looper: 一个线程可以产生一个Looper 对象,由它来管理此线程里的
Message Queue(消息队列)。 
  2)Handler: 你可以构造Handler对象来与 Looper沟通,以便push新消息到
Message Queue里;或者接收Looper 从Message Queue取出)所送来的消息。 
  3) Message Queue(消息队列):用来存放线程放入的消息。 
  4)线程:UI thread 通常就是main thread,而Android启动程序时会替它
建立一个Message Queue。 
    8、说说mvc模式的原理,它在android 中的运用 
   
MVC(Model_view_contraller)” 模型_视图_控制器”。 MVC应用程序总是由这
三个部分组成。Event(事件)导致Controller 改变Model或View,或者同时改
变两者。只要 Controller改变了Models的数据或者属性,所有依赖的View都
会自动更新。类似的,只要Controller改变了View,View会 
从潜在的Model中获取数据来刷新自己。 
     
View重绘和内存泄露的好像是面试经常问的问题 
  1. View的刷新: 
  在需要刷新的地方,使用handle.sendmessage发送信息,然后在handle的
getmessage里面执行invaliate或者postinvaliate. 
   2. GC内存泄露 
  出现情况: 
  1.数据库的cursor没有关闭 
  2.构造adapter时,没有使用缓存contentview 
    衍生listview的优化问题-----减少创建 view的对象,充分使用
contentview,可以使用一静态类来优化处理getview的过程/ 
   
3.Bitmap对象不使用时采用recycle()释放内存 
  4.activity中的对象的生命周期大于activity 
  调试方法: DDMS==> HEAPSZIE==>dataobject==>[Total Size] 
  还有其他问题,大家欢迎提出阿,可以是整体架构的,还有这个Hal层. 
    这篇文章会涉及到以下几个内容 
     
一    Activity的生命周期 
  二   让Activity变成一个窗口:Activity 属性设定 
  三   你后台的Activity被系统 
回收怎么办:onSaveInstanceState 
   
四   调用与被调用:我们的通信使者 - Intent 
  一 Activity的生命周期 
  和其他手机  平台  的应用程序一样,Android的应用程序的生命周期是被统
一掌控的,也就是说我们写的应用程序命运掌握在别人(系统)的手里,我们不
能改变它,只能学习并适应它。 
   
简单地说一下为什么是这样:我们手机在运行 一个应用程序的时候,有可能打进来电话发进来短信,或者没有电了,这时候程
序都会被中断,优先去服务电话的基本功能,另外系统也不允许你占用太多资源,
至少要保证电话功能吧,所以资源不足的时候也就有可能被干掉。言归正传,
Activity的基本生命周期如下代码所示: 
     
Java 代码 
  public class MyActivity extends Activity 
{      
protected void onCreate(Bundle savedInstanceState);         
protected void onStart();         
protected void onResume();      
protected void onPause();         
protected void onStop();      
protected void onDestroy();    
}      
你自己写的Activity会按需要 
重 载这些方法,onCreate是免不了的,在一个Activity正常启动的过程中,
他们被调用的顺序是 onCreate  -> onStart  ->onResume, 在Activity被干掉的
时候顺序是onPause  -> onStop  -> onDestroy ,这样就是一个完整的生命周期,
但是有人问了 
,程序正运行着呢来电话了,这个程序咋办?中止了呗,如果中止的时候新出的
一个Activity是全屏的那么:onPause->onStop ,恢复的时候
onStart->onResume ,如果打断 
这个应用程序的是一个Theme为Translucent 或者Dialog 的Activity那么只
是onPause ,恢复 
的时候onResume 。 
   
详细介绍一下这几个方法中系统在做什么以及我们应该做什么:      
onCreate: 
在这里创建界面,做一些数据的初始化工作 
  onStart: 
到这一步变成用户可见不可交互的 
  onResume: 
变成和用户可交互的,(在activity 栈系统通过栈的方式管理这些个Activity
的最上面,运行完弹出栈,则回到上一个Activity) 
  onPause: 
到 这一步是可见但不可交互的,系统会停止动画等消耗CPU 的事情从上文的描
述已经知道,应该在这里保存你的一些数据,因为这个时候你的程序的优先级降
低,有可能被系统收回。在这里保存的数据,应该在 onResume里读出来,注意:
这个方法里做的事情时间要短,因为下一个activity不会等到这个方法完成才
启动 
  onstop: 
变得不可见,被下一个activity覆盖了 
  onDestroy: 这是activity被干掉前最后一个被调用方法了,可能是外面类调
用finish方法或者是系统为了节省空间将它暂时性的干掉,可以用 
isFinishing()来判断它,如果你有一个Progress Dialog在线程中转动,请在
onDestroy里把他cancel掉,不然等线程结束的时候,调用Dialog的cancel
方法会抛异常的。 
   
onPause,onstop, onDestroy,三种状态下 activity都有可能被系统干掉为
了保证程序的正确性,你要在onPause()里写上持久层操作的代码,将用户编辑
的内容都保存到存储介质上(一般 都是数据库)。实际工作中因为生命周期的
变化而带来的问题也很多,比如你的应用程序起了新的线程在跑,这时候中断了,
你还要去维护那个线程,是暂停还是杀 掉还是数据回滚,是吧?因为Activity
可能被杀掉,所以线程中使用的变量和一些界面元素就千万要注意了,一般我都
是采用Android的消息机制 [Handler,Message]来处理多线程和界面交互的问
题。这个我后面会讲一些,最近因为这些东西头已经很大了,等我理清思绪再跟
大家分享。 
     二   让Activity变成一个窗口:Activity属性设定 
  讲点轻松的吧,可能有人希望做出来的应用程序是一个漂浮在手机主界面的东
西,那么很  简单你只需要设置一下Activity的主题就可以了在
AndroidManifest.xml 中定义 Activity的地方一句话: 
  Xml代码 
  android 
:theme="@android:style/Theme.Dialog"   
  android:theme="@android:style/Theme.Dialog" 
这就使你的应用程序变成对话框的形式弹出来了,或者  Xml代码 
  android:theme="@android:style/Theme.Translucent" 
android:theme="@android:style/Theme.Translucent" 
就 变成半透明的,[友情提示-.-]类似的这种activity的属性可以在
android.R.styleable 类的AndroidManifestActivity 方法中看到,
AndroidManifest.xml中所有元素的属性的介绍都可以参考这个类
android.R.styleable 
     
上面说的是属性名称,具体有什么值是在android.R.style中 
可以看到,比如这个"@android:style/Theme.Dialog"就对应于
android.R.style.Theme_Dialog ,('_'换成'.' <--注意:这个是文章内容不是
笑脸)就可以用在描述文件 
中了,找找类定义和描述文件中的对应关系就都明白了。 
     
三     你后台的Activity被系统回收怎么办:onSaveInstanceState 
  当你的程序中某一个Activity A 在运行时中,主动或被动地运行另一个新的
Activity B       这个时候A会执行 
   
   Java代码 
  public   
void onSaveInstanceState(Bundle outState) {         
super.onSaveInstanceState(outState);       
outState.putLong("id", 1234567890);    
}   
public void 
onSaveInstanceState(Bundle outState) {      
B 完成以后又会来找A, 这个时候就有两种情况,一种是A被回收,一种是没有
被回收,被回  收的A就要重新调用onCreate()方法,不同于直接启动的是这
回 onCreate()里是带上参数  savedInstanceState,没被收回的就还是
onResume就好了。 
  savedInstanceState是一个Bundle对象,你基本上可以把他理解为系统帮你
维护的一个Map对象。在onCreate()里你可能会用到它,如果正常启动onCreate
就不会有它,所以用的时候要判断一下是否为空。 
   
Java代码 
  if(savedInstanceState !=null){    
        long id =savedInstanceState.getLong("id");   
}   
if(savedInstanceState !=null){         
就像官方的Notepad教程 
里的情况,你正在编辑某一个note,突然被中断,那么就把这个note的id记
住,再起来的时候就可以根据这个id去把那个note取出来,程序就完整一些。
这也是看你的应用需不需要保存什么,比如你的界面就是读取一个列表,那就不
需要特殊记住什么,哦, 
没准你需要记住滚动条的位置...   四      调用与被调用:我们的通信使者Intent 
     
要 说Intent了,Intent就是这个这个意图,应用程序间Intent进行交流,打
个电话啦,来个电话啦都会发Intent, 这个是Android架构的松耦合的精髓部
分,大大提高了组件的复用性,比如你要在你的应用程序中点击按钮,给某人打
电话,很简单啊,看下代码先: 
     
Java代码 :   
Intent intent = new Intent();    
intent.setAction(Intent.ACTION_CALL);    
intent.setData(Uri.parse("tel:"+ number));    
startActivity(intent);   复制代码 
扔出这样一个意图,系统看到了你的意图就唤醒了电话拨号程序,打出来电话。
什么读联系人,发短信啊,邮件啊,统统只需要扔出intent就好了,这个部分
设计地确实很好啊。 
     
那Intent通过什么来告诉系统需要谁来接受他呢? 
  通常使用Intent有两种方法,第一种是直接说明需要哪一个类来接收代码如
下: 
     
Java代码 
  Intent intent = new Intent(this,MyActivity.class);    
intent.getExtras().putString("id","1");    
startActivity(intent);    
Intent intent = new 
Intent(this,MyActivity.class);intent.getExtras().putString("id","1");
tartActivity(intent);复制代码 第一种方式很明显,直接指定了MyActivity 为接受者,并且传了一些数据给
MyActivity,在MyActivity里可以用getIntent()来的到这个 intent 和数据。  
     
第二种就需要先看一下AndroidMenifest中的 intentfilter的配置了 
    Xml代码 
  <intent-filter>      
<action android:name="android.intent.action.VIEW" />   
<action android:value="android.intent.action.EDIT" />    
<action android:value="android.intent.action.PICK" />       
<category android:name="android.intent.category.DEFAULT"/>    
<data android:mimeType="vnd.android.cursor.dir/vnd.google.note" />   
</intent-filter>   
   
<intent-filter>       
<action android:name="android.intent.action.VIEW"/>       
<action android:value="android.intent.action.EDIT" />       
<action android:value="android.intent.action.PICK" />       
<category android:name="android.intent.category.DEFAULT" />       
<data android:mimeType="vnd.android.cursor.dir/vnd.google.note" /> 
</intent-filter> 
这里面配置用到了action, data, category 这些东西,那么聪明的你一定想到
intent里也会有这些东西,然后一匹配不就找到接收者了吗? 
  action其实就是一个意图的字符串名称。 
  上 面这段intent-filter的配置文件说明了这个Activity可以接受不同的 
Action,当然相应的程序逻辑也不一样咯,提一下那个 mimeType,他是在ContentProvider里定义的,你要是自己实现一个ContentProvider 就知道了,
必须指定 mimeType才能让数据被别人使用。 
     
不知道原理说明白没,总结一句,就是你调用别的界面不是直接 new那个界面,
而是通过扔出一个intent,让系统帮你去调用那个界面,这样就多么松藕合啊,
而且符合了生命周期被系统管理的原则。 
  想知道category都有啥,Android为你预先定制好的action都有啥等等,请
亲自访问官方链接Intent 
  ps:想知道怎么调用系统应用程序的同学,可以仔细看一下你的logcat,每次
运行一个程序的时候是不是有一些信息比如: 
   
Starting activity: Intent 
{action=android.intent.action.MAINcategories={android.intent.category
.LAUNCHER}flags=0x10200000comp={com.android.camera/com.android.camera
.GalleryPicker} } 
  再对照一下Intent的一些set方法,就知道怎么调用咯,希望你喜欢:) 
     
一,listview你是怎么优化的。 
二,view的刷新,之前说过 
三,IPC及原理 
四,Android多线程 
五,Android为什么要设计 4大组件,他们之间的联系,不设计行不行(主要是
为了实现MVC模式,然而java中最难的模式也是这个,很少有产品能将这个模
式做得很好【Technicolor的面试官问的这个】) 
六,service的周期,activity的周期,谈下你对Android内部应用的了解,比
如他做电话,以及联系人等等应用。框架层有很多东西还是多看看,熟悉 Android
怎么做的,不管你做应用程开发还是应用框架层开发很有好处的。 
   在就是你项目经验,突出你遇到什么难点,然后是怎么解决的!尽量将每个技术
点凸显出来,当然面试官有时候会为了体现你是否真正做过,他会问你,你在这
个应用中做那个模块,用了多少个类之类的问题。 
   
偶尔有的面试官会问你,你用过Android自带的单元测试了没,怎么用的? 
   
当然我面试过很多家单位,有的是做平板,手机,数字电视,有的是做出个 erp
之类的客户端等等,出于前面的三个,基本上都是将 Android的全部改掉,如果
真正要做Android的话,大家要学的还很多。 
     
总 之,一句话,什么样的面试官都有,去面试的时候要做好一切心理准备,不
管是技术还是基础都得扎实。一个人的交谈能力也很重要,总之不是非常标准的
普通话, 最起码你说的得让别人听得懂,而且得把面试官讲得非常彻底,这样
你获得offer的机会更大,谈工资也有优势~~当然曾经一家公司的面试官跟我说
过,技术 是不惜钱的,只要你有能力,多少钱他都请。 
    1.View如何刷新? 
  2.DDMS与TraceView的区别? 
  3.activity被回收了怎么办? 
  4.在Java中如何引入 C语言? 
   
参考答案 : 
  1.View 可以调用invalidate()和postInvalidate()这两个方法刷新 
  2.DDMS是一个程序执行查看器,在里面你可以看见线程和堆栈等信息,
TraceView是程序性能分析器 
  3.activity回收了,那就只有另起了 
  4.java调用C语言程序,可以用JNI接口来实现 
  上面答案仅作参考,毕竟我个人能力也有限嘛,难免会回答错误,呵呵..... 
解答:   1.View受系统刷新(系统内部有个循环,监控事件、做业务处理、绘UI),
可以用postInvalidate()促使系统刷新。 
  2.(还真不知道) 
  3.请参照Activity生命周期,如果被系统destroy了,也就是说的回收,只
有从新start了 
  4.通过JNI调用。建议阅读《The Java Native InterfaceProgrammer's Guide 
and Specification》,英文版的,从sun网站下吧。 
 

好吧,问的有点偏题了。
其实 总结下:
  1.如果你可能刚毕业,接触Android大半年或是培训过,有几个好不错的demo项目并且能理清里面的思路,要的4-6千水平的薪资,你是个踏实的人。对于面试,能知道大部分的基础知识,了解一个项目的流程,并且有上进心,那就很不错了。你知道自己能干什么,也会知道你还要干什么。因为你不可能把薪水局限在这么点吧。
  2.如果你有1年上未满两年Android开发经验。至少你跟团队完成1-2款成熟的商业项目,熟悉这个项目流程,至少参与30%以上编码。完全熟悉网络协议和处理。实现多种自定义的控件等,那么你要个8-10k上下的薪资,过年过节发个奖金,也算是个性情中人。对于面试时,你基本可以直接和面试官交流你的项目的过程和成果,你自己对项目的改进优化的看法,用的觉得自己比较出彩的技术,以及那些难点或是顽固性bug的解决。
  3.这第三条其实不太好总结了。因为没见过,或是没法定位。熟悉多平台开发。3年以上工作经验,1年ios,2以上年的Android。基本开的要求都在1.5-2w了。仅是开工资的这其实也不算太高,因为如果你真有这方面多平台开发经验,我想,你不仅仅只是个开发工程师的角色了。走技术还是产品,也是个人爱好了。参与过几个平台至少1款商业项目的整体开发,当然如果是独立开发过,那就更加出色了。因为这比纯粹的拿到一个半成品的项目增加或是修改来的难度高多了。然后或是有线上的app应用,无论下载量如何,至少你开始有自己的想法了。
并且这样水品的人除了工资要求,可能还会考虑其他的福利问题。那面试中问到的问题就多了。
  4.这边突然发现中间断了一层。一般市场开1-1.5w的开发人员。那么这部分可能已经可以担任一个中小级项目的项目经理了,至少他应该独立完成过一款产品(不包含视觉,交互,美工设计)。那么就可以问下对于应用优化,有利于团队协作管理的方面的问题。版本控制,自动打包测试。也就是上面我简单总结的几方面的问题。
本人其实也不懂,只不过有这方面的人来面试,我觉得吧,总的问几个别太二逼的问题吧。并且意义性比较大。顺便也能提高下自己。

猜你喜欢

转载自blog.csdn.net/qq_41118173/article/details/80528580