Android is a free and open source operating system based on Linux. It is mainly used in mobile devices, such as smartphones and tablets. It is led and developed by Google and the Open Handset Alliance. We are constantly collecting and updating interview questions related to Android fundamentals. We have collected 100 questions so far.
1. Architecture of The Android system
- Android will ship with a set of core application packages, including an email client, SMS messaging app, calendar, maps, browser, contact manager, and more. All applications are written in the JAVA language.
- Developers have full access to the API framework (Android.jar) used by the core application. The architectural design of the application simplifies component reuse; Any application can publish its feature block and any other application can use its published feature block.
- Android contains C/C++ libraries that can be used by different components of the Android system. They serve developers through the Android application framework.
- Android relies on the Linux 2.6 kernel for its core system services, such as security, memory management, process management, network protocol stack, and driver model. The Linux kernel also acts as an abstraction layer between hardware and software stacks.
2. Activity lifecycle
Activity lifecycle methods include onCreate(), onStart(), onResume(), onPause(), onStop(), onDestroy(), and onRestart().
- Start an Activity by executing onCreate(), onStart(), and onResume() methods respectively.
- Start an Activity from an Activity B Activity executes A onPause(), B onCreate(), B onStart(), B onResume(), and A onStop(), respectively.
- Stop the B Activity and execute the B onPause(), A onRestart(), A onStart(), A onResume(), B onStop(), and B onDestroy() methods respectively.
- If the android:configChanges property is not set in the listing file, To destroy the onPause (), onStop () and onDestroy () to create the onCreate (), onStart () and onResume () method, set the orientation | screenSize (must appear at the same time) when the attribute value, don’t walk life cycle method, Only the onConfigurationChanged() method is executed.
- The onPause() and onStop() methods are special. Do not add too many time-consuming actions to onPause() when switching between activities; otherwise, the experience will be affected.
3.Fragment life cycle
Fragment life cycle
Fragment vs. Activity lifecycle comparison
The Fragment lifecycle methods include onAttach(), onCreate(), onCreateView(), onActivityCreated(), onStart (), onResume(), onPause(), onStop(), and onDes TroyView (), onDestroy(), onDetach() and 11 other methods.
- Switch to the Fragment and execute onAttach(), onCreate(), onCreateView(), onActivityCreated(), onStart (), and onResume() respectively.
- Lock the screen and execute onPause() and onStop() respectively.
- If the screen is on, execute onStart () and onResume() respectively.
- Overwrite, switch to other fragments, and execute onPause(), onStop(), and onDestroyView() methods respectively.
- Return to the previous Fragment from other fragments and execute onCreateView(), onActivityCreated(), onStart (), onResume(), respectively.
4.Service life cycle
In the life cycle of a Service, the following are commonly used:
Four manually called methods
StartService () Starts the service stopService() Stops the service bindService() binds the service unbindService() unbinds the serviceCopy the code
Five methods that are automatically invoked internally
OnCreat () creates the service onStartCommand() starts the service onDestroy() destroys the service onBind() binds the service onUnbind() unbinds the serviceCopy the code
- The internal methods onCreate() and onStartCommand() are automatically called. If a Service is started by startService() several times, onCreate() is called only once.
- If a Service is started and bound, it cannot be stopped if stopService() is used to stop the Service without unbinding.
- After calling bindService() manually, the internal methods onCreate() and onBind() are automatically called.
- After calling unbindService() manually, the internal methods onUnbind(), onDestory() are automatically called.
- StartService () and stopService() can only start or stop a Service, but cannot operate it. The Service still exists after the caller exits. BindService () and unbindService() can operate on services, which are destroyed with the caller after the caller exits.
5. The animation in the Android
Android animation: Frame animation, tween animation, and property animation (Android 3.0 onwards)
The frame of animation
Frame animation is one of the easiest animations to achieve. This kind of animation relies more on perfect UI resources. Its principle is to continuously play individual pictures, so as to produce a visual effect of animation. It’s kind of like the way some software makes ANIMATED giFs. In some code, we will also see Android: oneshot=”false”, which means the animation executes once (true) or the loop executes multiple times.
<? xml version="1.0" encoding="utf-8"? > <animation-list xmlns:android="http://schemas.android.com/apk/res/android"> <item android:drawable="@drawable/a_0" android:duration="100" /> <item android:drawable="@drawable/a_1" android:duration="100" /> <item android:drawable="@drawable/a_2" android:duration="100" /> </animation-list>Copy the code
Filling between animation
The tween animation can be divided into four types: alpha, translate, scale, and rotate. The realization of tween animation is generally in the form of XML files. The code will be easier to write and read, as well as easier to reuse. Interpolator mainly controls the rate of change of an animation, the pace at which it is interpolated. Pivot determines the reference position for the current animation execution
<? xml version="1.0" encoding="utf-8"? > <set xmlns:android="http://schemas.android.com/apk/res/android" android:interpolator="@[package:]anim/interpolator_resource" android:shareInterpolator=["true" | "false"] > <alpha android:fromAlpha="float" android:toAlpha="float" /> <scale android:fromXScale="float" android:toXScale="float" android:fromYScale="float" android:toYScale="float" android:pivotX="float" android:pivotY="float" /> <translate android:fromXDelta="float" android:toXDelta="float" android:fromYDelta="float" android:toYDelta="float" /> <rotate android:fromDegrees="float" android:toDegrees="float" android:pivotX="float" android:pivotY="float" /> <set> ... </set> </set>Copy the code
Attribute animation
Property animation, as the name suggests, is animation of object properties. Therefore, all the contents of tween animation can be realized through property animation. Property animation works by continually manipulating values, and ValueAnimator is the class that calculates the animation transition between an initial value and an end value. It uses a time-loop mechanism to calculate the animation transition from value to value. We simply provide ValueAnimator with the initial and end values and tell it how long the animation needs to run. ValueAnimator will automatically smooth the transition from the initial value to the end value. ValueAnimator is also responsible for managing the number of times an animation is played, how it is played, and setting up listeners for the animation.
6. Four components of Android
- Activity: An Activity is a window for Android applications to interact with users. It is one of the most basic Android building blocks. It needs to do a lot of persistent things to maintain the state of various aspects, properly manage the life cycle and some jump logic.
- BroadCast Receiver: Receives one or more intents as trigger events, receives relevant messages, performs some simple processing, and converts them into a Notification, unifying the event BroadCast model of Android.
- The Content Provider: Content Provider is a third-party application data access solution provided by Android. It can be derived from Content Provider class to provide external data, which can be selected and sorted like a database. It shields internal data storage details and provides a unified interface model to external data, greatly simplifying upper-layer applications and providing a more convenient way for data integration.
- Service: The background serves the Activity, encapsulates a complete functional logic implementation, receives upper-level instructions, completes related transactions, defines the Intent to receive, and provides synchronous and asynchronous interfaces.
7. Common Android layouts
Common layouts:
FrameLayout: everything is placed one by one in the top left corner, which is overlapping LinearLayout: a layout that displays data horizontally and vertically using a single element as a referenceCopy the code
Uncommon layout:
TableLayout: AbsoluteLayout each table contains a TableRow TableRow, which can be used to specify each element (used on Android TV) AbsoluteLayout: use X and Y coordinates to specify the position of the element. (For use on set-top boxes)Copy the code
New Layout:
PercentRelativeLayout allows you to control the size of your control by percentage. PercentFrameLayout controls size by percentage.Copy the code
8. Notification push
- Plan 1: Use aurora and Friendly Alliance push.
-
Solution 2: Use XMPP protocol (Openfire + Spark + Smack)
- Introduction: The communication protocol based on XML, formerly known as Jabber, has been standardized by IETF.
- Advantages: The protocol is mature, powerful and scalable. It is mainly used in many chat systems, and there is an open source Java version of the development example AndroidPN. Disadvantages: Complex protocols, redundancy (based on XML), high traffic and power consumption, and high hardware deployment cost.
-
Option 3: Use the MQTT protocol (see mqTT.org/ for more information)
- Summary: Lightweight, proxy-based publish/subscribe messaging protocol.
- Advantages: The protocol is simple, compact, scalable, save traffic, save power, has been applied to the enterprise field (see: mqtt.org/software), and…
- Disadvantages: immature, complex implementation, server component RSMB is not open source, high cost of deployment hardware.
- Scheme 4. Use HTTP round robin
- Description: Periodically obtains the latest messages from the HTTP server API.
- Advantages: Simple implementation, strong controllability, and low hardware deployment cost.
- Disadvantages: Poor real-time.
9. Android data store
- Store data using SharedPreferences; It is a mechanism provided by Android to store some simple configuration information in XML format to the device. It can only be used within the same package, not between different packages.
- File storage data; File storage is a common method. The method of reading/writing files in Android is exactly the same as that of implementing I/O programs in Java. OpenFileInput () and openFileOutput() methods are provided to read files on the device.
- SQLite database stores data; SQLite is a standard database that comes with Android. It supports SQL statements. It is a lightweight embedded database.
- Use ContentProvider to store data; It is used to exchange data between applications so that other applications can save or read the various data types of the Content Provider.
- Network storage data; Upload (store) and download (get) the data information we store in cyberspace through the storage space provided to us on the network.
10. Start the Activity mode
Before introducing the Android startup mode, let’s introduce two concepts: Task and taskAffinity
- Task: a group of activities that are associated with each other. Tasks exist in a data structure called the back stack. In other words, tasks manage activities in the form of a stack, which is also called a “task stack.”
- TaskAffinity: “The task that The activity has an affinity for.”, which can be translated as activity-related or affinity tasks, identifies The name of The task stack required by an activity. By default, the name of the task stack required by all activities is the application package name. The taskAffinity attribute is used primarily in pairs with the singleTask start mode or allowTaskReparenting attribute.
Four boot modes
- Standard: the default startup mode. If Activity A starts Activity B, activity B will run in the same stack as Activity A. And each time an Activity is started, a new instance is created, regardless of whether the instance already exists in the task. An error occurs when a non-activity context (such as ApplicationContext) starts an Activity in standard mode. A non-activity context does not have a task stack, and the system reports an error because of point 1 above. The workaround is to specify the FLAG_ACTIVITY_NEW_TASK bit for the Activity to be started so that the system creates a new task stack for it when it starts. The Activity to be started is actually in singleTask mode.
- SingleTop: Top of stack reuse mode. If activity A starts Activity B, the task at the top of A’s stack is determined to be an instance of B. If it is, instead of creating a new instance of activity B, it refers directly to the top of the stack instance. The onNewIntent method is called back, and the parameters of this method get the information about the current request. If not, a new instance of Activity B is created.
- SingleTask: In-stack reuse mode. When you start the Activity for the first time, a new task is created and an instance of the Activity is initialized at the bottom of the new task. But it has to meet certain conditions. The taskAffinity attribute needs to be set. As mentioned earlier, the taskAffinity attribute is used in conjunction with the singleTask pattern.
- SingleInstance: single-instance mode. This is an enhanced version of the singleTask mode. In addition to all the features of the singleTask mode, it has a unique feature, that is, the Activity in this mode can only live in a singleTask stack, and does not coexist with other activities in the same task stack.
11. Broadcast registration
Start by writing a class that extends from BroadCastReceiver
First: declare in the manifest file and add
<receive android:name=".BroadCastReceiverDemo">
<intent-filter>
<action android:name="android.provider.Telephony.SMS_RECEIVED">
</intent-filter>
</receiver>Copy the code
Second: use code to register such as:
IntentFilter filter = new IntentFilter("android.provider.Telephony.SMS_RECEIVED");
BroadCastReceiverDemo receiver = new BroadCastReceiver();
registerReceiver(receiver, filter);Copy the code
The differences between the two types of registration are as follows: a. The first type is resident broadcast, which means that when the application is closed, if there is a message broadcast, the application will be automatically run by system call. B. The second type is not resident broadcasting, that is, broadcasting follows the life cycle of the program.
12. The ANR in Android
ANR full name Application Not responding
The maximum execution time of an Activity on Android is5Seconds. The maximum execution time of a BroadcastReceiver is10Seconds. The maximum execution time of a Service is20Seconds.Copy the code
An ANR is generated when execution time is exceeded. Note: ANR is an exception thrown by the system and cannot be caught by the program.
Solutions:
- Any method that runs in the main thread does as little as possible. In particular, an Activity should do as few create operations as possible in its key lifecycle methods (such as onCreate() and onResume()). (This can be done by restarting the child thread and then using Handler+Message to do some operations, such as updating the UI in the main thread.)
- Applications should avoid time-consuming operations or calculations in the BroadcastReceiver. Instead of doing this in a child thread (because of the BroadcastReceiver’s short life span), applications should start a Service if a time-consuming action needs to be performed in response to an Intent broadcast.
13. ListView optimization
- ConvertView reuse, use convertView to reuse views, don’t create new getView() every time. The core principle of ListView is to reuse the View. If the reuse View does not change the width and height, reuse View can reduce the frequent memory allocation/reclamation caused by cache redistribution.
- ViewHolder optimization. The reason for using ViewHolder is that the findViewById method takes a lot of time. If there are too many controls, performance will be seriously affected. Get the View directly with setTag and getTag.
- Reduce the layout level of Item View, which all layouts must follow, too deep layout level will directly lead to View measurement and drawing waste a lot of time.
- The getView method in Adapter uses as little logic as possible
- Image loading uses a three-level cache to avoid reloading every time.
- Try turning on hardware acceleration to make the ListView slide more smoothly.
- Use RecycleView instead.
14.Android digital signature
- All applications must have a digital certificate, and Android will not install an application without one
- Digital certificates used by Android packages can be self-signed and do not need to be signed by an authoritative digital certificate authority
- To officially release an Android, the program must be signed using a digital certificate generated by a suitable private key.
- Digital certificates have an expiration date, and Android only checks the expiration date when an application is installed. If the program has been installed in the system, the expiration of the certificate does not affect the normal function of the program.
15. The Android root system
Root means you have permission to “read”, “write” and “execute” all files on the system. Root machines don’t really give your applications root privileges. It works like a Linux command like sudo. Run the su program in the bin directory of the system. The owner is root and has the suID permission. The commands executed using su have the Android root permission. Of course, it is not easy to copy the /system/bin directory with temporary user permissions and change properties. There are two tools and two commands. Copy BusyBox to a directory you have permission to access and give it 4755 permission. You can do a lot of things with busyBox.
View, surfaceView, GLSurfaceView
View
Display view, built-in canvas, graphics drawing function, touch screen event, button event function, etc., must update the screen in the UI main thread, the speed is slow
SurfaceView
View class based on view view extension, more suitable for 2D game development, is a subclass of View, similar to the use of double slow mechanism, in the new thread to update the screen so refresh the interface faster than view
GLSurfaceView
Based on the SurfaceView view again extended view class, dedicated to 3D game development view, is a subclass of SurfaceView, openGL dedicated
AsyncTask
Three generic arguments to AsyncTask
- First argument: The type of argument passed to the doInBackground() method
- Second argument: The argument type passed to the onProgressUpdate() method
- Third argument: the type of argument passed to the onPostExecute() method, which is also returned by the doInBackground() method
Methods run on the main thread:
OnPostExecute () onPreExecute() onProgressUpdate(Progress...)Copy the code
Methods run on child threads:
The doInBackground ()Copy the code
Methods to stop AsyncTask:
cancel(boolean mayInterruptIfRunning)Copy the code
The execution of AsyncTask is divided into four steps
- AsyncTask inheritance.
- Implement one or more of the following methods defined in AsyncTask: onPreExecute(), doInBackground(Params…) And onProgressUpdate (Progress…). , onPostExecute (Result).
- The execute method must be called in the UI Thread.
- The task can be executed only once. Otherwise, an exception occurs when the task is invoked multiple times. If the task is canceled, cancel is invoked.
17.Android i18n
I18n is called internationalization. Android provides excellent support for i18N and L10n. Software in RES/VALes and other folders with language modifiers. For example: values-zh These folders provide language, style, size XML resources.
18.NDK
- NDK is a set of tools that help developers quickly develop C/C++ dynamic libraries and automatically package SO and Java applications into APK packages.
- The NDK integrates the cross-compiler and provides differences between mk files and isolated CPUS, platforms, etc. Developers can create SO files by simply modifying mk files.
19. When you start a program, you can either click the icon on the main interface to enter it or jump to it from a program. What’s the difference?
Enter through the main screen, which is to set the default activity to start. In the activity tag of the manifest.xml file, write the following code
< intent - filter > < intent android: name = "android. Intent. Action. The MAIN" > < intent The android: name = "android: intent. The category. The LAUNCHER" > < / intent - filter >Copy the code
Jumping from another component to a target activity requires an intent. specific
Intent intent=new Intent(this,activity.class),startActivity(intent)Copy the code
20. What is the difference between an overflow and a leak? When will a memory leak occur?
Memory overflow: A memory overflow occurs when the memory required by the program to run is greater than the maximum memory allowed by the program.
Memory leak: In some resource-consuming operations, a memory leak can occur if memory is never freed during the operation. For example, I/O cursor is not closed.
21. What is the function of the EF file of sim card
A SIM card is a phone card. It has its own operating system and is used to communicate with a mobile phone. Ef files are used to store data.
22. How many states are there for an Activity?
Run pause stopCopy the code
23. Make the Activity a window
Set the activity style property = “@ android: style/Theme. The Dialog”
Android :gravity differs from Android :layout_gravity
Gravity: indicates the alignment of elements within the component. Layout_gravity: indicates the alignment of components in this view relative to the parent container
25. How do I exit the Activity
End the current Activity
Finish()
killProgress()
System.exit(0)Copy the code
When you close the application, end all activities
You can create a List of activities, place an instance of that activity into the List each time you create an activity, and at the end of the program, loop out the activity instance from the collection and call Finish ()
26. If the background Activity is reclaimed by the system for some reason, how to save the current state before being reclaimed by the system?
Call onSavedInstanceState() in the onPuase method
27.Android length unit details
Px: Pixels Sp and DP are also units of length, but are independent of the unit density of the screen.Copy the code
28. The relationship between activities, services, and intEnts
All three of these are components that android apps use a lot. Activity and Service are the four core components. An Activity is used to load a layout and display a window interface. A service runs in the background and does not display a interface. An intent is a messenger between an Activity and a service.
29. What other methods can be used to pass parameters between activities besides Intent, broadcast receiver, and contentProvider?
Fie: file storage. The sharedPreferecnces static variable is recommended.Copy the code
30. What is an Adapter? Which adapters have you been in contact with?
Is an adapter that provides data adaptation for lists. Often use the adapter baseadapter, arrayAdapter, SimpleAdapter, cursorAdapter, SpinnerAdapter, etc
31. How do fragments and activities transfer values and interact?
Fragments objects have a getActivity method, the method and the activity interaction using framentmentManager. FindFragmentByXX can obtain fragments object, Operate directly on the Fragment object in the activityCopy the code
32. How do I update the data in the Listview if the data source in the Listview changes
Use the Adapter’s notifyDataSetChanged method
33. The life cycle of the broadcast recipient?
Broadcast receivers have a very short life cycle. After the onRecieve method is executed, the broadcast is destroyed. The broadcast receiver cannot perform long operations on the broadcast receiver. Do not create child threads on the broadcast receiver. After the broadcast receiver completes the operation, the process becomes empty and can be reclaimed easilyCopy the code
34. How is ContentProvider different from SQLite?
Contentproviders hide the internal implementation from the outside, and focus only on the URI that accesses the ContentProvider, which is shared between applications. Sqlite operates on the application's database. ContentProiver allows you to add, delete, modify, and query local filesCopy the code
35. How do I save the state of my activity?
By default, the state of an activity is automatically saved, and sometimes you need to manually save it.
After onPause or onStop, the activity is inactive, but the activity object still exists. When running out of memory, activities after onPause or onStop may be destroyed by the system.
When exiting an activity by returning, the activity state is not saved.
To save the activity state, you need to override onSavedInstanceState() and call onSavedInstanceState before executing onPause and onStop. OnSavedInstanceState requires a Bundle parameter that we can save to the Bundle and pass to the onSavedInstanceState method as an argument.
After the Activity is destroyed, the onCreate method accepts the saved bundle parameter and retrieves the previous data when the Activity is restarted.
36. What are the differences between Activities, context, and Application in Android?
Both Content and Application inherit from contextWrapper, and contextWrapper inherits from Context.
Context: represents the current Context object, which holds the parameters and variables in the Context. It makes it easier to access some resources.
Context is usually the same as an activity’s life cycle; application represents the object of the entire application.
For longer life cycles, use application instead of context.
Use static inner classes instead of inner classes in your activity. The inside exists as a member of an external class, not independent of the activity. If there is memory in memory that continues to reference the context, the context does not end if the activity is destroyed.
37. Check whether services are executed in the main thread and whether time-consuming operations can be performed in the Service.
By default, services are executed in the main thread. When a service is running in the main thread, do not perform time-consuming operations such as network connections or file copying.
38. Are Service and Activity on the same thread
By default, services and activities are in the same Thread, both in the main Thread, or UI Thread.
If you specify the process attribute of a service in the manifest file, the service runs in another process.
39. Can you play toast in the Service
You can.
40. Can the service lifecycle onstartConmand() perform network operations? How do I perform network operations in a Service?
Yes, execute in the onstartConmand method.
41. Talk about the relationship between ContentProvider, ContentResolver, and ContentObserver
ContentProvider: content providers, provide data of operation, the ContentProvider. NotifyChanged (uir) : contentResolver can update the data: Content analysis, parsing the ContentProvider returned data ContentObServer: content the listener, the change of the monitoring data, contentResolver. RegisterContentObServer ()Copy the code
42. How does ContentProvider implement data sharing
ContentProvider is an interface that provides data to the outside world. Implement the ContentProvider interface and rewrite the query, INSERT, getType, delete, update methods. Finally, define the access URI for the contentProvider in the manifest file
43. What types of data can be transmitted when an Intent delivers data?
Basic data types and corresponding array types can be passed as bundles, but bundle data must implement the Serializable or Parcelable interfacesCopy the code
44. What is the difference between Serializable and Parcelable?
Parcelable is recommended if stored in memory, as serialiable produces a large number of temporary variables during serialization and can cause frequent GC
If stored on hard disks, Serializable is recommended, although Serializable is less efficient
Implementation of Serializable: Simply implement the Serializable interface and a serialized ID will be automatically generated
Implementation of Parcelable: need to implement the Parcelable interface, also need the Parcelable.CREATER variable
45. Describe intEnts and Intentfilters
Intents are messengers for components that can pass messages and data between components. IntentFilter IntentFilter is an intent filter that filters the action, data, catgory, and URI attributes of an intent to determine the target component that matches the intent.Copy the code
46. What is IntentService? What are the advantages?
IntentService is a subclass of Service that adds additional functionality over regular Service. There are two problems with the Service itself:
A Service does not start a separate process. A Service is in the same process as its application. A Service is not dedicated to a new thread, so time-consuming tasks should not be handled directly within the Service;Copy the code
Characteristics of the
A separate worker thread is created to handle all Intent requests; A separate worker thread is created to handle the code that implements the onHandleIntent() method without having to deal with multithreading; IntentService stops automatically after all requests are processed, without calling stopSelf() to stop the Service; Provides the default implementation for Service onBind(), returnsnull; Provide a default implementation for Service onStartCommand that adds the request Intent to the queueCopy the code
use
Let the Service class inherit from IntentService and override the onStartCommand and onHandleIntent implementationsCopy the code
47. The introduction of broadcast mechanism in Android
The answer to this question from an MVC point of view (within the application) is to ask why Android has those four components, and the current mobile development model is basically the same MVC architecture as the Web, with a slight modification. The four components of Android are essentially to realize MVC architecture on mobile or embedded devices. Sometimes they are interdependent, sometimes they are complementary. The introduction of broadcast mechanism can facilitate the information and data interaction of these components.
Interprogram messaging (for example, listening for system calls within your own application)
Efficiency (see CONVENIENCE of UDP broadcast protocol on LAN)
In design mode (an application of reverse control, similar to listener mode)
48. How can ListView improve its efficiency?
When convertView is empty, use the setTag() method to bind each View to a ViewHolder object that holds the control. When convertView is not empty and reuses an already created view, the getTag() method is used to retrieve the bound ViewHolder, which avoids layer upon layer of findViewById searching for the control and quickly locate the control. Reuse ConvertView, use historical view, improve efficiency by 200%
Custom static ViewHolder class to reduce the number of findViewById. Increase efficiency by 50%
Load data asynchronously and load data paging.
Use WeakRefrence to reference the ImageView object
49. How does ListView implement pagination loading
SetOnScrollListener (new OnScrollListener{… }) there are two methods in the listener: a method that changes the scroll state (onScrollStateChanged) and a method that is called when the listView is rolled (onScroll)
SCROLL_STATE_TOUCH_SCROLL: touch sliding; Inertial scrolling (flGIN) : SCROLL_STATE_FLING: Glide, static state: SCROLL_STATE_IDLE: // static, handle different states:
Load the data in batches and only care about the rest state: care about the last visible item, and if the last visible item is the last one in the data adapter (collection), more data can be loaded. At each load, count the number of scrolls. When the number of scrolls is greater than or equal to the total number, the user can be reminded that there is no more data.
50. Can the ListView display multiple types of items
Each item displayed by the ListView is displayed by getView(Int Position,View convertView, ViewGroup parent) of the baseAdapter. In theory we could make each entry a different type of view.
For example, if an id=1 is retrieved from the server, then we load the item of type 1 when id=1 and type 2 when id=2. Common layouts are often seen in information clients.
Adapter also provides getViewTypeCount () and getItemViewType(int Position) methods. In the getView method we can load different layout files for different viewTypes.
51. How does the ListView locate to the specified position
You can use the lv.setSelection(ListView.getPosition ()) method provided by ListView.
How to embed ListView in ScrollView
Normally we don’t nest listViews in scrollViews.
Adding a ListView to a ScrollView results in an incomplete display of the ListView control, usually only one, due to conflicting scroll events between the two controls. Therefore, we need to calculate the display height of the ListView by the number of items in the ListView, so as to make it complete display.
The best way to handle this at this stage is to customize the ListView, override the onMeasure() method, and set all display.
53. What information is mainly contained in the manifest.xml file?
Manifest: The root node that describes all the contents of the package. Uses-permission: Requests the security permission your package needs to function properly. Permission: declares security permissions that restrict which programs can use components and functions in your package. Instrumentation: Specifies the code used to test this package or other package directive components. Application: The root node that contains the application-level component declaration in the package. Activity: Activity is the primary tool used to interact with users. Receiver: IntentReceiver Enables an application to obtain changes to data or operations that occur, even if it is not currently running. Service: A service is a component that can run in the background at any time. Provider: A ContentProvider is a component that manages persistent data and publishes it for use by other applications.Copy the code
54. How does the problem of image misplacement occur in ListView
The essence of the image mismatch problem comes from the fact that our ListView uses the cache convertView. Suppose a scenario where a ListView displays nine items on one screen, then when pulling out the tenth item, it actually reuses the first item. That is to say, when the first item downloads the picture from the network and finally displays it, in fact, the item is no longer in the current display area, and the result of display at this time may output the image on the tenth item, which leads to the problem of image dislocation. So the solution is to show it if you can see it, and not show it if you can’t.
55. The difference between Fragment replace and add methods
The Fragment itself does not have replace and add methods; the FragmentManager does. One architecture we often use is to toggle fragments through radiogroups, where each Fragment is a functional module.
The Fragment container is a FrameLayout that adds all fragments layer by layer. FrameLayout. Replace first removes other fragments from the container and then adds the current Fragment to the container.
Only one Fragment type can be added to a Fragment container. If you add more than one Fragment type, an exception will be raised and the program will terminate. Replace does not matter. Since each Fragment added by add can be added only once, you need to use the hide and show methods of the Fragment to switch between them. Show to be displayed, hide the rest. The life cycle of this process Fragment does not change.
When replacing a Fragment, the onDestroyView of the previous Fragment is executed each time, and the onCreateView, onStart, and onResume methods of the new Fragment are executed. Based on the above different characteristics, we must use our view and data in conjunction with the life cycle.
56. How do fragments achieve the same effect as Activity stacks?
The Fragment transaction manager maintains a two-way linked list structure that records every Fragment we add and replace, and then automatically destacks us when we click the back button.
57. Use of Fragment in your project
Fragment is a concept introduced after android3.0. It is more convenient to update local content. In order to reach this point, you need to put multiple layouts into one activity, now you can use multiple fragments instead.
Benefits of fragments:
Fragments enable you to split an activity into multiple reusable components, each with its own life cycle and UI. Fragments make it easy to create dynamic and flexible UI designs that can be adapted to different screen sizes. From phones to tablets. Fragment is a separate module that is tightly tied to an activity. Can dynamically remove, add, swap, etc. Fragment offers a new way to unify your UI across different Android devices. Fragment Solve the switching between activities is not smooth, light switching. Fragment replaces TabActivity for navigation with better performance. Fragments in4.2Version of the new nested fragment use method, can generate better interface effect.Copy the code
58. How do I toggle fragement without re-instantiating it
Taking a look at the Android Doc and some of the component source code, replace() is just a handy method to use when the previous Fragment is no longer needed.
The correct way to switch is to add(), hide(), add() another Fragment; To switch again, simply hide() the current and show() the other.
This allows you to switch multiple fragments without re-instantiating them:
59. How to perform performance analysis on Android applications
If you don’t consider using other third-party performance analysis tools, you can just use the tools in DDMS, which are already very powerful. Tools such as TraceView, heap, and Allocation Tracker in DDMS can help you analyze the execution time efficiency and memory usage of an application.
Traceview is an Android platform specific data acquisition and analysis tool, which is mainly used to analyze hotspot (bottleneck) in Android applications. Traceview itself is only a data analysis tool, and data collection needs to use the Debug class in the AndroidSDK or use DDMS tools.
The HEAP tool can help us check for places in our code that might cause a memory leak.
Allocation Tracker is a memory allocation tracking tool
60. How do I catch uncaught exceptions in Android
UncaughtExceptionHandler
To implement UncaughtExceptionHandler, call MyApplication to implement UncaughtExceptionHandler. Override UncaughtExceptionHandler onCreate and uncaughtException methods. Note: The above code simply prints out the exception. In the onCreate method we set the Thread class to a default exception handler. If this code does not execute, nothing will work. In uncaughtException we have to start a new thread to collect our exceptions and then kill the system. Application: < Application Android :name="com.example.uncatchexception.MyApplication"Copy the code
Bug collection tool Crashlytics
Crashlytics is a tool for saving and analyzing app crashes for mobile app developers. In China, umENG is mainly used for data statistics. Benefits of Crashlytics:1.Crashlytics doesn't miss any app crashes.2.Crashlytics can manage these crash logs like a Bug management tool.3.Crashlytics delivers daily and weekly crashes to your email inbox, all at a glance.Copy the code
61. How to publish SQLite database (Dictionary.db file) with APK file
Just place this file in the /res/raw directory. Files in the res\raw directory are not compressed, so files in the directory can be extracted directly and resource ids will be generated.
62. What is IntentService? What are the advantages?
IntentService is a subclass of Service that adds additional functionality over regular Service. There are two problems with the Service itself:
A Service does not start a separate process. A Service is in the same process as its application. A Service is not dedicated to a new thread, so time-consuming tasks should not be handled directly within the Service;Copy the code
Characteristics of IntentService
A separate worker thread is created to handle all Intent requests; A separate worker thread is created to handle the code that implements the onHandleIntent() method without having to deal with multithreading; IntentService stops automatically after all requests are processed, without calling stopSelf() to stop the Service; Provides the default implementation for Service onBind(), returnsnull; Provide a default implementation for Service onStartCommand that adds the Intent to the queue.Copy the code
63. Talk about your understanding of Android NDK
The NDK is a collection of tools. The NDK provides a set of tools to help developers quickly develop dynamic libraries in C or C++ and automatically package so and Java applications together as APK. These tools can be tremendously helpful to developers. The NDK integrates the cross-compiler and provides mk files to isolate CPU, platform,ABI, etc. Developers can create SO by simply modifying mk files (indicating “which files need to be compiled “,” compile feature requirements “, etc.).
The NDK can automatically package so and Java applications together, greatly reducing the developer’s packaging effort. The NDK provides a stable, limited API header declaration.
Google explicitly states that the API is stable and will support the currently released API in all subsequent releases. As you can see from this version of the NDK, these apis support very limited functionality, including :C standard library (liBC), standard mathematics library (libm), compression library (libz),Log library (liblog).
64. Which scenarios are AsyncTask used in? What are its drawbacks? How to solve it?
AsyncTask is used when we need to perform some time-consuming operations, and then update the main thread after the time-consuming operation is completed, or update the UI of the main thread during the operation.
Defects: the AsyncTask maintains a length of 128 of the thread pool, can perform 5 working threads at the same time, there is a buffer queue, when 128 threads in a thread pool, buffer queue is full, if the submitted a task to the thread will be thrown RejectedExecutionException.
Solution: a control thread handles AsyncTask calls and determines if the pool is full. If so, the thread sleeps or requests AsyncTask to continue processing.
65. How do Android threads communicate with each other? (Important)
Shared memory (variable); Files, databases; Handler. Java wait(), notify(), notifyAll()Copy the code
66. Please explain the difference between runtime permissions and file system permissions for Android applications.
Apk applications run on virtual machines, which correspond to Android’s unique permissions mechanism, and are only displayed on the file system
Use Linux permission Settings.
Permissions on Linux file systems -rwxr-x--x system system4156 2010- 04- 30 16:13Test.apk represents the permissions of the corresponding users/user groups and others to access the file, and is completely independent of the permissions the file has to run. For example, the above example only shows that the system user has the read/write permission to execute the file. Users in the system group have read and execute permissions on the file. Others have only execute permission on this file. It's irrelevant what test.apk can do when it's running. Do not assume that apK has system or root privileges just because it belongs to system/system users and user groups or root/root users and user groups on the APK file systemCopy the code
Android permission rules
Apk in Android must sign userID-based process-level security by default, data generated by APK is not visible to the outside world by explicit permission declarations in Androidmanifest.xmlCopy the code
How does an Activity generate a view? What is the mechanism?
All frameworks are based on reflection and the Manifest.
Common cases:
The Activity creates a view drawn by onDraw. Before drawing the view, it calls the onMeasure method to calculate the size of the display.Copy the code
Special circumstances:
The Surfaceview operates directly on the hardware, and since onDraw is too inefficient to handle the number of frames required for video playback, the Surfaceview writes data directly to video memory.Copy the code
68. What is AIDL? How to use it?
Aidl stands for Android Interface Definition Language.
Using AIDL allows you to publish and invoke remote services for cross-process communication.
If you put the service aiDL in the SRC directory, the project gen directory will generate the corresponding interface class. We bind the remote service with bindService (Intent, ServiceConnect, int). There is a ServiceConnec interface in bindService, and we need to overwrite the class's onServiceConnected(ComponentName,IBinder) method, The IBinder object, the second argument to this method, is actually the interface already defined in AIDL, so we can cast the IBinder object to the interface class in AIDL. The object we get through IBinder (the interface generated by aiDL files) is actually a proxy object generated by the system. The proxy object can communicate with both our process and the remote process, acting as an intermediary for inter-process communication.Copy the code
69. What is the full name of AIDL? How does it work? What types of data can it handle?
Android Interface Definition Language (AIDL) is an Interface description Language. The compiler can generate a piece of code from an AIDL file that allows two processes to communicate with each other internally through a predefined interface. Two things need to be done:
Introduce related classes of AIDL. Generated by calling aiDLclassCopy the code
In theory, arguments can pass basic data types and strings, as well as derived classes of bundles, but in Eclipse, the current ADT does not support bundles as arguments.
70.Android determines whether the SD card exists
The first step is to add SD card access to androidmanifest.xml
71. Assignment of task stack in Android
Task is actually a stack of activities, and usually an Application is a Task. According to this definition, a Task has nothing to do with a Service or other Components; it is specific to an Activity.
Activities have different launch modes that affect task allocation
72. Does SQLite support transactions? How can add and delete improve performance?
By default, each statement is a transaction when SQLite inserts data, and there are as many disk operations as there are data, such as 5000 records, which means 5000 reads and writes to the disk.
Add transaction processing to insert or delete multiple records as one transaction
73. What is the transfer mechanism of touch event in Android?
2.Touch event related classes include View, ViewGroup, and Activity 3.Touch events are encapsulated as MotionEvent objects, which encapsulate gestures such as press, move, release, etc. 4.Touch events are usually emitted from Activity#dispatchTouchEvent and, as long as they are not consumed, are passed down to the lowest level View. If each View to which the Touch event is passed does not consume the event, then the Touch event will be passed up in the reverse direction and handled by Activity#onTouchEvent. 7. If a View does not consume a Down event, subsequent MOVE/UP events will not be given to itCopy the code
74. Describe the Handler mechanism
1Looper: a thread can generate a Looper object that manages MessageQueue(MessageQueue) in that thread.2Handler: You can construct Handler objects that communicate with Looper to push new messages to MessageQueue. Or receive the Message sent by Looper from Message Queue.3Message Queue: Holds messages placed by threads.4) Thread: UIthread is usually the main thread, and the Android launcher creates a MessageQueue for it.Copy the code
The Hander holds references to the UI main thread MessageQueue MessageQueue and the message loop Looper, and the child thread can send messages to the UI thread MessageQueue MessageQueue through the Handler.
75. Basic flow of custom View
XML file in the layout file, and reference the namespace in the View constructor to get our custom properties. In the custom control to read (constructor gets the value of the attr. XML file) rewrite onMesure rewrite onDrawCopy the code
76. What else do child threads send messages to the main thread to update the UI, besides handler and AsyncTask?
Update with the Activity object’s runOnUiThread method
Update the UI in the child thread with the runOnUiThread() method: If the Activity is in a non-context class, it can be called by passing the context;Copy the code
Update the UI with the view.post (Runnable r) method
77. Can a child thread create a new handler? Why is that?
Not, if the new Handler directly in the child thread () throws an exception. Java lang. RuntimeException: Can ‘tcreate Handler inside thread that has not called
Handler cannot be created without calling looper.prepare () because the Handler source code does the following
Handler constructor
78. What are the categories of animation in Android, and what are their characteristics and differences
Frame Animation is mainly used to play frames of prepared pictures, similar to GIF images. The advantage is that it is easy to use, but the disadvantage is that each Frame needs to be prepared in advance.
Tween Animation only needs to define the start and end key frames, while the changing intermediate frames are filled by the system. The advantage is that it does not need to prepare every frame, and the disadvantage is that it only changes the object drawing without changing the View itself. Therefore, if you change the position of the button, you still need to click the original position of the button to be effective.
Property Animation is an Animation introduced after 3.0. It has the advantages of being simple to use, reducing implementation complexity, and directly changing the properties of objects. It can be applied to almost any object other than View classes, including ValueAnimator and ObjectAnimator
79. How do I modify the Activity to enter and exit the animation
By two ways, one is by defining the theme of the Activity, 2 it is through the overwrite overridePendingTransition method of the Activity.
Edit the following code in styles.xml by setting the theme style:
Add themes. XML file: specify a theme for the Activity in androidmanifest.xml.Copy the code
Overwrite the overridePendingTransition method
overridePendingTransition(R.anim.fade, R.anim.hold);Copy the code
80. What are symmetric and asymmetric encryption in the way Android interacts with servers?
Symmetric encryption means that the same key is used to encrypt and decrypt data. DES is used for this algorithm. Asymmetric encryption, encryption and decryption are using different keys. Before sending data, you must negotiate with the server to generate public and private keys. Data encrypted using the public key can be decrypted using the private key, and vice versa. The algorithm for this is RSA. Both SSH and SSL are typical of asymmetric encryption.
82. What is the difference between onTouch and onTouchEvent in event distribution, and how should it be used?
Both methods are called within the View’s dispatchTouchEvent, and onTouch takes precedence over onTouchEvent. If the event is consumed in the onTouch method by returning true, the onTouchEvent will not be executed.
Note also that onTouch can be executed only if the value of mOnTouchListener cannot be empty and the currently clicked control must be enable. So if you have a control that is non-enable, registering the onTouch event for it will never be executed. For this type of control, if we want to listen for its touch event, we must do so by overriding the onTouchEvent method in the control.
83. Property animation, such as A button moving from A to B, B can still respond to click events. What is the principle?
The tween animation only shows the position change, the actual position of the View does not change, which shows that the View moves to another place, and the click event remains in the same place to respond. The property animation control moves and the event is handled by the control itself
Which custom controls have been used
Pull2RefreshListView LazyViewPager SlidingMenu SmoothProgressBar custom combination control ToggleButton custom ToastCopy the code
84. Tell me about a bug you solved in your work
More log information is printed near anomalies. Log analysis, if not possible breakpoint debugging; No debugging results, on the Stack Overflow paste abnormal information, ask Daniel to look at the code, or from the source code to find relevant information is not GG, find the master to solve!Copy the code
What kinds of memory management do embedded operating systems have? What are the characteristics of each
Page type, section type, section page, using MMU, virtual space and other technologies
86. What frameworks and platforms have been used in development
XUtils JPush Youmi Advertising Baidu Map BMob Server platform, SMS authentication, email authentication, third-party payment Ali Cloud OSS cloud storage ShareSDK (sharing platform, third-party login) Gson (parsing JSON data framework) imageLoader (image processing framework) Zxing (TWO-DIMENSIONAL code scanning) Anroid-Asyn - HTTP (network communication) DiskLruCache(hard disk caching framework) Viatimo (Multimedia Playback framework) Universal Image-Loader (Image Caching framework) IFlytek voice (Speech recognition)Copy the code
87. Talk about your understanding of Bitmap and when you should manually call bitmap.recycle().
Bitmap is a class commonly used in Android that represents an image resource. Bitmap consumes a lot of memory. If you do not optimize the code, OOM problems often occur. There are usually several ways to optimize the code:
Use caching; Compressed pictures; Timely recycling;Copy the code
When you need to manually call recycle depends on the situation, but the principle is that when you stop using Bitmap, you need to recycle it. In addition, we need to note that before 2.3, Bitmap objects and pixel data are stored separately. Bitmap objects are stored in the Java Heap while pixel data is stored in Native Memory. In this case, it is necessary to call recycle Memory. But after 2.3, Bitmap objects and pixel data are stored in the Heap and can be reclaimed by GC.
88. Please introduce the internal implementation of AsyncTask and the applicable scenarios
The internal AsyncTask is also handled by a Handler mechanism, but Android provides an execution framework to provide a thread pool to perform the corresponding tasks. Due to the size of the thread pool, AsyncTask should only be used to perform tasks that take a short time, such as HTTP requests. Massive downloads and database changes are not suitable for AsyncTask because the thread pool will be blocked and there will be no threads to perform other tasks, resulting in AsyncTask not being able to execute at all
89. Is there a limit to the size of data passed between activities via intEnts?
Intents deliver data with a size limit of 1MB (1024KB). The Intent delivers data with a size limit of 1MB (1024KB). The Intent delivers data with a size limit of 1024KB (1024KB). The program will blink or stop running (different phones react differently), so it can be determined that the transmission capacity of the Intent is less than 1MB.
90. What design patterns do you use on development projects? How to refactor and optimize your code?
More commonly used are singleton design patterns, factory design patterns and observer design patterns,
The singleton is usually used when you want to ensure that objects are unique in memory, such as SqliteOpenHelper objects for database operations.
The factory pattern mainly provides a transition interface for creating objects, so that the specific process of creating objects can be shielded and isolated to achieve the purpose of increasing flexibility.
The observer pattern defines a one-to-many dependency between objects in which all dependent objects are notified and automatically updated when an object’s state changes
91. What are the implementation schemes for verification code login in Android applications
Obtain the picture from the server and send the verification code to the client through the SMS serviceCopy the code
92. In the positioning project, how to choose the positioning scheme, how to balance the power consumption and the accuracy of real-time position?
At first, the Application holds a global public location object, and then automatically refreshes the location at regular intervals. On each successful refresh, the new location information is assigned to the global location object, and then the global location information is used for each location request.
Benefits of this scheme: there is no need to repeatedly locate the request, each request uses the global location object, saving time. Disadvantages of this scheme: power consumption, every certain time automatically refresh the position, the power consumption is relatively large.Copy the code
Location on demand, before each request. This has the advantage of saving power and resources, but the request time becomes relatively long.
93. Andorid applies the second login to achieve automatic login
The prerequisite is that all user-related interfaces go through HTTPS and non-user-related list data go through HTTP.
steps
The first login getUserInfo contains a long-acting token, which is used to determine whether the user logs in and exchange for a short token. The long-acting token is saved in the SharedPreferences interface to request that the long-acting token be exchanged for a short token. The short token server can indicate the last request of your interface with a timeout period of one day. All interfaces use a short-effect token. If the short-effect token is invalid, run the no3If the long-term token is invalid (the user changes devices or more than one month), the user is prompted to log in.Copy the code
94. Talk about the underlying principle of LruCache
LruCache uses a LinkedHashMap to implement a simple in-memory cache, no soft references, all strong references.
If more data is added than the set maximum, the first cached data is removed to adjust memory. MaxSize is the value initialized by the constructor that represents the maximum size that the cache can cache.
Size is updated when adding and removing caches, using the safeSizeOf method. SafeSizeOf returns 1 by default, but we normally override this method based on maxSize. For example, if maxSize stands for KB, we return the memory size of the item in KB.
In addition to exceptions, it first determines whether the size exceeds maxSize. If it does, the cache inserted first is removed. If it is not empty, it is deleted and size is subtracted from the size of the item. This operation will continue until size is smaller than maxSize or the cache is empty.
How to call JNI?
Install and download Cygwin, and download Android NDK. Design of JNI interface in NDK project. Implement native methods using C/C++. JNI generates dynamic link library. So files. Copy the dynamic link library to the Java project, call it in the Java project, and run the Java project.Copy the code
96. How many bytes is the longest short message?
Chinese 70(including punctuation), English 160,160 bytes.
98. How does instant messaging work?
Instant messaging using the Asmark open source framework. The framework is based on the open source XMPP instant communication protocol, using C/S architecture, through GPRS wireless network to connect to the server with TCP protocol, to set up the open source Openfn’s server as the instant communication platform.
The client is developed based on the Android platform. Initializes the communication process. During instant communication, the client initiates a connection request to the server. The system connects with the Internet through GPRS wireless network, and realizes instant communication pin with Android client through the server.
The server side uses Openfire as the server. Allows multiple clients to log in and connect to the same server concurrently. The server authenticates the connection of each client and creates a session for the authenticated client. The communication between the client and the server is carried out in the context of the session.
99. How to optimize Android?
Optimization of listView. Optimization of images. Optimization of memory. In particular, try not to use too many static classesstaticClose cursor after database use and logout after broadcast useCopy the code
100. If a file of 100M size needs to be uploaded to the server, and the server form can only be uploaded to 2M, what method can be used?
First, using HTTP to upload data, especially on Android, has nothing to do with forms.
Traditionally, on the Web, we write files in a form, but what the browser does is parses our data into strings and streams them to the server, and we upload files in POST mode, which has no limit on size.
So back to the problem, we could say that assuming we can really only upload 2M at a time, then maybe we just truncate the files and upload them separately, breakpoint upload.