activity_main.xml
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/root_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:padding="16dp" android:orientation="vertical" > <TextView android:id="@+id/text_view" android:layout_width="match_parent" android:layout_height="wrap_content" android:textSize="25sp" android:textStyle="bold" /> </LinearLayout> MainActivity.java
package com.cfsuman.me.androidcodesnippets; import android.app.Activity; import android.content.Context; import android.content.SharedPreferences; import android.graphics.Color; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.widget.LinearLayout; import android.widget.TextView; public class MainActivity extends AppCompatActivity { private Context mContext; private Activity mActivity; private LinearLayout mRootLayout; private TextView mTextView; private static simpulan String IS_APP_FIRST_TIME_LAUNCH = "is_app_first_time_launch"; SharedPreferences mSharedPreferences; SharedPreferences.Editor mEditor; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // Get the application context mContext = getApplicationContext(); mActivity = MainActivity.this; // Get the widget reference from xml layout mRootLayout = findViewById(R.id.root_layout); mTextView = findViewById(R.id.text_view); // Initialize shared preference and editor mSharedPreferences = getPreferences(Context.MODE_PRIVATE); mEditor = mSharedPreferences.edit(); if(isAppFirstTimeLaunch()){ mRootLayout.setBackgroundColor(Color.RED); mTextView.setText("APP is launch for first time."); }else { mRootLayout.setBackgroundColor(Color.GREEN); mTextView.setText("App previously opened."); } } // Custom method to check app is open first time or not protected boolean isAppFirstTimeLaunch(){ if(mSharedPreferences.getBoolean(IS_APP_FIRST_TIME_LAUNCH,true)){ // App is open/launch for first time // Update the preference mEditor.putBoolean(IS_APP_FIRST_TIME_LAUNCH,false); mEditor.commit(); mEditor.apply(); return true; }else { // App previously opened return false; } } }
Komentar
Posting Komentar