What is the Activity

An Activity is one of four components that provide an interface for the user to tap and swipe.

Activity Lifecycle

onCreate(): You must implement this callback, which is triggered when the system creates your Activity. Your implementation should initialize the Activity’s base components.

“OnStart ()” : This callback contains the final preparations before the Activity enters the foreground to interact with the user. At this point the user can’t interact.

“OnResume ()” : At this point, the Activity is at the top of the Activity stack and captures all user input. Most of the core functionality of the application is implemented in the onResume() method. At this point the user is visible and interactive.

“OnPause ()” : The system calls onPause() when the user clicks the “Return” or “recently used application” button and the Activity loses focus and enters the “paused” state. At this point the user can’t interact. The system stops cpu-consuming operations such as animations.

“OnStop ()” : the user is not visible at this point. Stop animation, refresh UI, etc.

“OnRestart ()” : This callback is called when an Activity in the “onStop()” state is about to restart. OnRestart () restores the Activity from the state it was in when it was stopped to the running state.

“OnDestroy ()” : This is the last method of the Activity. This can be determined using isFinishing(). If any dialog is running, cancel it on this interface, otherwise throw an exception.

There are four main states of an Activity

“Running” : In the foreground of the screen (at the top of the current task stack)

“Paused” : Lost focus but still visible to the user (overwriting the Activity may be transparent or incomplete blocked)

“Stopped” : Completely overwritten by another Activity

“Destroyed” : Exit, completely destroy

Activity Stack (in and out)

When multiple activities run,Android manages activities in an Activity stack. The state of an instance of an Activity determines its position in the stack. The Activity in the foreground is always at the top of the stack. When the Activity in the foreground is destroyed due to an exception or other reason, the Activity in the second layer of the stack is activated and rises to the top of the stack. When a new Activity starts pushing, the original Activity is pushed to the second layer of the stack. An Activity’s position on the stack changes to reflect its transition between states.

Start the Activity

1. Simple startup

Declare it in androidManifest.xml

<? xml version="1.0" encoding="utf-8"? >

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

    package="com.scc.demo">

    <application

        android:allowBackup="true"

        android:icon="@mipmap/ic_launcher"

        android:label="@string/app_name"

        android:roundIcon="@mipmap/ic_launcher_round"

        android:supportsRtl="true"

        android:theme="@style/Theme.Demo">

        <activity

            android:name=".actvitiy.MainActivity">

            <intent-filter>

                <action android:name="android.intent.action.MAIN" />

 

                <category android:name="android.intent.category.LAUNCHER" />

            </intent-filter>

        </activity>

        <activity android:name="com.scc.demo.actvitiy.RedActivity"/>

        <activity android:name="com.scc.demo.actvitiy.BlueActivity"/>

    </application>

</manifest>

Copy the code

Start in mainActivity.java

Intent intent = new Intent(MainActivity.this,RedActivity.class);

startActivity(intent);

Copy the code

2. Data transmission

2.1 Simple data transfer mainActivity.class

Intent intent = new Intent(MainActivity.this,BlueActivity.class);

intent.putExtra("scc"."aiyouyou");

startActivity(intent);

Copy the code

BlueActivity.class

Log.e(getClass().getName(),getIntent().getStringExtra("scc"));

Print the result: aiyouyou

Copy the code

2.2 Complex data transfer

2.2.1 Using the Bundle mainActivity.class

Intent intent = new Intent(MainActivity.this,BlueActivity.class);

Bundle bundle = new Bundle();

bundle.putString("scc"."heiha");

bundle.putString("size"."18");

intent.putExtras(bundle);

startActivity(intent);

Copy the code

BlueActivity.class

Intent intent = getIntent();

Bundle bundle = intent.getExtras();

Log.e(getClass().getName(),bundle.getString("scc") +":"+bundle.getString("size"));

Copy the code

Running result:

Heiha:18

Copy the code

2.2.2 Using Serializable

2.2.2.1 Create an entity class User Implements Serializable

MainActivity.class

Intent intent = new Intent(MainActivity.this,BlueActivity.class);

intent.putExtra("user".new User("Handsome"."Male".20));

startActivity(intent);

Copy the code

BlueActivity.class

User user = (User)getIntent().getSerializableExtra("user");

Log.e(getClass().getName(),user.getName()+":"+user.getGender()+user.getAge());

