Android ttraining 模块总结 01

来源:互联网 发布:对称矩阵谱分解 编辑:程序博客网 时间:2024/06/14 11:07

Android Training Summary

create an android Project

  • build.gradle
    1. compiledSdkVersion
      setting this to the latest version allows you to enable new features and optimize your app for a great user experience on the latest devices.
    2. applicationId
      is the fully qualified package name for your application that you specified in the New Project wizard.
    3. minSdkVersion
      is the Minimum SDK version you specified during the New Project wizard. This is the earliest version of the Android SDK that your app supports.
    4. targetSdkVersion
      indicates the highest version of Android with which you have tested your application,default that is the newest
  • /res
    1. drawable-

Supporting Different Devices

  • Some of the important variations that you should consider include different languages, screen sizes, and versions of the Android platform.

1.Supporting Different Languages

  • create local directories, such as value-es inside res/
  • create String files in specified folder
  • use the String Resource
    • for instance
      String hello = getResources().getString(R.string.hello_world);

2.Supporting Different Screens

  • Android categorizes device screens using two general properties: size and density,so you should expect that your app will be installed on devices with screens that range in both size and density
  • generalized sizes : small normal large xlarge
  • generalized densities: low (ldpi), medium (mdpi), high (hdpi), extra high (xhdpi)
  • the step of supporting different screens
    1. Create Different Layouts named with a - suffix. For instance

      layout-large/ main.xml
    2. And then system will select the appropriatest view to display
  • Create Different Bitmaps
    • To generate these images, you should start with your raw resource in vector format and generate the images for each density using the following size scale:
      • xhdpi: 2.0
      • hdpi: 1.5
      • mdpi: 1.0 (baseline)
      • ldpi: 0.75
    • So ldpi : mdpi(baseline) : hdpi : xhdpi = 3 : 4 : 6 : 8
    • The folder named as create different screens
      Note: Low-density (ldpi) resources aren’t always necessary. When you provide hdpi assets, the system scales them down by one half to properly fit ldpi screens.

3.Supporting Different Platform Versions

Tip: In order to provide the best features and functionality across several Android versions, you should use the Android Support Library in your app, which allows you to use several recent platform APIs on older versions.

  • Specify Minimum and Target API Levels
    • the minSdkVersion and targetSdkVersion attributes for the element identify the lowest API level with which your app is compatible and the highest API level against which you’ve designed and tested your app.For instance :
      id:minSdkVersion="4" android:targetSdkVersion="15" />
  • Check System Version at Runtime

    • use following code to check the condition of platform

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    }


Note: When parsing XML resources, Android ignores XML attributes that aren’t supported by the current device. So you can safely use XML attributes that are only supported by newer versions without worrying about older versions breaking when they encounter that code.

