introduce

This tutorial will show you how to create your own code templates. Most Android developers have used the Android code template at least once to create new projects. But have you ever tried creating your own Android code template? In this tutorial, we will show you the Android project template that you can use to generate the Google Analytics configuration from the Android Studio IDE.

The source code

Download the source text link here

Code generation process diagram

Creation Procedure

To create your own template, make sure:

  1. You’ve seen the code generation process diagram above;
  2. You have some knowledge of FreeMarker;
  3. You have some knowledge of the Android IDE template format, and you can check out the documentation here.

Step 1: Create the Google Analytics application folder

Is this your template directory, on Windows, ${android studio installation path} / plugins/android/lib/templates /, other platform Linux, Mac OS please find itself; In GoogleAnalyticApplication folder created in the root folder and other files, as shown below:

Step 2: Create the template.xml file

Each template directory must contain a template.xml file, which contains metadata about the template, including name, description, category, and user-visible parameters that the IDE presents to the user as options. The file also specifies the recipe file name and the global variable file that FreeMarker handles. If there are global variables in addition to the template parameter values, they should be visible to all FreeMarker handles files. Template.xml

<? The XML version = "1.0"? > <template format="3" revision="4" name="Google Analytics Application" minApi="7" minBuildApi="14" description="Creates  a new application that has already Google Analytics configuration."> <category value="Activity" /> <formfactor value="Mobile" /> <parameter id="activityClass" name="Activity Name" type="string" constraints="class|unique|nonempty" suggest="${layoutToActivity(layoutName)}" default="MainActivity" help="The name of the activity class to create" /> <parameter id="layoutName" name="Layout Name" type="string" constraints="layout|unique|nonempty" suggest="${activityToLayout(activityClass)}" default="activity_main" help="The name of the layout to create for the activity" /> <parameter id="classApplication" name="Class extends Application" type="string" constraints="nonempty|class" help="The name of class that extends from Application" /> <parameter constraints="nonempty|string" id="googleAnalyticID" name="Google Analytic ID" type="string" help="Id of Google Analytic"  /> <parameter id="dispatchPeriod" name="Dispatch Period" help="Frequency of automatic dispatch in seconds. Defaults to 30 minutes (1800 seconds)." type="string" default="1800"/> <parameter id="autoActivityTracking" name="Auto Activity Tracking" help="If true, views (Activities) will be tracked automatically. false by default." type="boolean" default="false"/> <! -- 128x128 thumbnails relative to template.xml --> <thumbs> <! -- default thumbnail is required --> <thumb>template_google_analytics.png</thumb> </thumbs> <globals file="globals.xml.ftl" /> <execute file="recipe.xml.ftl" /> </template>Copy the code

Some of the parameters are: ActivityClass, layoutName, classApplication, googleAnalyticID, dispatchPeriod, autoActivityTracking, will be displayed in the pop-up window when the project is created.

Step 3: Create globals.xml.ftl

This is an optional file that contains definitions of global variables for all FreeMarker processing tasks in this template. globals.xml.ftl

<? The XML version = "1.0"? > <globals> <global id="manifestOut" value="${manifestDir}" /> <global id="srcOut" value="${srcDir}/${slashedPackageName(packageName)}" /> <global id="resOut" value="${resDir}" /> </globals>Copy the code

Step 4: Create related files and folders in the root folder

The root folder contains the template source code

1. Create AndroidManifest. XML. FTL
<? The XML version = "1.0" encoding = "utf-8"? > <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="${packageName}"> <application android:name="${packageName}.${classApplication}" android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme"> <meta-data android:name="com.google.android.gms.version" android:value="@integer/google_play_services_version" /> <meta-data android:name="com.google.android.gms.analytics.globalConfigResource" android:resource="@xml/analytics_global_config" /> <activity android:name=".activities.MainActivity" android:label="@string/app_name"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> </application> </manifest>Copy the code

Where packageName, classApplication is defined in template. XML.

2. Create the application.java.ftl file
package ${packageName}; import android.app.Application; import com.google.android.gms.analytics.GoogleAnalytics; import com.google.android.gms.analytics.Tracker; /** * Created by TungDX on 5/29/2015. */ public class ${classApplication} extends Application { private static GoogleAnalytics analytics; private static Tracker tracker; @Override public void onCreate() { analytics = GoogleAnalytics.getInstance(this); tracker = analytics.newTracker("${googleAnalyticID}"); } public static GoogleAnalytics getGoogleAnalytics() { return analytics; } public static Tracker getTracker() { return tracker; }}Copy the code

The packageName, googleAnalyticID, is defined in template.xml.

