android系统面试问答

Android is the most popular operating system for mobile phone. Android apps are very popular these days. Since Android is open source, it’s very popular and anyone can create android apps. There are many companies working solely to create android apps. I have written a lot on Android tutorials, here I am listing some of the important android interview questions to help you in the interview.

Android是最流行的手机操作系统。 如今,Android应用程序非常受欢迎。 由于Android是开源的,因此非常流行,任何人都可以创建android应用。 有许多公司专门致力于创建android应用。 我在Android教程上写了很多东西,在这里我列出了一些重要的android面试问题,以帮助您进行面试。

Android面试题 (Android Interview Questions)

  1. Activity和AppCompatActivity有什么区别? (What is the difference between Activity and AppCompatActivity?)

    AppCompatActivity provides native ActionBar support that is consistent across the application. Also, it provides backward compatibility for other material design components till SDK version 7(ActionBar was natively available since SDK 11). Extending an Activity doesn’t provide any of these.

    Note: Since SDK 21 every activity by default, extends AppCompatActivity.

    AppCompatActivity提供本机ActionBar支持,在整个应用程序中保持一致。 此外,它还提供其他材料设计组件的向后兼容性,直到SDK版本7(ActionBar自SDK 11开始就可以使用)。 扩展活动不提供任何这些。

    注意:由于SDK 21默认情况下每个活动都扩展了AppCompatActivity。

  2. 活动,AppCompatActivity,FragmentActivity和ActionBarActivity。 它们有什么关系? (Activity, AppCompatActivity, FragmentActivity and ActionBarActivity. How are they related?)

    Activity is the base class. FragmentActivity extends Activity. AppCompatActivity extends FragmentActivity. ActionBarActivity extends AppCompatActivity.
    FragmentActivity is used for fragments.
    Since the build version 22.1.0 of the support library, ActionBarActivity is deprecated. It was the base class of appcompat-v7.
    At present, AppCompatActivity is the base class of the support library. It has come up with many new features like ToolBar, tinted widgets, material design color pallets etc.

    活动是基类。 FragmentActivity扩展了Activity。 AppCompatActivity扩展了FragmentActivity。 ActionBarActivity扩展了AppCompatActivity。
    FragmentActivity用于片段。
    从支持库的构建版本22.1.0开始,不推荐使用ActionBarActivity。 它是appcompat-v7的基类。
    当前,AppCompatActivity是支持库的基类。 它具有许多新功能,例如工具栏,着色小部件,材料设计颜色托盘等。

  3. 什么是Android支持库,为什么推荐? (What is Android Support Library and why is it recommended?)

    The android platform supports a wide variety of the versions and devices to choose from. With the release of every new version, new Android APIs are added and evolved. To make these new Android APIs available to users on older devices the Android Support Library was designed. Android Support Library provides developers with newer APIs that are compatible on older framework releases.

    android平台支持多种版本和设备供您选择。 随着每个新版本的发布,将添加并发展新的Android API。 为了使这些新的Android API在较旧的设备上可供用户使用,我们设计了Android支持库。 Android支持库为开发人员提供了与较旧框架版本兼容的较新API。

  4. 描述Android支持库的结构吗? (Describe the structure of Android Support Library?)

    Android Support Library is not just a single library. It’s a collection of libraries that have different naming conventions and usages. On a higher level, it’s divided into three types;

    1. Compatibility Libraries: These focus on back porting features so that older frameworks can take advantage of newer releases. The major libraries include v4 and v7-appcompat. v4 includes classes like DrawerLayout and ViewPager while appcompat-v7 provides classes for support ActionBar and ToolBar.
    2. Component Libraries: These include libraries of certain modules that don’t depend on other support library dependencies. They can be easily added or removed. Examples include v7-recyclerview and v7-cardview.
    3. Miscellaneous libraries: The Android support libraries consists of few other libraries such as v8 which provides support for RenderScript, annotations for supporting annotations like @NonNull.

    Android支持库不仅仅是一个库。 它是具有不同命名约定和用法的库的集合。 从更高的层次上讲,它分为三种类型:

    1. 兼容性库 :这些专注于向后移植功能,以便较旧的框架可以利用较新的版本。 主要库包括v4v7-appcompat 。 v4包含诸如DrawerLayout和ViewPager之类的类,而appcompat-v7提供了用于支持ActionBar和ToolBar的类。
    2. 组件库 :这些库包括某些模块的库,这些模块不依赖于其他支持库的依赖关系。 可以轻松添加或删除它们。 示例包括v7-recyclerviewv7-cardview
    3. 杂类库 :Android支持库由其他几个库组成,例如v8 ,它提供对RenderScript的支持, annotations用于支持@NonNull之类的注解。
  5. 命名活动的七个重要生命周期方法。 (Name the seven important lifecycle methods of an Activity.)

    1. onCreate()
    2. onStart()
    3. onResume()
    4. onPause()
    5. onStop()
    6. onDestroy()
    7. onRestart()
    1. onCreate()
    2. onStart()
    3. onResume()
    4. onPause()
    5. onStop()
    6. onDestroy()
    7. onRestart()
  6. 区分onCreate()onStart()onResume()onDestroy()onStop()onPause() 。 在活动的生命周期中何时调用它们? (Differentiate between onCreate(), onStart(), onResume(), onDestroy(), onStop(), onPause(). When are they called during the lifecycle of an Activity?)

    onCreate() is the first method that’s invoked when an activity is launched for the first time. onStart() is invoked after onCreate() has completed it’s task. onResume() is called after onStart() has completed.

    When an activity leaves its foreground (probably for a smaller duration such as standby/sleep) onPause() is invoked followed by onStop()(when the activity is not visible. eg. some other application is launched). onDestroy() is called when the activity or application is killed.

    Essentially the lifecycle methods are divided into three layers of duration :

    1. onCreate() and onDestroy() are present during the entire duration of the activity
    2. onStart() and onStop() are present while the activity is visible
    3. onResume() and onPause() are present while the activity is in foreground

    onCreate()是首次启动活动时调用的第一个方法。 onStart()在onCreate()完成任务后被调用。 在onStart()完成之后调用onResume()。

    当活动离开其前景时(可能在较短的持续时间内,例如待机/睡眠),将调用onPause(),然后调用onStop()(当活动不可见时,例如,启动某些其他应用程序)。 当活动或应用程序被杀死时,将调用onDestroy()。

    本质上,生命周期方法分为三层持续时间:

    1. 在整个活动过程中都存在onCreate()和onDestroy()
    2. 活动可见时存在onStart()和onStop()
    3. 活动处于前台时存在onResume()和onPause()
  7. 从应用程序中按下主页按钮将调用onPause()和onStop()。 描述仅调用onPause()的方案。 (Pressing the home button from an application invokes onPause() and onStop(). Describe a scenario where only the onPause() gets invoked.)

    Create and launch a new activity which obscures the current activity partially. This can be done by defining the layout_width and layout_height to partially cover the screen. This would keep the first activity visible but not in the foreground. Example: define the layout_width and layout_height as 200dp each.

    创建并启动一个新活动,该活动会部分遮盖当前活动。 这可以通过定义layout_width和layout_height来部分覆盖屏幕来完成。 这将使第一个活动保持可见,但在前台不可见。 示例:将layout_width和layout_height分别定义为200dp。

  8. 用户旋转屏幕时活动如何响应? (How does the activity respond when the user rotates the screen?)

    When the screen is rotated, the current instance of the activity is destroyed a new instance of the Activity is created in the new orientation. The onRestart() method is invoked first when a screen is rotated. The other lifecycle methods get invoked in the similar flow as they were when the activity was first created.

    旋转屏幕时,活动的当前实例被破坏,以新的方向创建活动的新实例。 旋转屏幕时,将首先调用onRestart()方法。 其他生命周期方法的调用与创建活动时的流程类似。

  9. Given below is a sample layout of the activity_main.xml
    <?xml version="1.0" encoding="utf-8"?>	 	 
    <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"	 	 
     android:layout_width="match_parent"	 	 
     android:layout_height="match_parent"	 	 
     android:paddingBottom="@dimen/activity_vertical_margin"	 	 
     android:paddingLeft="@dimen/activity_horizontal_margin"	 	 
     android:paddingRight="@dimen/activity_horizontal_margin"	 	 
     android:paddingTop="@dimen/activity_vertical_margin"	 	 
     >
     	 
     <TextView	 	 
     android:layout_width="wrap_content"	 	 
     android:layout_height="wrap_content"	 	 
     android:text="0"	 	 
     android:id="@+id/textView"	 	 
     android:layout_alignParentRight="true"	 	 
     android:layout_alignParentEnd="true"	 	 
     android:layout_alignParentLeft="true"	 	 
     android:layout_alignParentStart="true" />
     	 	 
     <Button 
     android:layout_width="wrap_content"	 	 
     android:layout_height="wrap_content"	 	 
     android:text="Increment"	 	 
     android:id="@+id/button"	 	 
     android:layout_centerVertical="true"	 	 
     android:layout_centerHorizontal="true" />	 	 
    </RelativeLayout>

    Given below is a sample MainActivity.java class;

    上面的应用程序旨在每次单击按钮时将textview值增加1,但是它将崩溃。 为什么? (The above application is designed to increment the textview value by 1 every time the button is clicked but it will crash. Why?)

    The application will crash with a android.content.res.Resources$NotFoundException: String resource ID #0x1 exception since the textview expects a string value. The above code is passing the integer directly. We need to convert it into a string. This can be done in either of two ways:

    1. textView.setText(""+i);
    2. textView.setText(String.valueOf(i));

    下面给出的是activity_main.xml的示例布局
    <?xml version="1.0" encoding="utf-8"?>	 	 
    <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"	 	 
     android:layout_width="match_parent"	 	 
     android:layout_height="match_parent"	 	 
     android:paddingBottom="@dimen/activity_vertical_margin"	 	 
     android:paddingLeft="@dimen/activity_horizontal_margin"	 	 
     android:paddingRight="@dimen/activity_horizontal_margin"	 	 
     android:paddingTop="@dimen/activity_vertical_margin"	 	 
     >
     	 
     <TextView	 	 
     android:layout_width="wrap_content"	 	 
     android:layout_height="wrap_content"	 	 
     android:text="0"	 	 
     android:id="@+id/textView"	 	 
     android:layout_alignParentRight="true"	 	 
     android:layout_alignParentEnd="true"	 	 
     android:layout_alignParentLeft="true"	 	 
     android:layout_alignParentStart="true" />
     	 	 
     <Button 
     android:layout_width="wrap_content"	 	 
     android:layout_height="wrap_content"	 	 
     android:text="Increment"	 	 
     android:id="@+id/button"	 	 
     android:layout_centerVertical="true"	 	 
     android:layout_centerHorizontal="true" />	 	 
    </RelativeLayout>

    下面给出了一个示例MainActivity.java类;

    应用程序将崩溃,并出现android.content.res.Resources$NotFoundException: String resource ID #0x1异常,因为textview需要一个字符串值。 上面的代码直接传递整数。 我们需要将其转换为字符串。 可以通过以下两种方式之一来完成此操作:

    1. textView.setText(""+i);
    2. textView.setText(String.valueOf(i));
  10. 这是上述情况的后续问题。 更改屏幕方向时,上述应用程序如何响应? (This is a follow up question to the case above. How does the above application respond when the screen orientation is changed?)

    On-screen rotation the activity restarts and the objects are initialized again. Hence the textView counter resets to zero every time the orientation is changed.

    在屏幕上旋转活动将重新启动,并且对象将再次初始化。 因此,每次更改方向时,textView计数器都会重置为零。

  11. 旋转屏幕时如何防止数据重新加载和重置? (How to prevent the data from reloading and resetting when the screen is rotated?)

    The most basic approach is to add an element attribute tag android:configChanges inside the activity tag in the AndroidManifest.xml as shown below.

    <activity android:name=".MainActivity"
    	 android:configChanges="orientation|screenSize">
    	
    	<intent-filter>
    	  	 <action android:name="android.intent.action.MAIN" />
    	  	 <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        
    </activity>

    In general, the configChanges for any activity are defined as

    The keyboardHidden configuration is to prevent the keyboard from resetting if it’s pulled out.

    最基本的方法是在AndroidManifest.xml的活动标记内添加一个元素属性标记android:configChanges ,如下所示。

    <activity android:name=".MainActivity"
    	 android:configChanges="orientation|screenSize">
    	
    	<intent-filter>
    	  	 <action android:name="android.intent.action.MAIN" />
    	  	 <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
        
    </activity>

    通常,将任何活动的configChanges定义为

    keyboardHidden配置用于防止拔出键盘时重置键盘。

  12. An example layout of activity_main.xml is given below. The MainActivity.java only contains the blank onCreate() method.
    <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    	android:layout_width="match_parent"
    	android:layout_height="match_parent"
    	android:paddingBottom="@dimen/activity_vertical_margin"
     	android:paddingLeft="@dimen/activity_horizontal_margin"
     	android:paddingRight="@dimen/activity_horizontal_margin"
     	android:paddingTop="@dimen/activity_vertical_margin"
    >
     
      <EditText
     	android:layout_width="wrap_content"
     	android:layout_height="wrap_content"
     	android:text="Hello World!"
     	android:layout_alignParentRight="true"
     	android:layout_alignParentEnd="true"
     	android:layout_alignParentLeft="true"
     	android:layout_alignParentStart="true" />
    
    </RelativeLayout>

    The configChanges are defined in the AndroidManifest.xml as android:configChanges="orientation|screenSize|keyboardHidden"

    更改方向后,在EditText中输入的输入文本是否会保留? 是/否? 说明。 (Does the input text entered in the EditText persist when the orientation is changed? Yes/No? Explain.)

    No. Despite the configChanges defined in the AndroidManifest.xml, the EditText input text entered resets when the orientation is changed. This is because no resource id has been defined. On orientation change, the instance of the EditText gets lost. To fix this issue to work correctly add an android:id attribute element in the EditText tag.

    configChanges在AndroidManifest.xml中定义为android:configChanges="orientation|screenSize|keyboardHidden"

    不会。尽管在AndroidManifest.xml中定义了configChanges,但更改方向时会重置输入的EditText输入文本。 这是因为尚未定义资源ID。 更改方向时,EditText的实例丢失。 要解决此问题以使其正常工作,请在EditText标签中添加android:id属性元素。

  13. 为什么不建议使用android:configChanges? 还有更多更好的方法来处理方向变化吗? (Why is android:configChanges not recommended? Are there more better ways to handle orientation changes?)

    android:configChanges is not the recommended way by Google. Though it’s the simplest way to use, it comes with its own share of drawbacks. First, the common perception that android:configChanges = “orientation” will magically retain the data is a complete misinterpretation. The orientation changes can occur from a number of other events such as changing the default language can trigger a configuration change and destroy and recreate the activity.

    Second, the activity can restart itself if it’s in the background and Android decides to free up its heap memory by killing it. When the application returns to the foreground it’ll restart it’s data to the original state and the user may not like that.

    A better alternative of android:configChanges is;

    Saving the current state of the activity when it’s being destroyed and restoring the valuable data when it’s restarted can be done by overriding the methods onSaveInstanceState() and onRestoreInstanceState() of the activity class.

    android:configChanges不是Google推荐的方法。 尽管这是最简单的使用方法,但它也有其自身的缺点。 首先,人们普遍认为android:configChanges =“ orientation”将神奇地保留数据是完全错误的解释。 方向更改可能来自许多其他事件,例如更改默认语言可以触发配置更改以及破坏并重新创建活动。

    其次,如果活动处于后台,并且Android决定通过杀死活动来释放其堆内存,则该活动可以自行重启。 当应用程序返回到前台时,它将重新启动其数据,使其恢复为原始状态,用户可能会不喜欢这种状态。

    android:configChanges更好替代方法是;

    可以通过重写活动类的onSaveInstanceState()onRestoreInstanceState()方法来保存活动被破坏时的当前状态,并在重新启动时恢复有价值的数据。

  14. 活动生命周期中的onSaveInstanceState()和onRestoreInstanceState()在哪里? 如何通过这些方法保存和还原数据? (Where do onSaveInstanceState() and onRestoreInstanceState() come in the activity lifecycle? How is the data saved and restored from these methods?)

    In general the onSaveInstanceState() is invoked after onPause() and before the onStop(). But the API documentation explicitly states that the onSaveInstanceState( ) method will be called before onStop() but makes no guarantees it will be called before or after onPause(). The onRestoreInstanceState() is called after onStart() is invoked. The onRestoreInstanceState() method is invoked only when the activity was killed before. If the activity is NOT killed the onSaveInstanceState() is NOT called.

    When the activity is being destroyed, the onSaveInstanceState() gets invoked. The onSaveInstanceState contains a Bundle parameter. The data to be saved is stored in the bundle object in the form of a HashMap.

    The bundle object is like a custom HashMap object. The data is retrieved in the onRestoreInstanceState() method using the keys.

    通常,在onPause()之后和onStop()之前调用onSaveInstanceState()。 但是API文档明确声明onSaveInstanceState()方法将在onStop()之前调用,但不能保证它将在onPause()之前或之后调用。 在调用onStart()之后调用onRestoreInstanceState()。 仅在活动被杀死之前,才调用onRestoreInstanceState()方法。 如果未终止活动,则不调用onSaveInstanceState()。

    销毁活动时,将调用onSaveInstanceState()。 onSaveInstanceState包含一个Bundle参数。 要保存的数据以HashMap的形式存储在bundle对象中。

    bundle对象就像一个自定义的HashMap对象。 使用键在onRestoreInstanceState()方法中检索数据。

  15. 您已获得包含EditText字段的布局。 实现onSaveInstanceState()和onRestoreInstanceState()在屏幕旋转时保存和还原当前输入文本,而无需在清单文件中声明android:configChanges属性。 MainActivity.java在下面给出。 (You’ve been given a layout that contains an EditText field. Implement the onSaveInstanceState() and onRestoreInstanceState() to save and restore the current input text when the screen is rotated without declaring the android:configChanges attribute in the manifest file. The MainActivity.java is given below.)
    public class MainActivity extends AppCompatActivity {
        EditText editText;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            editText = (EditText) findViewById(R.id.editText);
        }
    }

    public class MainActivity extends AppCompatActivity {
        EditText editText;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            editText = (EditText) findViewById(R.id.editText);
        }
    }
  16. 如何保持屏幕方向固定? 还应实现一种机制,以使特定活动的屏幕始终处于打开状态。 (How to keep the screen orientation fixed? Also implement a mechanism so that the screen is always on for a particular activity.)

    The screen orientation can be fixed by adding the attribute android:screenOrientation="portrait" or android:screenOrientation="landscape" in the activity tag.

    To keep the screen always on for a particular screen add the android:keepScreenOn="true" in the root tag of the activity layout.

    可以通过在活动代码中添加属性android:screenOrientation="portrait"android:screenOrientation="landscape"来固定屏幕方向。

    要使屏幕始终保持打开状态,请在活动布局的根标记中添加android:keepScreenOn="true"

  17. 如何以编程方式重新启动活动? 实现方法restartActivity(),该方法在单击按钮时重新启动活动。 (How to restart an activity programmatically? Implement the method restartActivity() that restarts an Activity on a button click. )

    Given below is the MainActivity.java class

    public class MainActivity extends AppCompatActivity {
        Button btn;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            
            btn = (Button) findViewById(R.id.btn);
    
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    restartActivity();
    
                }
            });
        }
    
        public void restartActivity() {
            //Complete the code
        }
    
    }

    We need to invoke the recreate method on the Activity instance as shown below.

    下面给出的是MainActivity.java类

    public class MainActivity extends AppCompatActivity {
        Button btn;
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
            
            btn = (Button) findViewById(R.id.btn);
    
            btn.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
    
                    restartActivity();
    
                }
            });
        }
    
        public void restartActivity() {
            //Complete the code
        }
    
    }

    我们需要在Activity实例上调用recreate方法,如下所示。

  18. 描述意图的三种常见用法以及如何调用它们。 (Describe three common usages of intent and how are they invoked.)

    Android Intents are used to

    1. start an activity – startActivity(intent)
    2. start a service – startService(intent)
    3. deliver a broadcast – sendBroadcast(intent)

    Android Intent用于

    1. 开始活动– startActivity(intent)
    2. 启动服务– startService(intent)
    3. 提供广播– sendBroadcast(意图)
  19. 使用意图实现两个动作,即呼叫电话号码和打开URL。 (Implement two actions using intents namely calling a phone number and opening a URL.)

    To enable calling from the application we need to add the following permission in the manifest tag of AndroidManifest.xml

    <uses-permission android:name="android.permission.CALL_PHONE" />

    In the MainActivity the following code invokes an action call to the given number represented as a string.
    The string is parsed as a URI.

    To open a URL we need to add the following permission.

    <uses-permission android:name="android.permission.INTERNET" />

    The intent to view a URL is defined below.

    要启用从应用程序调用,我们需要在AndroidManifest.xml的清单标签中添加以下权限

    <uses-permission android:name="android.permission.CALL_PHONE" />

    在MainActivity中,以下代码调用对表示为字符串的给定数字的操作调用。
    该字符串被解析为URI。

    要打开URL,我们需要添加以下权限。

    <uses-permission android:name="android.permission.INTERNET" />

    查看URL的意图在下面定义。

  20. Intent对象上的setFlags()和addFlags()有什么区别? (What’s the difference between setFlags() and addFlags() on an Intent object?)

    When we’re using setFlags, we’re replacing the old flags with a new set of Flags. When we use addFlags, we’re appending more flags.

    当使用setFlags时,我们用一组新的Flags替换了旧的flags。 当使用addFlags时,我们将附加更多标志。

  21. 当使用意图调用新的活动时,请提及两种清除活动的后栈的方法。 (Mention two ways to clear the back stack of Activities when a new Activity is called using intent.)

    The first approach is to use a FLAG_ACTIVITY_CLEAR_TOP flag.

    Intent intent= new Intent(ActivityA.this, ActivityB.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    finish();

    The second way is by using FLAG_ACTIVITY_CLEAR_TASK and FLAG_ACTIVITY_NEW_TASK in conjunction.

    第一种方法是使用FLAG_ACTIVITY_CLEAR_TOP标志。

    Intent intent= new Intent(ActivityA.this, ActivityB.class);
    intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(intent);
    finish();

    第二种方法是结合使用FLAG_ACTIVITY_CLEAR_TASKFLAG_ACTIVITY_NEW_TASK

  22. FLAG_ACTIVITY_CLEAR_TASK和FLAG_ACTIVITY_CLEAR_TOP有什么区别? (What’s the difference between FLAG_ACTIVITY_CLEAR_TASK and FLAG_ACTIVITY_CLEAR_TOP?)

    FLAG_ACTIVITY_CLEAR_TASK is used to clear all the activities from the task including any existing instances of the class invoked. The Activity launched by intent becomes the new root of the otherwise empty task list. This flag has to be used in conjunction with FLAG_ ACTIVITY_NEW_TASK.

    FLAG_ACTIVITY_CLEAR_TOP on the other hand, if set and if an old instance of this Activity exists in the task list then barring that all the other activities are removed and that old activity becomes the root of the task list. Else if there’s no instance of that activity then a new instance of it is made the root of the task list. Using FLAG_ACTIVITY_NEW_TASK in conjunction is a good practice, though not necessary.

    FLAG_ACTIVITY_CLEAR_TASK用于清除任务中的所有活动,包括已调用类的任何现有实例。 通过意图启动的活动将成为否则为空的任务列表的新根。 该标志必须与FLAG_ ACTIVITY_NEW_TASK结合使用。

    另一方面,如果设置了FLAG_ACTIVITY_CLEAR_TOP ,并且如果任务列表中存在该活动的旧实例,则禁止所有其他活动都被删除,并且该旧活动成为任务列表的根。 否则,如果没有该活动的实例,则将该活动的新实例作为任务列表的根。 结合使用FLAG_ACTIVITY_NEW_TASK是一个好习惯,尽管不是必须的。

  23. 举一个需要FLAG_ACTIVITY_NEW_TASK的用法示例。 另外,描述活动如何响应此标志。 (Give one usage example where FLAG_ACTIVITY_NEW_TASK is necessary. Also, describe how the activity responds to this flag.)

    When we’re trying to launch an activity from outside the activity’s context, a FLAG_ACTIVITY_NEW_TASK is compulsory else a runtime exception would be thrown.

    Example scenarios are: launching from a service, invoking an activity from a notification click.

    If the activity instance is already on the task list when the flag is set, it will invoke the onNewIntent() method of that Activity. All the implementation stuff goes in that method.

    当我们尝试从活动上下文之外启动活动时,必须使用FLAG_ACTIVITY_NEW_TASK,否则会抛出运行时异常。

    示例场景包括:从服务启动,从通知单击中调用活动。

    如果在设置标志时活动实例已经在任务列表中,它将调用该活动的onNewIntent()方法。 所有实现的东西都放在该方法中。

  24. 定义活动的launchMode的类型并描述它们中的每一个。 (Define the types of launchMode of an Activity and describe each of them.)

    The android:launchMode of an Activity can be of the following types:

    • standard : It’s the default launch mode for an activity wherein every new instance of the activity called will be put on top of the stack as a separate entity. Hence calling startActivity() for a particular class 10 times will create 10 activities in the task list.
    • singleTop: It differs from the standard launch mode in the fact that when the Activity instance that’s invoked is already present on the top of the stack, instead of creating a new Activity, that instance will be called. In cases where the same Activity instance is not on the top of the stack or if it doesn’t exist in the stack at all then a new instance of the activity will be added to the stack. Hence we need to handle the upcoming intent in both the onCreate() and onNewIntent() methods to cover all cases.
    • singleTask: This is different from singleTop in the case that if the Activity instance is present in the stack, the onNewIntent() would be invoked and that instance would be moved to the top of the stack. All the activities placed above the singleTask instance would be destroyed in this case. When the activity instance does not exist in the stack, the new instance would be placed on the top of the stack similar to the standard mode.
    • singleInstance : An activity with this launchMode defined would place only a singleton activity instance in the Task. The other activities of the application will be placed in a separate Task.

    Activity的android:launchMode可以为以下类型:

    • standard :这是一项活动的默认启动模式,其中,该活动的每个新实例都将作为单独的实体放在堆栈的顶部。 因此,为特定的类调用10次startActivity()将在任务列表中创建10个活动。
    • singleTop :与标准启动模式的不同之处在于,当调用的Activity实例已经存在于堆栈的顶部时,而不是创建新的Activity时,将调用该实例。 如果同一个Activity实例不在堆栈顶部,或者如果它根本不存在于堆栈中,则将新的Activity实例添加到堆栈中。 因此,我们需要在onCreate()onNewIntent()方法中处理即将到来的意图,以涵盖所有情况。
    • singleTask :如果在堆栈中存在Activity实例,则将调用onNewIntent()并将该实例移到堆栈顶部,这与singleTop不同。 在这种情况下,位于singleTask实例上方的所有活动都将被销毁。 如果活动实例在堆栈中不存在,则类似于标准模式,新实例将放置在堆栈的顶部。
    • singleInstance :定义了launchMode的活动将仅在Task中放置一个单例活动实例。 应用程序的其他活动将放置在单独的任务中。
  25. 什么是taskAffinity? (What is taskAffinity?)

    A taskAffinity is an attribute tag defined in the activity tag in the AndroidManifest.xml for launchMode singleInstance. Activities with similar taskAffinity values are grouped together in one task.

    26) You’ve been given an EditText that already has some text in it. How would you place the cursor at the end of the text? The current situation and the output needed are given below.

    Call the setSelection(position) on the EditText object with the position we need to place the cursor on. The current position is 0. To place it at the end of the current text we’ll add the following code snippet in our MainActivity.

    EditText in;
    
    in=(EditText)findViewById(R.id.editText);
            if (in != null) {
                in.setSelection(Integer.parseInt(String.valueOf(in.getText().toString().length())));
            }

    The setSelection method requires an integer parameter. So we’re wrapping the length of the string as an Integer using parseInt.

    taskAffinity是在AndroidManifest.xml的activity标签中为launchMode singleInstance定义的属性标签。 具有相似taskAffinity值的活动被分组到一个任务中。

    26)您将获得一个EditText,其中已经包含一些文本。 您如何将光标放在文本的末尾? 下面给出了当前情况和所需的输出。

    调用EditText对象上的setSelection(position) ,将其放置在需要将光标置于其上的位置。 当前位置是0。要将其放置在当前文本的末尾,我们将在MainActivity中添加以下代码段。

    setSelection方法需要一个整数参数。 因此,我们使用parseInt将字符串的长度包装为Integer。

  26. 实现一个EditText,当按下Enter键时该文本将自行清除。 下图显示了要求。 (Implement an EditText that clears itself when the enter key is pressed. The image below demonstrates the requirement.)

    We’ll add the TextWatcher class to the editText object. And check for the “\n” character and clear the editText as shown below.

    我们将TextWatcher类添加到editText对象。 然后检查“ \ n”字符并清除editText,如下所示。

  27. 区分LinearLayout,RelativeLayout,AbsoluteLayout。 (Differentiate between LinearLayout, RelativeLayout, AbsoluteLayout.)

    A LinearLayout arranges its children in a single row or single column one after the other. A RelativeLayout arranges it’s children in positions relative to each other or relative to parent depending upon the LayoutParams defined for each view.
    AbsoluteLayout needs the exact positions of the x and y coordinates of the view to position it. Though this is deprecated now.

    LinearLayout将其子项一个接一个地排列在单行或单列中。 RelativeLayout会根据为每个视图定义的LayoutParams将其子级安排在相对于彼此或相对于父级的位置。
    AbsoluteLayout需要视图的x和y坐标的精确位置才能对其进行定位。 尽管现在不建议使用。

  28. FrameLayout和TableLayout有什么区别。 (What’s the difference between a FrameLayout and a TableLayout.)

    A FrameLayout stack up child views above each other with the last view added on the top. Though we can control the position of the children inside the FrameLayout using the layout_gravity attribute.

    When the width and height of the FrameLayout are set to wrap_content, the size of the FrameLayout equals the size of the largest child (plus padding).

    A TableLayout consists of TableRows. The children are arranged in the form of rows and columns.

    FrameLayout将子视图彼此堆叠,最后一个视图添加在顶部。 尽管我们可以使用layout_gravity属性控制子帧在FrameLayout中的位置。

    将FrameLayout的宽度和高度设置为wrap_content时,FrameLayout的大小等于最大子项的大小(加上填充)。

    TableLayout由TableRows组成。 子级以行和列的形式排列。

  29. 数据如何存储在“共享首选项”中? commit()和apply()有什么区别? 推荐哪一个? (How is data stored in Shared Preferences? What’s the difference between commit() and apply()? Which is the recommended one?)

    Data is stored in SharedPreferences in the form of a key-value pair(HashMap).

    commit() was introduced in API 1 whereas apply() came up with API 9.

    commit() writes the data synchronously and returns a boolean value of success or failure depending on the result immediately.
    apply() is asynchronous and it won’t return any boolean response. Also, if there is an apply() outstanding and we perform another commit(), then the commit() will be blocked until the apply() is not completed.

    commit() is instantaneous and performs disk writes. If we’re on the main UI thread apply() should be used since it’s asynchronous.

    数据以键值对(HashMap)的形式存储在SharedPreferences中。

    在API 1中引入了commit(),而在API 9中引入了apply()。

    commit()同步写入数据,并根据结果立即返回成功或失败的布尔值。
    apply()是异步的,不会返回任何布尔响应。 另外,如果有一个apply()未完成,并且我们执行了另一个commit(),则commit()将被阻止,直到apply()未完成。

    commit()是瞬时的,并执行磁盘写入。 如果在主UI线程上,则应使用apply(),因为它是异步的。

  30. 当用户按下屏幕上的“后退”按钮时,调用哪种方法? (Which method gets invoked when the user presses back button on the screen?)

    The onBackPressed() method of the Activity is invoked. Unless overridden it removes the current activity from the stack and goes to the previous activity.

    Activity的onBackPressed()方法被调用。 除非被覆盖,否则它将从堆栈中删除当前活动并转到上一个活动。

  31. 如何禁用onBackPressed()? (How do you disable onBackPressed()?)

    The onBackPressed() method is defined as shown below:

    @Override
        public void onBackPressed() {
            super.onBackPressed();
        }

    To disable the back button and preventing it from destroying the current activity and going back we have to remove the line super.onBackPressed();

    onBackPressed()方法的定义如下所示:

    要禁用后退按钮并防止其破坏当前活动并返回,我们必须删除super.onBackPressed();super.onBackPressed();

  32. 什么是StateListDrawable? (What is a StateListDrawable?)

    A StateListDrawable is a drawable object defined in the XML that allows us to show a different color/background for a view for different states. Essentially it’s used for Buttons to show a different look for each state(pressed, focused, selected, none).

    StateListDrawable是XML中定义的可绘制对象,它允许我们为不同状态的视图显示不同的颜色/背景。 从本质上讲,它用于按钮为每种状态(按下,聚焦,选中,无)显示不同的外观。

  33. 实现一个按钮,该按钮使用StateListDrawable来处理按下状态和未按下状态,并带有弯曲的边缘和按钮周围的边框。 (Implement a button that using a StateListDrawable for pressed and not pressed states with curved edges and a border around the button.)

    The selector drawable for a button is shown below.

    <selector xmlns:android="https://schemas.android.com/apk/res/android">
    
    <item android:state_pressed="false">
     	<shape android:shape="rectangle">
     		<solid android:color="@android:color/holo_red_dark"/>
     		<stroke android:color="#000000" android:width="3dp"/>
     		<corners android:radius="2dp"/>
    	</shape>
    </item>
    
    <item android:state_pressed="true">
    	<shape android:shape="rectangle">
     	 	 <solid android:color="@android:color/darker_gray"/>
     	 	 <stroke android:color="#FFFF" android:width="1dp"/>
     	 	 <corners android:radius="2dp"/>
     	</shape>
    </item>
    
    </selector>

    We need to add this drawable XML in the android:background attribute of the button as:

    The output looks like this:

    android button state list, android interview questions

    按钮可绘制的选择器如下所示。

    我们需要在按钮的android:background属性中添加以下可绘制XML:

    android:background="@drawable/btn_background"

    输出看起来像这样:

  34. 什么是碎片? 描述那里的生命周期方法。 (What are Fragments? Describe there lifecycle methods.)

    Fragments are a part of an activity and they contribute there own UI to the activity they are embedded in. A single activity can contain multiple fragments. Fragments are reusable across activities.

    The lifecycle methods of a Fragment are :

    1. onAttach(Activity) : is called only once when it is attached with activity.
    2. onCreate(Bundle) : it is used to initialise the fragment.
    3. onCreateView(LayoutInflater, ViewGroup, Bundle) : creates and returns view hierarchy.
    4. onActivityCreated(Bundle) : it is invoked after the completion of onCreate() method.
    5. onViewStateRestored(Bundle) : it provides information to the fragment that all the saved state of fragment view hierarchy has been restored.
    6. onStart() : makes the fragment visible.
    7. onResume() : makes the fragment interactive.
    8. onPause() : is called when fragment is no longer interactive.
    9. onStop() : is called when fragment is no longer visible
    10. onDestroyView() : it allows the fragment to clean up resources
    11. onDestroy() : it allows the fragment to do final clean up of fragment state
    12. onDetach() : it is called when the fragment is no longer associated with the activity

    An image depicting the Fragments lifecycle is given below.

    android fragment lifecycle

    片段是活动的一部分,它们为嵌入的活动贡献自己的UI。单个活动可以包含多个片段。 片段可跨活动重用。

    片段的生命周期方法是:

    1. onAttach(Activity) :与活动连接时仅被调用一次。
    2. onCreate(Bundle) :用于初始化片段。
    3. onCreateView(LayoutInflater, ViewGroup, Bundle) :创建并返回视图层次结构。
    4. onActivityCreated(Bundle) :在onCreate()方法完成后调用。
    5. onViewStateRestored(Bundle) :它向片段提供有关片段视图层次结构的所有保存状态已还原的信息。
    6. onStart() :使片段可见。
    7. onResume() :使片段具有交互性。
    8. onPause() :当片段不再交互时调用。
    9. onStop() :当片段不再可见时调用
    10. onDestroyView() :它允许片段清理资源
    11. onDestroy() :它允许片段对片段状态进行最终清理
    12. onDetach() :当片段不再与活动关联时调用

    下面给出了描述片段生命周期的图像。

  35. 如何通过单击按钮以编程方式杀死另一个活动中正在运行的活动? (How to kill a running Activity from another Activity programmatically on Button click?)

    We’ll declare and assign a class instance of the FirstActivity to itself as shown below.

    public class FirstActivity extends AppCompatActivity {
    public static FirstActivity firstActivity;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            firstActivity=this;
    }
    }

    We’ll call finish() on the above instance of the FirstActivity to kill the activity from any other activity.

    我们将声明FirstActivity的类实例并将其分配给它自己,如下所示。

    public class FirstActivity extends AppCompatActivity {
    public static FirstActivity firstActivity;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            firstActivity=this;
    }
    }

    我们将在上述FirstActivity实例上调用finish(),以将活动从其他任何活动中删除。

  36. 什么是待定意图? (What is a PendingIntent?)

    A PendingIntent is a wrapper for the Intent object. It’s passed to a foreign application (NotificationManager, AlarmManager) such that when some given conditions are met, the desired action is performed on the intent object it holds onto. The foreign application performs the intent with the set of permissions defined in our application.

    PendingIntent是Intent对象的包装器。 它被传递给外部应用程序(NotificationManager,AlarmManager),以便在满足某些给定条件时,对其持有的意图对象执行所需的操作。 外部应用程序使用我们的应用程序中定义的一组权限执行此意图。

  37. AsyncTask和Thread类有什么区别? (What is the difference between AsyncTask and Thread class?)

    A Thread is generally used for long tasks to be run in the background. We need a Handler class to use a Thread.
    An AsyncTask is an intelligent Thread subclass. It’s recommended to use AsyncTask when the caller class is the UI Thread as there is no need to manipulate the handlers. AsyncTask is generally used for small tasks that can communicate back with the main UI thread using the two methods onPreExecute() and onPostExecute() it has.

    A Handler class is preferred when we need to perform a background task repeatedly after every x seconds/minutes.

    线程通常用于在后台运行的长任务。 我们需要一个Handler类来使用Thread。
    AsyncTask是智能的Thread子类。 建议在调用者类为UI线程时使用AsyncTask,因为无需操纵处理程序。 AsyncTask通常用于小型任务,这些任务可以使用其具有的两种方法onPreExecute()和onPostExecute()与主UI线程通讯。

    当我们需要每隔x秒/分钟重复执行一次后台任务时,首选Handler类。

  38. Given below is an AsyncTask example.

    下面给出的是一个AsyncTask示例。

    private class MyTask extends AsyncTask {
          protected String doInBackground(String... params) {
    
            Toast.makeText(getApplicationContext(),"Will this work?",Toast.LENGTH_LONG).show();
    
              int count = 100;
              int total = 0;
              for (int i = 0; i < count/2; i++) {
                  total += i;
              }
              return String.valueOf(totalSize);
          }
    
          protected void onPostExecute(String result) {
           
          }
     }
  39. 上面的AsyncTask是如何从主线程启动的? 它会成功运行吗? (How is the above AsyncTask started from the main thread? Will it run successfully?)

    We need to call the AsyncTask from the onCreate() using the following piece of code;

    MyTask myTask= new MyTask();
    myTask.execute();

    No. The application will crash with a runtime exception since we’re updating the UI Thread by trying to display a Toast message inside the doInBackground method. We need to get rid of that line to run the application successfully.

    我们需要使用以下代码从onCreate()调用AsyncTask;

    否。由于我们正在通过尝试在doInBackground方法内部显示Toast消息来更新UI线程,因此应用程序将因运行时异常而崩溃。 我们需要摆脱那条线才能成功运行该应用程序。

  40. doInBackground方法的返回值到哪里? 如何在onCreate()方法中获得该返回值? (Where does the returned value of the doInBackground method go to? How do you get that returned value in the onCreate() method?)

    The returned value of the doInBackground goes to the onPostExecute() method. We can update the main UI thread from here. To get the returned value in the onCreate() method we need to use the following code snippet.

    MyTask myTask= new MyTask();
    String result=myTask.execute().get();

    This approach is not recommended as it blocks the main UI thread until the value is not returned.

    The ideal scenario to use it is when the other views of the UI thread need the value from the AsyncTask for processing.

    doInBackground的返回值将转到onPostExecute()方法。 我们可以从这里更新主UI线程。 为了在onCreate()方法中获取返回值,我们需要使用以下代码片段。

    不建议使用此方法,因为它会阻塞主UI线程,直到不返回值为止。

    理想的方案是在UI线程的其他视图需要AsyncTask中的值进行处理时使用。

  41. 实现一个AsyncTask在给定间隔后重复执行 (Implement an AsyncTask that repeats itself after a given interval)

    We need to use a Handler class in the onPostExecute that executes the AsyncTask recursively.

    private class MyTask extends AsyncTask {
          protected String doInBackground(String... params) {
    
            Toast.makeText(getApplicationContext(),"Will this work?",Toast.LENGTH_LONG).show();
    
              int count = 100;
              int total = 0;
              for (int i = 0; i < count/2; i++) {
                  total += i;
              }
              return String.valueOf(totalSize);
          }
    
          protected void onPostExecute(String result) {
    
    // repeats after every 5 seconds here.
    new Handler().postDelayed(new Runnable() {
            @Override
            public void run() {
                new MyAsyncTask().execute("my String");
            }
        }, 5*1000);       
    
          }
     }

    我们需要在onPostExecute中使用Handler类,该类以递归方式执行AsyncTask。

  42. 什么是服务? (What is a service?)

    A service is a component in android that’s used for performing tasks in the background such as playing Music, location updating etc. Unlike activities, a service does not have a UI. Also, a service can keep running in the background even if the activity is destroyed.

    服务是android中的一个组件,用于在后台执行任务(例如播放音乐,更新位置等)。与活动不同,服务没有UI。 此外,即使活动被破坏,服务也可以在后台继续运行。

  43. 如何启动/停止服务? (How to start/stop a service?)

    A service is started from an activity by executing the following code snippet.

    startService(new Intent(this, MyService.class));

    Though just executing the above code won’t start a service. We need to register the service first in the AndroidManifest.xml file as shown below.

    To stop a service we execute stopService(). To stop the service from itself we call stopSelf().

    通过执行以下代码段,从活动启动服务。

    startService(new Intent(this, MyService.class));

    尽管仅执行上面的代码不会启动服务。 我们需要首先在AndroidManifest.xml文件中注册服务,如下所示。

    要停止服务,我们执行stopService() 。 为了停止服务本身,我们调用stopSelf()

  44. 定义和区分两种服务。 (Define and differentiate between the two types of services.)

    Services are largely divided into two categories : Bound Services and Unbound/Started Services

    1. Bound Services: An Android component may bind itself to a Service using bindservice(). A bound service would run as long as the other application components are bound to it. As soon as the components call unbindService(), the service destroys itself.
    2. Unbound Services: A service is started when a component (like activity) calls startService() method and it runs in the background indefinitely even if the original component is destroyed.

    服务大致分为两类: 绑定服务未绑定/启动的服务

    1. 绑定服务 :Android组件可以使用bindservice()将自身绑定到服务。 只要将其他应用程序组件绑定到绑定服务,该服务就会运行。 组件一旦调用unbindService() ,服务unbindService()自行销毁。
    2. Unbound Services :服务在组件(例如活动)调用startService()方法时启动,并且即使原始组件被销毁,它也可以无限期在后台运行。
  45. 描述服务的生命周期方法。 (Describe the lifecycle methods of a service.)

    • onStartCommand() : This method is called when startService() is invoked. Once this method executes, the service is started and can run in the background indefinitely. This method is not needed if the service is defined as a bounded service. The service will run indefinitely in the background when this method is defined. We’ll have a stop the service ourselves
    • onBind() This method needs to be overridden when the service is defined as a bounded service. This method gets called when bindService() is invoked. In this method, we must provide an interface that clients use to communicate with the service, by returning an IBinder. We should always implement this method, but if you don’t want to allow binding, then you should return null
    • onCreate() : This method is called while the service is first created. Here all the service initialization is done
    • onDestroy() : The system calls this method when the service is no longer used and is being destroyed. All the resources, receivers, listeners clean up are done here
    • onStartCommand() :调用startService()时将调用此方法。 执行此方法后,服务将启动,并且可以无限期在后台运行。 如果服务定义为有界服务,则不需要此方法。 定义此方法后,该服务将在后台无限期运行。 我们将自己停止服务
    • onBind()当将服务定义为有界服务时,需要重写此方法。 调用bindService()时将调用此方法。 在此方法中,我们必须通过返回IBinder,提供客户端用于与服务进行通信的接口。 我们应该始终实现此方法,但是如果您不想允许绑定,则应该返回null
    • onCreate() :在首次创建服务时调用此方法。 此处所有服务初始化均已完成
    • onDestroy() :当不再使用该服务并将其销毁时,系统将调用此方法。 所有资源,接收者,监听者的清理都在这里完成
  46. 区分广播接收器和服务。 (Differentiate between Broadcast Receivers and Services.)

    A service is used for long running tasks in the background such as playing a music or tracking and updating the user’s background location.

    A Broadcast Receiver is a component that once registered within an application executes the onReceive() method when some system event gets triggered. The events the receiver listens to are defined in the AndroidManifest.xml in the intent filters. Types of system events that a Broadcast Receiver listens to are:
    changes in the network, boot completed, battery low, push notifications received etc. We can even send our own custom broadcasts using sendBroadcast(intent).

    服务用于在后台长时间运行的任务,例如播放音乐或跟踪和更新用户的背景位置。

    广播接收器是一个组件,一旦某个系统事件被触发,该组件一旦在应用程序中注册,便会执行onReceive()方法。 接收方侦听的事件是在Intent过滤器的AndroidManifest.xml中定义的。 广播接收器侦听的系统事件类型为:
    网络更改,启动完成,电池电量不足,收到推送通知等。我们甚至可以使用sendBroadcast(intent)发送自己的自定义广播。

  47. 如何在manifest.xml中注册广播接收器? (How is a Broadcast Receiver registered in the manifest.xml?)

    The Broadcast Receiver is defined inside the receiver tags with the necessary actions defined inside the intent filter as shown below.

    <receiver android:name=".ConnectionReceiver" >
    	<intent-filter>
    		<action android:name="android.net.conn.CONNECTIVITY_CHANGE" />
    	</intent-filter>
    </receiver>

    广播接收器在接收器标签中定义,必要的动作在意图过滤器中定义,如下所示。

  48. RecyclerView与ListView有何不同? (How does RecyclerView differ from ListView?)

    • A RecyclerView recycles and reuses cells when scrolling. This is a default behaviour. It’s possible to implement the same in a ListView too but we need to implement a ViewHolder there
    • A RecyclerView decouples list from its container so we can put list items easily at run time in the different containers (linearLayout, gridLayout) by setting LayoutManager
    • Animations of RecyclerView items are decoupled and delegated to ItemAnimator

    • RecyclerView在滚动时回收并重用单元格。 这是默认行为。 也可以在ListView中实现相同的功能,但是我们需要在其中实现ViewHolder
    • RecyclerView将列表与其容器分离,因此我们可以通过设置LayoutManager在运行时轻松地将列表项放在不同的容器(linearLayout,gridLayout)中
    • RecyclerView项目的动画已解耦并委派给ItemAnimator
  49. 实现一个ExpandableListView,默认情况下所有标头组都在其中展开。 (Implement an ExpandableListView where all the header groups are expanded by default.)

    We need to call the method expandGroup on the adapter to keep all the group headers as expanded.

    ExpandableListView el = (ExpandableListView) findViewById(R.id.el_main);
    elv.setAdapter(adapter);
    for(int i=0; i < adapter.getGroupCount(); i++)
        el.expandGroup(i);

    我们需要在适配器上调用方法expandGroup,以使所有组标头保持展开状态。

  50. 当执行它的活动改变方向时,AsyncTask会发生什么? (What happens to the AsyncTask when the Activity that’s executes it, changes the orientation? )

    The lifecycle of an AsyncTask is not tied onto the Activity since it’s occurring on a background thread. Hence an orientation change won’t stop the AsyncTask. But if the AsyncTask tries to update the UI thread after the orientation is changed, it would give rise to java.lang.IllegalArgumentException: View not attached to window manager since it will try to update the former instances of the activity that got reset.

    AsyncTask的生命周期未绑定到Activity,因为它发生在后台线程上。 因此,方向更改不会停止AsyncTask。 但是,如果AsyncTask在更改方向后尝试更新UI线程,则会引起java.lang.IllegalArgumentException: View not attached to window manager因为它将尝试更新已重置的活动的以前的实例。

  51. / assets和/ res / raw /文件夹的用途是什么? (What is the use of /assets and /res/raw/ folders?)

    /assets folder is empty by default. We can place files such as custom fonts, game data here. Also, this folder is ideal for maintaining a custom dictionary for lookup. The original file name is preserved. These files are accessible using the AssetManager (getAssets()).

    /res/raw folder is used to store xml files, and files like *.mp3, *.ogg etc. This folder gets built using aapt and the files are accessible using R.raw.

    / assets文件夹默认为空。 我们可以在此处放置自定义字体,游戏数据等文件。 同样,此文件夹是维护自定义词典以进行查找的理想选择。 原始文件名被保留。 可以使用AssetManager( getAssets() )访问这些文件。

    / res / raw文件夹用于存储xml文件,以及* .mp3,*。ogg等文件。此文件夹是使用aapt构建的,并且可以使用R.raw访问这些文件。

That’s all for android interview questions and answers. If I will get some more android interview questions, I will add them to the list with detailed answers later on.

这就是android面试问题和答案的全部内容。 如果我会收到更多关于android面试的问题,稍后将它们添加到列表中,并提供详细的答案。

翻译自: https://www.journaldev.com/10929/android-interview-questions-and-answers

android系统面试问答

Logo

瓜分20万奖金 获得内推名额 丰厚实物奖励 易参与易上手

更多推荐