The privacy protocol interface often pops up during Android studio docking

preface:

Now we pay more attention to privacy information, so we often encounter the pop-up window to add privacy agreement. For some lazy technologies, it is the easiest to have ready-made code or encapsulated things. There's no need to spend too much time dealing with it.

Well, the rookie is also lazy, not directly encapsulated, directly put the corresponding code, need to directly copy the corresponding code to their own project, and then use the call can be, save trouble.

1. There must be a privacy pop-up interface. Therefore, create an interface under the layout directory.

The name of this rookie is activity_privacy_policy.xml, what do you like.

Directly on activity_privacy_policy code.

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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:orientation="vertical"
    android:background="@drawable/dialog_privacy_bg"
    >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignParentBottom="true"
        >

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_above="@+id/ll_btn_bottom"
            android:layout_marginBottom="35dp"
            android:gravity="center"
            android:orientation="vertical"
            tools:ignore="UnknownId">

            <TextView
                android:id="@+id/tv_title"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_marginTop="10dp"
                android:layout_marginBottom="10dp"
                android:text="User usage protocol"
                android:textColor="@color/colorBlack"
                android:textSize="18sp"

                />


            <ScrollView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:layout_marginLeft="5dp"
                android:layout_marginRight="5dp"
                android:layout_marginBottom="15dp"
                android:fadingEdgeLength="60dp"
                android:requiresFadingEdge="horizontal">

                <TextView
                    android:id="@+id/tv_content"
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:layout_marginTop="10dp"
                    android:singleLine="false"
                    android:text=""
                    android:textColor="@color/colorBlack"

                    />
            </ScrollView>


        </LinearLayout>

        <LinearLayout
            android:id="@+id/BtnView"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentStart="true"
            android:layout_alignParentBottom="true"
            android:gravity="bottom">

            <Button
                android:id="@+id/btn_exit"
                android:layout_width="0dp"
                android:layout_height="32dp"
                android:layout_weight="1"
                android:background="@color/colorWhite"
                android:text="@string/privacy_exit"
                android:textColor="@color/colorGray"
                android:textSize="16sp"
                android:textStyle="bold" />

            <View
                android:layout_width="0.25dp"
                android:layout_height="40dp"
                android:background="@color/colorGray" />

            <Button
                android:id="@+id/btn_enter"
                android:layout_width="0dp"
                android:layout_height="32dp"
                android:layout_weight="1"
                android:background="@color/colorWhite"
                android:text="@string/privacy_agree"
                android:textColor="@color/colorOrange"
                android:textSize="16sp"
                android:textStyle="bold" />

        </LinearLayout>
    </RelativeLayout>
</LinearLayout>

2. Since there is a pop-up interface, there is the BG code of the pop-up interface, so create a dialog in the drawable directory_ privacy_ bg. xml.

code:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <!--Fill settings-->
    <solid android:color="@android:color/white" />

    <!--Fillet settings-->
    <corners android:radius="6dp" />

</shape>

3. Then the color setting is indispensable. Go directly to the colors. In the values directory Fill in the XML. For example, the color used by this rookie

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#008577</color>
    <color name="colorPrimaryDark">#00574B</color>
    <color name="colorAccent">#D81B60</color>
    <color name="colorWhite">#FFFFFFFF</color>
    <color name="colorBlack">#FF000000</color>
    <color name="colorGray">#878787</color>
    <color name="colorOrange">#FFE26C25</color>
    <color name="colorBlue">#FF036EB8</color>
</resources>

4. With color, words are indispensable. So in the values directory, the string XML button text and so on. For this rookie

<string name="privacy_exit">sign out</string>
<string name="privacy_agree">agree</string>

These two buttons are used to confirm and reject private content. What do you like to use to determine for yourself. After all, I can't force you to use the same as me.

