As more and more tripartite apps appear on the market, some mobile phone manufacturers also start to impose installation or operation restrictions on these apps, or the version of the tripartite APP itself is too low to be supported by a particular system version.

Today I’m going to simulate the effect of implementing a feature that “cannot run on the current system version because the APP version itself is too low”.

The implementation idea is as follows:

  1. To get the target running version of your APP, you also need to know the compiled version of your system

  2. Through version comparison, when entering the APP, users will be given a prompt of “not supported to run”

  3. After confirming the prompt, the user directly exits the APP

The key point is the use of targetSdkVersion, source code as follows:

1, the main Activity

public class TargetSdkVersionDemo extends Activity { @Override protected void onCreate(Bundle onSavedInstance) { super.onCreate(onSavedInstance); setContentView(R.layout.target_sdk_version_demo); int appTargetSdkVersion = getApplicationInfo().targetSdkVersion; Log.i("TargetSdkVersionDemo", "targetsdkversion " + appTargetSdkVersion); If (appTargetSdkVersion <= build.version_codes.o) {// If (appTargetSdkVersion <= build.version_codes.o) { showNotSupportDialog(appTargetSdkVersion); }} private void showNotSupportDialog(int version) {new AlertDialog.Builder(this).setMessage(" This APP is running in the target version "+ version + ", lower than the current version of the phone, does not support running!" ) .setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, Int which) {// Finish (); } }) .create() .show(); }}Copy the code

In androidmanifest.xml, you need to define the targetSdkVersion attribute of the uses-sdk tag:

<uses-sdk android:targetSdkVersion="25" />
Copy the code

Note:

If you define targetSdkVersion in the build.gradle file in the app directory, the value in AndroidManifest will be overridden.

3. The effect picture is as follows:

The application uses getApplicationInfo().targetsdkVersion as a member of applicationInfo.java. This value is parsed by the system service PackageManagerService during APK installation. The parsed source is in frameworks\ Base \ Core \ Java \ Android \ Content \ PM \ packageParser.java:

You can see:

  • TAG_USES_SDK (uses-sdk)

  • Then parse the attribute name targetSdkVersion and the value of minSdkVersion

Last assigned to the applicationInfo object:

pkg.applicationInfo.targetSdkVersion = targetSdkVersion
Copy the code

This article is published by OpenWrite, a blogging tool platform