二、 Service 1、Service 是否在 main thread 中执行, service 里面是否能执行耗时的操 作? 默认情况,如果没有显示的指 servic所运行的进程, Service 和 activity 是运行在当前 app 所在进 程的 main thread(UI主线程)里面。 service 里面不能执行耗时的操作(网络请求,拷贝数据库,大文件 ) 特殊情况 ,可以在清单文件配置 service 执行所在的进程 ,让 service 在另外的进程中执行 android:name="com.baidu.location.f" android:enabled="true" android:process=":remote" >
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看作是通信使者。
动态注册:在代码中进行如下注册 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. 设计模式上(反转控制的一种应用,类似监听者模式)
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对象
七、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--; }
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?
A 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 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
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
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.
How do you pass the data to sub-activities android?
Using with Bundle, we can pass the data to sub activities.
Bundle bun =newBundle();
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.
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
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.
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
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.
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
Now we write the final step. Write the given below method in MainActivity,java file
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:
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:
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.
Enum是计算机编程语言中的一种数据类型---枚举类型。 在实际问题中,有些变量的取值被限定在一个有限的范围内。 例如,一个星期内只有七天 我们通常这样实现上面的定义:
public String monday;
public String tuesday;
public String wensday;
public String thursday
java.lang.IllegalStateException: No matching PlatformTransactionManager bean found for qualifier 'add' - neither qualifier match nor bean name match!
网上找了好多的资料没能解决,后来发现:项目中使用的是xml配置的方式配置事务,但是
原文:http://stackoverflow.com/questions/15585602/change-limit-for-mysql-row-size-too-large
异常信息:
Row size too large (> 8126). Changing some columns to TEXT or BLOB or using ROW_FORMAT=DYNAM
/**
* 格式化时间 2013/6/13 by 半仙 [email protected]
* 需要 pad 函数
* 接收可用的时间值.
* 返回替换时间占位符后的字符串
*
* 时间占位符:年 Y 月 M 日 D 小时 h 分 m 秒 s 重复次数表示占位数
* 如 YYYY 4占4位 YY 占2位<p></p>
* MM DD hh mm
在使用下面的命令是可以通过--help来获取更多的信息1,查询当前目录文件列表:ls
ls命令默认状态下将按首字母升序列出你当前文件夹下面的所有内容,但这样直接运行所得到的信息也是比较少的,通常它可以结合以下这些参数运行以查询更多的信息:
ls / 显示/.下的所有文件和目录
ls -l 给出文件或者文件夹的详细信息
ls -a 显示所有文件,包括隐藏文
Spring Tool Suite(简称STS)是基于Eclipse,专门针对Spring开发者提供大量的便捷功能的优秀开发工具。
在3.7.0版本主要做了如下的更新:
将eclipse版本更新至Eclipse Mars 4.5 GA
Spring Boot(JavaEE开发的颠覆者集大成者,推荐大家学习)的配置语言YAML编辑器的支持(包含自动提示,