5. The premise content of realizing the privacy pop-up has been prepared, so it is necessary to start calling the privacy pop-up. After all, the privacy content is required when entering for the first time, so it is necessary to deal with it according to the actual situation. Secondly, there are generally two privacy protocols, one is the user agreement and the other is the privacy agreement. So, before and after, it depends on the demand,

5.1 since you only need to display once, you need to save the data and directly save the data tool class.

package //I hide the package name
import android.content.Context;
import android.content.SharedPreferences;

import java.util.Map;
/**
 * Cache data locally
 * **/
public class DataUtils {
    /**
     * SP file name saved in the phone
     */
    public static final String FILE_NAME = "privacy_sp";

    /**
     * Save data
     */
    public static void put(Context context, String key, Object obj) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        if (obj instanceof Boolean) {
            editor.putBoolean(key, (Boolean) obj);
        } else if (obj instanceof Float) {
            editor.putFloat(key, (Float) obj);
        } else if (obj instanceof Integer) {
            editor.putInt(key, (Integer) obj);
        } else if (obj instanceof Long) {
            editor.putLong(key, (Long) obj);
        } else {
            editor.putString(key, (String) obj);
        }
        editor.commit();
    }

    public static  boolean isKeep(Context context, String key, Object defaultObj){
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, context.MODE_PRIVATE);
        if(sp.contains(key))
        {

        }

        return false;
    }
    /**
     * Get specified data
     */
    @org.jetbrains.annotations.Nullable
    public static Object get(Context context, String key, Object defaultObj) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, context.MODE_PRIVATE);
        if (defaultObj instanceof Boolean) {
            return sp.getBoolean(key, (Boolean) defaultObj);
        } else if (defaultObj instanceof Float) {
            return sp.getFloat(key, (Float) defaultObj);
        } else if (defaultObj instanceof Integer) {
            return sp.getInt(key, (Integer) defaultObj);
        } else if (defaultObj instanceof Long) {
            return sp.getLong(key, (Long) defaultObj);
        } else if (defaultObj instanceof String) {
            return sp.getString(key, (String) defaultObj);
        }
        return null;
    }

    /**
     * Delete specified data
     */
    public static void remove(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.remove(key);
        editor.commit();
    }


    /**
     * Returns all key value pairs
     */
    public static Map<String, ?> getAll(Context context) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, context.MODE_PRIVATE);
        Map<String, ?> map = sp.getAll();
        return map;
    }

    /**
     * Delete all data
     */
    public static void clear(Context context) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.clear();
        editor.commit();
    }

    /**
     * Check whether the data corresponding to the key exists
     */
    public static boolean contains(Context context, String key) {
        SharedPreferences sp = context.getSharedPreferences(FILE_NAME, context.MODE_PRIVATE);
        return sp.contains(key);
    }
}

5.2 if you have a data saving class, open the privacy interface code. After all, this rookie is not encapsulated, so you can directly use the privacy pop-up code. When using, you can encapsulate it yourself or throw it directly into the Activity class.

1.Since it is the first time to save data. Therefore, before calling privacy, you must get whether you agree to which privacy content.
 String isPrivacy = DataUtils.get(MainActivity.this,"privacy","0").toString();
 String isPolicy = DataUtils.get(MainActivity.this,"policy","0").toString();

2.If there are two privacy, you need to define a variable globally to ensure that the current one belongs to that privacy
 /**Type of privacy currently represented:
  * 1:Personal information privacy
  * 2:Terms of use
  * **/
  private int prviacyType = 1;
  
  Note: one is the user agreement record status, and the other is the privacy agreement record status. As for that, you can see mine yourself.