Copy the code

Running result:

Handsome times: male20

Copy the code

3. The boot tape returns a value

Start the MainActivity. Java

Intent intent = new Intent(MainActivity.this,BlueActivity.class);

intent.putExtra("scc"."I'm here.");

startActivityForResult(intent,998);

Log.e(getClass().getName(),"startActivityForResult");

@Override

protected void onActivityResult(int requestCode, int resultCode, Intent data) {

    super.onActivityResult(requestCode, resultCode, data);

    Log.e(getClass().getName(),"requestCode:"+requestCode+":resultCode:"+resultCode);

    // Start ActivityCode value 998 and return ActivitiyCode value 500

    if(requestCode==998&&resultCode==500) {

        Log.e(getClass().getName(),"Intent data:"+data.getStringExtra("scc_result"));

    }

}

Copy the code

Booted blueactVitiy.java

Log.e(getClass().getName(),getIntent().getStringExtra("scc"));

btn_back.setOnClickListener(new View.OnClickListener() {

    @Override

    public void onClick(View v) {

        Log.e(getClass().getName(),"onClick.setResult");

        Intent intent = new Intent();

        intent.putExtra("scc_result"."Srema, your emperor is back.");

        setResult(500, intent);

        finish();

    }

});

Copy the code

Running result:

Click the MainActivity start button

MainActivity$1: startActivityForResult

BlueActivity: I come

Click the BlueActvitiy Back button

lueActivity$1: onClick.setResult

requestCode:998:resultCode:500

Intent Data: Srema your emperor is back

That's done.

Copy the code

Note :requestCode must not be equal to resultCode, otherwise postback will be invalid.

The launchMode of the Activity

“Standard” : Each time an Activity is activated (startActivity), an instance of the Activity is created and placed in the task stack;

“SingleTop” : If an Activity activates itself, that is, if the Activity is at the top of the task stack, you do not need to create it, otherwise you create an instance of the Activity;

“SingleTask” : If the Activity you want to activate already has an instance on the task stack, you don’t need to create it, you just need to put the Activity on top of the stack. And call its onNewIntent();

“SingleInstance” : An instance of MainActivity is created in the stack of application 1. If application 2 also wants to activate MainActivity, it does not need to be created. Both applications share the instance.

Priority of the process

Foreground Process 1. Foreground Process It indicates that the user is interacting with the process at the highest priority. The Android system marks a process as a foreground process based on the following conditions:

  • The process holds an Activity that the user is interacting with (that is, the Activity’s lifecycle method goes to the onResume() method).

  • This process holds a Service that is executing the lifecycle methods (onCreate(), onStart(), onDestroy()).

  • This process holds a BroadcastReceiver that is executing the onReceive() method.

2. Visible Process. It indicates that although the process does not hold any foreground components, it can still affect the interface that the user sees. The Android system marks a process as visible based on the following conditions:

  • The process holds a non-foreground Activity, but the Activity is still visible to the user (that is, the Activity calls onPause()). For example, when an activity starts a dialog, the activity is blocked by the dialog.

  • The process holds a Service that is executing the service.startforeground () method.

3. Service Process. All services are classified as Service processes except those that meet the criteria of foreground and visible processes.

4. Background process. A background process is a process that holds an invisible Activity that calls the onStop() method. Usually, there are many background processes, and when memory runs out, among all background processes, the one that has not been used for the longest time will be reclaimed first according to LRU (most recently used) rules.

“5. Empty Process”. A process that does not hold any active components. This process is kept for the sole purpose of caching so that the next time components in the process are started, they can respond faster. When resources are scarce, the system balances the process cache with the underlying kernel cache for recycling.

  • These processes typically contain one or more Activity instances that are not currently visible to the user (the onStop() method has been called and returns).

Scheme Jump Protocol

1. Scheme in Android is a page jump protocol. You can jump to each page in the app by defining your own Scheme protocol

2. The server can tell the app which page to jump to

3. App can jump to another App page

4. Go to the H5 page

Sample:

1. Add an Intent-filter Schema to the Activity tag in androidManifest.xml