3. Create the mainactivity.java. FTL file
package ${packageName}.activities; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import ${packageName}.${classApplication}; import ${packageName}.R; public class MainActivity extends ActionBarActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @Override protected void onStart() { super.onStart(); ${classApplication}.getGoogleAnalytics().reportActivityStart(this); } @Override protected void onStop() { super.onStop(); ${classApplication}.getGoogleAnalytics().reportActivityStop(this); }}Copy the code

Where packageName, classApplication is defined in template. XML.

4. Create the activity_main.xml. FTL file
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    android:paddingBottom="@dimen/activity_vertical_margin">
    <TextView
        android:text="@string/ready"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />
</RelativeLayout>
Copy the code
Create the strings.xml. FTL file
<resources> <#if ! isNewProject> <string name="title_${activityToLayout(activityClass)}">${escapeXmlString(activityTitle)}</string> </#if> <string name="ready">Google Analytic is ready! </string> </resources>Copy the code
6. Create dimens. XML
<resources> <! -- Default screen margins, per the Android Design guidelines. --> <dimen name="activity_horizontal_margin">16dp</dimen> <dimen name="activity_vertical_margin">16dp</dimen> </resources>Copy the code
7. Create the victim.xml. FTL file

The recipe. XML file contains the various commands to execute when generating code from this template. For example, you can copy certain files or directories, or run source files through FreeMarker and ask the IDE to open a file after the code is generated.

<? The XML version = "1.0"? > <recipe> <dependency mavenUrl="com.android.support:support-v4:${targetApi}.+" /> <dependency mavenUrl="com.android.support:appcompat-v7:${targetApi}.+"/> <dependency mavenUrl="com.google.android.gms:play-services:6+" /> <instantiate from="AndroidManifest.xml.ftl"to="${escapeXmlAttribute(manifestOut)}/AndroidManifest.xml" /> <instantiate from="src/app_package/Application.java.ftl" to="${escapeXmlAttribute(srcOut)}/${classApplication}.java"/> <instantiate from="src/app_package/activities/MainActivity.java.ftl" to="${escapeXmlAttribute(srcOut)}/activities/${activityClass}.java"/> <instantiate from="res/xml/analytics_global_config.xml.ftl" to="${escapeXmlAttribute(resOut)}/xml/analytics_global_config.xml"/> <instantiate from="res/layout/activity_main.xml.ftl" to="${escapeXmlAttribute(resOut)}/layout/${layoutName}.xml"/> <copy  from="res/values/dimens.xml" to="${escapeXmlAttribute(resOut)}/values/dimens.xml"/> <merge from="res/values/strings.xml.ftl"to="${escapeXmlAttribute(resOut)}/values/strings.xml" /> <open file="${escapeXmlAttribute(srcOut)}/activities/${activityClass}.java" /> <open file="${escapeXmlAttribute(resOut)}/layout/${layoutName}.xml" /> </recipe>Copy the code
8. Check dependencies

9. Check the AndroidManifest. XML. FTL
<instantiate from="AndroidManifest.xml.ftl"          to="${escapeXmlAttribute(manifestOut)}/AndroidManifest.xml" />
Copy the code

10. Check the Application. The Java. FTL
<instantiate from="src/app_package/Application.java.ftl" to="${escapeXmlAttribute(srcOut)}/${classApplication}.java"/>
https://robusttechhouse.com/wp-admin/post.php?post=6937&action=edit&message=10#
Copy the code

11. Check the MainActivity. Java. FTL
<instantiate from="src/app_package/activities/MainActivity.java.ftl" to="${escapeXmlAttribute(srcOut)}/activities/${activityClass}.java"/>
Copy the code

12. Check analytics_global_config. XML. FTL
<instantiate from="res/xml/analytics_global_config.xml.ftl" to="${escapeXmlAttribute(resOut)}/xml/analytics_global_config.xml"/>
Copy the code

13. Generate activity_main. XML, dimens. XML, and strings. XML files from the template
<instantiate from="res/layout/activity_main.xml.ftl" to="${escapeXmlAttribute(resOut)}/layout/${layoutName}.xml"/> <copy  from="res/values/dimens.xml" to="${escapeXmlAttribute(resOut)}/values/dimens.xml"/> <merge from="res/values/strings.xml.ftl" to="${escapeXmlAttribute(resOut)}/values/strings.xml" />Copy the code
14. Open the corresponding file after the project is created
<open file="${escapeXmlAttribute(srcOut)}/activities/${activityClass}.java" />
<open file="${escapeXmlAttribute(resOut)}/layout/${layoutName}.xml" />
Copy the code

If your Android Studio IDE is running, restart it to see your template as shown below

The original link