Managing the Activity Lifecycle

  • If the user performs an action that starts another activity or switches to another app, the system calls another set of lifecycle methods on your activity as it moves into the background (where the activity is no longer visible, but the instance and its state remains intact).For easily to start
  • Activity Lifecycle like a pyramid,this is the picture of activity lifecycle
  • Activity Lifecycle stage

    • onCreate()

      onCreate() should define the user interface and possibly instantiate some class-scope variables

    • onStart()
      Technically, the activity becomes visible to the user when onStart() is called,
    • onResume()
      In this state, the activity is in the foreground and the user can interact with it. (Also sometimes referred to as the “running” state.)
    • onPause()
      In this state, the activity is partially obscured by another activity—the other activity that’s in the foreground is semi-transparent or doesn’t cover the entire screen. The paused activity does not receive user input and cannot execute any code.
    • onStop()
      In this state, the activity is completely hidden and not visible to the user; it is considered to be in the background. While stopped, the activity instance and all its state information such as member variables is retained, but it cannot execute any code
    • onDestroy()

      onDestroy(). The system calls this method on your activity as the final signal that your activity instance is being completely removed from the system memory.
      if your activity includes background threads that you created during onCreate() or other long-running resources that could potentially leak memory if not properly closed, you should kill them during onDestroy().Most resources should be released on methods that onPause() and onStop().

      Note: The system calls onDestroy() after it has already called onPause() and onStop() in all situations except one: when you call finish() from within the onCreate() method,the system immediately calls onDestroy() without calling any of other lifecycle method.

  • Pausing and Resuming an Activity
    • the difference between onStop() and onPause()

      As long as the activity is still partially visible but currently not the activity in focus, it remains paused.However, once the activity is fully-obstructed and not visible, it stops

    • When to call onPause()
      1. Check if the activity is visible; if it is not, stop animations or other ongoing actions that could consume CPU. Beginning with Android 7.0,it is a failure.
      2. Commit unsaved changes, but only if users expect such changes to be permanently saved when they leave (such as a draft email).
      3. Release system resources, such as broadcast receivers, handles to sensors (like GPS), or any resources that may affect battery life while your activity is paused and the user does not need them.
      4. onPause() should be used to save little resource,you should avoid performing CPU-intensive work during onPause(),it should be performed during onStop().Everything for the user experience
    • Resume Your Activity
      1. You should initialize components that you release during onPause(),and perform other initialization.
  • Stopping and Restarting an Activity
    • There are a few of key scenarios in which your activity is stopped and restarted:
      • The user opens the Recent Apps window and switches from your app to another app. The activity in your app that’s currently in the foreground is stopped. If the user returns to your app from the Home screen launcher icon or the Recent Apps window, the activity restarts.
      • The user performs an action in your app that starts a new activity. The current activity is stopped when the second activity is created. If the user then presses the Back button, the first activity is restarted.
      • The user receives a phone call while using your app on his or her phone.
    • Stop Your Activity
      • When your activity receives a call to the onStop() method, it’s no longer visible and should release almost all resources that aren’t needed while the user is not using it.
      • 一定要在这里释放了不需要的资源以及保存需要的数据,因为如果系统内存不足,那么会将优先级低的后台应用释放掉。
      • 注意:即使你的activity资源被系统释放掉了,但是view的状态还是存在的被保存到了Bundle里面,所以你不需要再次初始化控件。例如你在EditText里面输入了一段文本,这个文本是不需要存储的,当再次进入还是会恢复的
    • Recreating an Activity
      • the scenarios activity is destroyed
      • Your activity will be destroyed and recreated each time the user rotates the screen
      • By default, the system uses the Bundle instance state to save information about each View object in your activity layout
      • To save additional data about the activity state, you must override the onSaveInstanceState() callback method.
      • If the system must recreate the activity instance later, it passes the same Bundle object to both the onRestoreInstanceState() and onCreate() methods.
      • 上面的两点可以看出,如果你重写了onSaveInstanceState(),那么如果系统将activity销毁并重建的时候在onCreate()和onRestoreInstanceState() 方法中的bundle就是这些activity的实例,会保存这些信息,也就是说这是一个activity的信息集合,就像handler一样,不过是由系统调用的
      • 说明一下重建过程
        • 在resume阶段如果系统想destroy activity,那么要调用onSaveInstanceState(),然后再destroy
        • 在onCreate到resume的中间要调用onRestoreInstanceState()方法,来获取save data
      • so your activity can save state information with a collection of key-value pairs.So you can use the methods that put and int to save and get data.
        public void onRestoreInstanceState(Bundle savedInstanceState) {
        // Always call the superclass so it can restore the view hierarchy
        super.onRestoreInstanceState(savedInstanceState);
        // Restore state members from saved instance
        mCurrentScore = savedInstanceState.getInt(STATE_SCORE);
        mCurrentLevel = savedInstanceState.getInt(STATE_LEVEL);
        }

Building a dynamic UI with Fragments

  • How to create a Fragment?
    • You can think the fragment is a moduler section for activity, which has it’s own lifecycle receives its own input events, and which you can add or remove while the activity is running
    • 如果要支持Android 1.6以及以下那么需要引进Support Library
  • 必须要重写的方法
    • onCreateView()
  • 使用fragment步骤
    1. 创建一个类继承Fragment
    2. 重写Fragment的onCreateView()方法

      public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
      return inflater.inflate(R.layout.fragment_1,container,false); //这里用来加载fragment需要的布局文件
      }
      //照抄就好
    3. 在activity里面引入

      <fragment android:name="com.zh.young.fragmentdemo.fragment.fragment1"
      android:id="@+id/test"
      android:layout_weight="1"
      android:layout_width="0dp"
      android:layout_height="match_parent" />
      <!--fragment的使用必须要加一个id,不然会报错,到目前为止不知道什么原因-->
    4. 然后就OK了
0 0