<activity android:name="com.scc.demo.actvitiy.RedActivity"

   >

    <intent-filter>

        <action android:name="android.intent.action.VIEW" />

        <category android:name="android.intent.category.DEFAULT" />

        <category android:name="android.intent.category.BROWSABLE" />

        <data

            android:host="scc"

            android:path="/redActivity"

            android:port="2021"

            android:scheme="sccdemo" />

    </intent-filter>

</activity>

Copy the code

2. Call

2.1. Call in HTML

<a href="sccdemo://scc:2021/redActivity? color=0000&ad=10086"</a> </a>

Copy the code

2.2. Calls within the application

Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("sccdemo://scc:2021/redActivity? color=0000&ad=10086"));

startActivity(intent);

Copy the code

2.3. Get Url and other parameters

Intent intent = getIntent();

Uri data = intent.getData();

String action = intent.getAction();

String scheme = intent.getScheme();

Set<String> categories = intent.getCategories();

Log.e("SCHEME"."data:"+data);

Log.e("SCHEME"."action:"+action);

Log.e("SCHEME"."categories:"+categories);

Log.e("SCHEME"."DataString:"+intent.getDataString());

Log.e("SCHEME"."-- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -- -");

Log.e("SCHEME"."scheme:"+scheme);

Log.e("SCHEME"."id:"+data.getQueryParameterNames());

Log.e("SCHEME"."host:"+data.getHost());

Log.e("SCHEME"."path:"+data.getPath());

Log.e("SCHEME"."port:"+data.getPort());

Copy the code

Android’s API does not declare that exceptions will be thrown, so it cannot throw Runtime exceptions at Runtime. Have you ever encountered this? If so, what problems will it cause? How to solve it?

Yes, like NullPointerException. I have encountered textView not initialized when, for example, textView.settext (). Will cause the program can not run normally appear forceclose (current application clashed NullPointExection (null pointer), IndexOutOfBoundsException (Angle of the cross) and so on a series of uncaught exception). Open the console to view the logcat information to find the exception information and modify the program.

If a background Activity is reclaimed by the system for some reason, how do I save the current state before being reclaimed by the system?

Override the onSaveInstanceState() method, which holds the data that needs to be saved, and which will be called before the activity is reclaimed. You can extract the saved data from it by overriding the onRestoreInstanceState() method (it is recommended that you keep the saved state below 50K of data).

Set your Activity to look like a window

In the AndroidMainfest.xml configuration: Android: theme = “@ android: style/theme. The Dialog”, another android: theme = “@ android: style/theme. Translucent” is transparent.

Out of the Activity? Exit an Application that has invoked multiple activities?

For a single activity exit:

For an application with a single Activity, exit is as simple as finish(). Methods such as killProcess() and system.exit () can also be used.

For multiple activity exits at the same time:

1, throwing an exception to Force exit: this method makes the program Force Close by throwing an exception. However, the problem that needs to be solved is how to end the program without the Force Close window popping up.

2. Record the Activities you start: Record each Activity you start. Close each Activity when you need to exit.

3. Send a specific broadcast: When the application needs to end, send a specific broadcast, each Activity receives the broadcast, then close.

When you start a new Activity, use startActivityForResult, then tag yourself, handle in onActivityResult, and close recursively.

For programming convenience, it’s a good idea to define an Activity base class that handles these common problems.

Passing large amounts of data between activities with Intents can cause problems

There is a limit to the size of the Intent’s data. It is not specified here, but the experimental method shows that the data should be limited to 1MB(1024KB). It is found that when the data size exceeds 1MB, the application will blink, stop running, and other exceptions (different phones react differently). Therefore, it can be determined that the transmission capacity of an Intent is less than 1MB, but this value varies according to different versions and vendors.

Solutions are as follows:

1. Reduce the data passed through intents, and use the transient keyword to modify non-required fields.

2. Convert the object to a JSON string, reducing the data volume. Because a JVM loading a class usually comes with extra space to hold information about the class, converting the data in the class to A JSON string can reduce the data size.

What is the life cycle of the activity when switching between vertical and horizontal screens?

1. Android :configChanges without setting the Activity. When switching between the horizontal and portrait screens, each life cycle will be called again.

Set android:configChanges=”orientation” for the Activity to re-call each lifecycle when switching between the horizontal and portrait screens.

3, set up the Activity of the android: configChanges = “orientation” | “screenSize, horizontal, vertical screen switch not to call the life cycle. Only the onConfigurationChanged() method is executed.