3.After getting the status, judge that the protocol interface pops up.
    //If you do not agree to the privacy treaty, the privacy treaty pops up
    if(isPrivacy.equals("1") && isPolicy.equals("1"))
    {
          //Agreed. Skip the privacy pop-up directly
    }else if(isPrivacy.equals("0"))
    {
          prviacyType = 1;
          showPrivacy("privacy.txt","Personal information privacy");
     }else if(isPrivacy.equals("1")&& isPolicy.equals("0"))
     {
          prviacyType = 2;
          showPrivacy("policy.txt","Terms of use");
     }
 4.When the front content is set, the pop-up privacy will be called, and the privacy content will be loaded and displayed according to the called privacy content.
    
    public void showPrivacy(String privacyFileName,String title)    {
        //Load the current private content text to display
        String str = initAssets(privacyFileName);
        
        //Layout ui interface information
        final View inflate = LayoutInflater.from(this).inflate(R.layout.activity_privacy_policy, null);
        TextView tv_title = (TextView) inflate.findViewById(R.id.tv_title);
        //Set private content header
        tv_title.setText(title);
        //To display private content, because the text layout needs to be beautiful, the content needs to use a newline character, but the loaded content can not really use a newline character. You can only use < br / > as a newline character in the text and replace it with \ n
        TextView tv_content = (TextView) inflate.findViewById(R.id.tv_content);
        tv_content.setText(str.replace("<br/>", "\n"));
        
        //Get consent and exit buttons and add events
        TextView btn_exit = (TextView) inflate.findViewById(R.id.btn_exit);
        TextView btn_enter = (TextView) inflate.findViewById(R.id.btn_enter);
        
        //Start to pop up the Privacy Interface
        final Dialog dialog = new AlertDialog
                .Builder(this)
                .setView(inflate)
                .show();
        //After the dialog box pops up, click or press the return key to not disappear
        dialog.setCancelable(false);

        WindowManager m = getWindowManager();
        Display defaultDisplay = m.getDefaultDisplay();
        final WindowManager.LayoutParams params = dialog.getWindow().getAttributes();
        params.width = (int) (defaultDisplay.getWidth() * 0.90);
        dialog.getWindow().setAttributes(params);
        dialog.getWindow().setBackgroundDrawableResource(android.R.color.transparent);

         //Exit button event
        btn_exit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                finish();
            }
        });
        //Agree button event
        btn_enter.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                dialog.dismiss();
                if(prviacyType == 1)
                {
                    prviacyType = 2;
                    //Save privacy consent status
                    DataUtils.put(MainActivity.this,"privacy","1");
                    //Show next private content
                    showPrivacy("policy.txt","Terms of use");
                }else if(prviacyType == 2)
                {
                    DataUtils.put(MainActivity.this,"policy","1");
                     //After both privacy contents are determined, proceed to the next step
                }

            }
        });
    }
    /**     
     * Read the data from the txt file under assets 
     */
    public String initAssets(String fileName) {
        String str = null;
        try {
            InputStream inputStream = getAssets().open(fileName);
            str = getString(inputStream);
        } catch (IOException e1) {
            e1.printStackTrace();
        }
        return str;
    }


    public static String getString(InputStream inputStream) {
        InputStreamReader inputStreamReader = null;
        try {
            inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
        } catch (UnsupportedEncodingException e1) {
            e1.printStackTrace();
        }
        BufferedReader reader = new BufferedReader(inputStreamReader);
        StringBuffer sb = new StringBuffer("");
        String line;
        try {
            while ((line = reader.readLine()) != null) {
                sb.append(line);
                sb.append("");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return sb.toString();
    }

end:

So far, the privacy pop-up has been handled. Private text content is not provided. Each of these is different. Specifically, it can be provided by the relevant personnel providing privacy.

Note: this rookie encountered a pit when doing it

        1. Text encoding problem. Therefore, the privacy is in txt text format, but the coding must be processed, or the privacy content read back is garbled.

        2. The interface size of the privacy pop-up window needs to be determined according to your actual situation. After all, it needs to be beautiful rather than full screen coverage. Therefore, we all know that although the beauty of technology is a piece of shit, we can make it look better if we can look better. At least I can see it myself.

Keywords: Java

Added by anthonyv on Mon, 20 Dec 2021 22:33:01 +0200