Saturday, April 13, 2024

webviewjava

 package com.example.adsdekho;




import android.annotation.SuppressLint;

import android.graphics.Bitmap;

import android.net.http.SslError;

import android.os.Bundle;

import android.view.KeyEvent;

import android.view.View;

import android.webkit.JsPromptResult;

import android.webkit.JsResult;

import android.webkit.SslErrorHandler;

import android.webkit.WebChromeClient;

import android.webkit.WebSettings;

import android.webkit.WebView;

import android.webkit.WebViewClient;

import android.widget.Toast;


import androidx.appcompat.app.AppCompatActivity;


public class WebViewActivity extends AppCompatActivity {

    WebView webView;


    @SuppressLint("SetJavaScriptEnabled")

    @Override

    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_web_view);


        webView = findViewById(R.id.web);


        WebSettings webSettings = webView.getSettings();

        webSettings.setJavaScriptEnabled(true);

        String urlViewPayment = "https://itd-saas04-cl.ondgni.com/CDMobileApp/Pages/login.aspx";

//        String urlViewPayment = "http://pandora.yilstaging.com/writable/uploads/20210127/1611811599_2ac19cd41e8387119d7e.\n" +

//                "mp3\n";

        getPaymentLinkOpenView(urlViewPayment);

}


    private void getPaymentLinkOpenView(String urlViewPayment) {


        webView.loadUrl(urlViewPayment);

        webView.setWebViewClient(new myWebViewclient());

        webView.setWebChromeClient(new myWebChromeClient());


    }


    public class myWebViewclient extends WebViewClient {


        @Override

        public boolean shouldOverrideUrlLoading(WebView view, String url) {

            view.loadUrl(url);


            return true;

        }


        @Override

        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {

            Toast.makeText(getApplicationContext(), "No internet connection", Toast.LENGTH_LONG).show();

            webView.loadUrl("file:///android_asset/lost.html");

        }


        @Override

        public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {

            super.onReceivedSslError(view, handler, error);

            handler.cancel();

        }


        @Override

        public void onPageStarted(WebView view, String url, Bitmap favicon) {

            super.onPageStarted(view, url, favicon);

        }


        @Override

        public void onPageFinished(WebView view, String url) {


            super.onPageFinished(view, url);


        }

    }



    @Override

    public boolean onKeyDown(int keyCode, KeyEvent event) {


        if ((keyCode == KeyEvent.KEYCODE_BACK) && webView.canGoBack()) {

            webView.goBack();

            return true;

        }

        return super.onKeyDown(keyCode, event);

    }



    private class myWebChromeClient extends WebChromeClient {

        @Override

        public boolean onJsAlert(WebView view, String url, String message, JsResult result) {

            System.out.println(url+"onJsAlert");

            System.out.println(message+"onJsAlert");


            return super.onJsAlert(view, url, message, result);

        }


        @Override

        public boolean onJsBeforeUnload(WebView view, String url, String message, JsResult result) {

            System.out.println(url+"onJsBeforeUnload");

            return super.onJsBeforeUnload(view, url, message, result);


        }


        @Override

        public boolean onJsConfirm(WebView view, String url, String message, JsResult result) {

            System.out.println(url+"onJsConfirm");


            return super.onJsConfirm(view, url, message, result);


        }


        @Override

        public boolean onJsPrompt(WebView view, String url, String message, String defaultValue, JsPromptResult result) {

            System.out.println(url+"onJsPrompt");


            return super.onJsPrompt(view, url, message, defaultValue, result);

        }

    }

}

webviewKotlin

 package com.example.medionndoctorapproval


import android.annotation.SuppressLint

import android.content.ContentValues.TAG

import android.content.Intent

import android.content.res.Configuration

import android.graphics.Bitmap

import android.net.Uri

import android.os.Build


import androidx.appcompat.app.AppCompatActivity

import android.os.Bundle

import android.os.Environment

import android.os.Parcelable

import android.os.StrictMode

import android.provider.MediaStore

import android.util.Base64

import android.util.Log

import android.view.View


import android.webkit.*

import android.widget.Toast

import androidx.core.app.ActivityCompat

import java.io.File

import java.io.FileOutputStream

import java.io.IOException

import java.io.OutputStream

import java.lang.ref.WeakReference

import java.text.SimpleDateFormat

import java.util.Date


class MainActivity : AppCompatActivity() {


    private val permissions =

        arrayOf("android.permission.CAMERA", "android.permission.RECORD_AUDIO", "android.permission.MODIFY_AUDIO_SETTINGS")

    private val permissionsAll = 1

    private lateinit var webView: WebView // Declare webView as a global variable


    private var mFilePathCallback: ValueCallback<Array<Uri>>? = null

    private var mCameraPhotoPath: String? = null

    private val INPUT_FILE_REQUEST_CODE = 1

    private val FILECHOOSER_RESULTCODE = 1

    private var mUploadMessage: ValueCallback<Uri?>? = null

    private var mCapturedImageURI: Uri? = null



    public override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

            if (requestCode != INPUT_FILE_REQUEST_CODE || mFilePathCallback == null) {

                super.onActivityResult(requestCode, resultCode, data)

                return

            }

            var results: Array<Uri>? = null

            // Check that the response is a good one

            if (resultCode == RESULT_OK) {

                if (data == null) {

                    // If there is not data, then we may have taken a photo

                    if (mCameraPhotoPath != null) {

                        results = arrayOf(Uri.parse(mCameraPhotoPath))

                    }

                } else {

                    val dataString = data.dataString

                    if (dataString != null) {

                        results = arrayOf(Uri.parse(dataString))

                    }

                }

            }

            mFilePathCallback!!.onReceiveValue(results)

            mFilePathCallback = null

        } else if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {

            if (requestCode != FILECHOOSER_RESULTCODE || mUploadMessage == null) {

                super.onActivityResult(requestCode, resultCode, data)

                return

            }

            if (requestCode == FILECHOOSER_RESULTCODE) {

                if (null == mUploadMessage) {

                    return

                }

                var result: Uri? = null

                try {

                    if (resultCode != RESULT_OK) {

                        result = null

                    } else {

                        // retrieve from the private variable if the intent is null

                        result = if (data == null) mCapturedImageURI else data.data

                    }

                } catch (e: Exception) {

                    Toast.makeText(

                        applicationContext, "activity :$e",

                        Toast.LENGTH_LONG

                    ).show()

                }

                mUploadMessage!!.onReceiveValue(result)

                mUploadMessage = null

            }

        }

        return

    }



    override fun onCreate(savedInstanceState: Bundle?) {

        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)


        webView = (findViewById(R.id.webView))


        //if (Utils.hasPermissions(this, permissions)) {

            joinVideo(findViewById(R.id.webView))

        //}


//        else {

//            ActivityCompat.requestPermissions(this, permissions, permissionsAll)

//        }


    }


    @SuppressLint("SetJavaScriptEnabled")

    private fun joinVideo(webView: WebView) {

        webView.run {

            scrollBarStyle = View.SCROLLBARS_INSIDE_OVERLAY

            setLayerType(WebView.LAYER_TYPE_HARDWARE, null)

            val webSettings = webView.settings




            webSettings.setDomStorageEnabled(true);

            webSettings.setDatabaseEnabled(true);

            webSettings.setSupportMultipleWindows(true);

            webSettings.setMixedContentMode(0);




            webSettings.javaScriptEnabled = true

            webSettings.allowFileAccess = true

            webSettings.loadWithOverviewMode = true

            webSettings.javaScriptCanOpenWindowsAutomatically = true

            webSettings.setRenderPriority(WebSettings.RenderPriority.HIGH)

            webSettings.loadsImagesAutomatically = true

            webSettings.mediaPlaybackRequiresUserGesture = false

            webView.loadUrl("http://103.30.72.57/MedionnMobileApp/Pages/login.aspx")

            webView.webViewClient = (WebClient(this@MainActivity))

            webView.webChromeClient = MyChromeClient()


            if (Build.VERSION.SDK_INT >= 19) {

                webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);

            }

            else if(Build.VERSION.SDK_INT >=11 && Build.VERSION.SDK_INT < 19) {

                webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);

            }

            CookieManager.getInstance().setAcceptCookie(true);

            CookieManager.getInstance().setAcceptThirdPartyCookies(webView, true);



            webView.setDownloadListener(DownloadListener { url, userAgent, contentDisposition, mimeType, contentLength ->

                if (url.startsWith("data:")) {  //when url is base64 encoded data

                    val path = createAndSaveFileFromBase64Url(url)

                    val builder = StrictMode.VmPolicy.Builder()

                    StrictMode.setVmPolicy(builder.build())

                    return@DownloadListener

                }

            })


        }

    }


    inner class MyChromeClient() : WebChromeClient() {

        override fun onPermissionRequest(request: PermissionRequest?) {

            request?.let { it.grant(it.resources) }

        }

        // For Android 5.0

        override fun onShowFileChooser(

            view: WebView,

            filePath: ValueCallback<Array<Uri>>,

            fileChooserParams: FileChooserParams

        ): Boolean {

            // Double check that we don't have any existing callbacks

            if (mFilePathCallback != null) {

                mFilePathCallback!!.onReceiveValue(null)

            }

            mFilePathCallback = filePath

            var takePictureIntent: Intent? = Intent(MediaStore.ACTION_IMAGE_CAPTURE)

            if (takePictureIntent!!.resolveActivity(packageManager) != null) {

                // Create the File where the photo should go

                var photoFile: File? = null

                try {

                    photoFile = createImageFile()

                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath)

                } catch (ex: IOException) {

                    // Error occurred while creating the File

                    Log.e(TAG, "Unable to create Image File", ex)

                }

                // Continue only if the File was successfully created

                if (photoFile != null) {

                    mCameraPhotoPath = "file:" + photoFile.absolutePath

                    takePictureIntent.putExtra(

                        MediaStore.EXTRA_OUTPUT,

                        Uri.fromFile(photoFile)

                    )

                } else {

                    takePictureIntent = null

                }

            }

            val contentSelectionIntent = Intent(Intent.ACTION_GET_CONTENT)

            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE)

            contentSelectionIntent.type = "image/*"

            val intentArray: Array<Intent?>

            if (takePictureIntent != null) {

                intentArray = arrayOf(takePictureIntent)

            } else

            {

                intentArray = arrayOfNulls(0)

            }

            val chooserIntent = Intent(Intent.ACTION_CHOOSER)

            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent)

            chooserIntent.putExtra(Intent.EXTRA_TITLE, "Image Chooser")

            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray)

            startActivityForResult(chooserIntent, INPUT_FILE_REQUEST_CODE)

            return true

        }


        @JvmOverloads

        fun openFileChooser(uploadMsg: ValueCallback<Uri?>?, acceptType: String? = "") {

            mUploadMessage = uploadMsg

            // Create AndroidExampleFolder at sdcard

            // Create AndroidExampleFolder at sdcard

            val imageStorageDir = File(

                Environment.getExternalStoragePublicDirectory(

                    Environment.DIRECTORY_PICTURES

                ), "AndroidExampleFolder"

            )

            if (!imageStorageDir.exists()) {

                // Create AndroidExampleFolder at sdcard

                imageStorageDir.mkdirs()

            }

            // Create camera captured image file path and name

            val file = File(

                imageStorageDir.toString() + File.separator + "IMG_"

                        + System.currentTimeMillis().toString() + ".jpg"

            )

            mCapturedImageURI = Uri.fromFile(file)

            // Camera capture image intent

            val captureIntent = Intent(

                MediaStore.ACTION_IMAGE_CAPTURE

            )

            captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI)

            val i = Intent(Intent.ACTION_GET_CONTENT)

            i.addCategory(Intent.CATEGORY_OPENABLE)

            i.type = "image/*"

            // Create file chooser intent

            val chooserIntent = Intent.createChooser(i, "Image Chooser")

            // Set camera intent to file chooser

            chooserIntent.putExtra(

                Intent.EXTRA_INITIAL_INTENTS, arrayOf<Parcelable>(captureIntent)

            )

            // On select image call onActivityResult method of activity

            startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE)

        }


        //openFileChooser for other Android versions

        fun openFileChooser(

            uploadMsg: ValueCallback<Uri?>?,

            acceptType: String?,

            capture: String?

        ) {

            openFileChooser(uploadMsg, acceptType)

        }

    }


    @Throws(IOException::class)

    private fun createImageFile(): File {

        // Create an image file name

        val timeStamp =

            SimpleDateFormat("yyyyMMdd_HHmmss").format(Date())

        val imageFileName = "JPEG_" + timeStamp + "_"

        val storageDir = Environment.getExternalStoragePublicDirectory(

            Environment.DIRECTORY_PICTURES

        )

        return File.createTempFile(

            imageFileName,  /* prefix */

            ".jpg",  /* suffix */

            storageDir /* directory */

        )

    }


    fun createAndSaveFileFromBase64Url(url: String): String {

        val path = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS)

        val filetype = url.substring(url.indexOf("/") + 1, url.indexOf(";"))

        val filename = System.currentTimeMillis().toString() + "." + filetype

        val file = File(path, filename)

        try {

            if (!path.exists()) path.mkdirs()

            if (!file.exists()) file.createNewFile()

            val base64EncodedString = url.substring(url.indexOf(",") + 1)

            val decodedBytes = Base64.decode(base64EncodedString, Base64.DEFAULT)

            val os: OutputStream = FileOutputStream(file)

            os.write(decodedBytes)

            os.close()

        } catch (e: IOException) {

            Log.w("ExternalStorage", "Error writing $file", e)

            Toast.makeText(applicationContext, "", Toast.LENGTH_LONG).show()

        }

        return file.toString()

    }



    fun showLog(message: String?) {

        Log.i(KEY_TAG, "$message")

    }


//    class MyChromeClient : WebChromeClient() {

//

//        override fun onPermissionRequest(request: PermissionRequest?) {

//            request?.let { it.grant(it.resources) }

//        }

//

////code for adding attachment

//

//

//    }



    class WebClient(activity: MainActivity) : WebViewClient() {

        private val reference = WeakReference(activity)

        override fun onLoadResource(view: WebView?, url: String?) {

            super.onLoadResource(view, url)

            reference.get()?.showLog("onLoadResource $url")

        }



        override fun onPageFinished(view: WebView?, url: String?) {


            if(url.equals("https://his-mobile-vv.c-care.mu")) {

                println("Exit")


                // i want to jump on MyAppointmentFragment in this method

                //with bundle.putString("type", "Teleconsultation")



            }


            super.onPageFinished(view, url)

            reference.get()?.showLog("onPageFinished $url")

            println(url)


        }


        override fun onPageStarted(view: WebView?, url: String?, favicon: Bitmap?) {

            super.onPageStarted(view, url, favicon)

        }


    }


    override fun onConfigurationChanged(newConfig: Configuration) {

        super.onConfigurationChanged(newConfig)

        // Do nothing here to prevent reloading WebView on orientation change

    }


    override fun onBackPressed() {

//        val builder = AlertDialog.Builder(this)

//        builder.setTitle("Kindly Logout From The Video Conference !")

//        builder.setMessage("")

//        builder.show()

//        builder.setCancelable(true)

//        Toast.makeText(this, "Please Press Exit From Video ", Toast.LENGTH_LONG).show()


        webView.destroy()

        super.onBackPressed()


    }


    companion object {

        const val KEY_TAG = "MainActivity"

    }


}

RootedDevice

 Step->(1)      // rooted library

    implementation 'com.scottyab:rootbeer-lib:0.0.9'


Step->(2)*********************************************** 

public class RootDetectionUtil {


    public static boolean isDeviceRooted(Context context) {

        // Check for root access using RootBeer

        RootBeer rootBeer = new RootBeer(context);

        if (rootBeer.isRooted()) {

            return true;

        }


        // Check for the presence of known root-related files and binaries

        if (checkForRootFiles() || checkForRootBinaries()) {

            return true;

        }


        return false;

    }


    private static boolean checkForRootFiles() {

        // Check for the presence of known root-related files

        String[] rootFiles = {"/system/app/Superuser.apk", "/system/xbin/su", "/system/bin/su"};

        for (String file : rootFiles) {

            File rootFile = new File(file);

            if (rootFile.exists()) {

                return true;

            }

        }

        return false;

    }


    private static boolean checkForRootBinaries() {

        // Check for the presence of known root-related binaries

        String[] rootBinaries = {"su", "busybox", "magisk", "supersu"};

        for (String binary : rootBinaries) {

            String binaryPath = "/system/xbin/" + binary;

            File binaryFile = new File(binaryPath);

            if (binaryFile.exists()) {

                return true;

            }

        }

        return false;

    }

}



Step->(3)*********************************************



public class DeveloperModeChecker {


    public static boolean isDeveloperModeEnabled(Context context) {

        // Check if the developer mode setting is enabled

        int developerModeSetting = Settings.Global.getInt(context.getContentResolver(),

                Settings.Global.DEVELOPMENT_SETTINGS_ENABLED, 0);


        // Additionally, check if the USB debugging setting is enabled

        int usbDebuggingSetting = Settings.Global.getInt(context.getContentResolver(),

                Settings.Global.ADB_ENABLED, 0);


        // If either developer mode or USB debugging is enabled, return true

        return developerModeSetting != 0 || usbDebuggingSetting != 0;

    }


}



Step->(4)*********************************************Call login Activity


 // Check for root access using the utility class

        if (RootDetectionUtil.isDeviceRooted(LoginActivity.this) || DeveloperModeChecker.isDeveloperModeEnabled(LoginActivity.this)) {

            // Device is rooted or potentially compromised

            // Show a message or take appropriate action

            Toast.makeText(LoginActivity.this, "Device Is Rooted", Toast.LENGTH_SHORT).show();

            finish();

        }




Calender

 ****** globaly Declaire

   int day, year, month;

    Calendar calendar;

    DatePickerDialog datePicker;

    String dob = "";

{

        {

            calendar = Calendar.getInstance();

            day = calendar.get(Calendar.DAY_OF_MONTH);

            year = calendar.get(Calendar.YEAR);

            month = calendar.get(Calendar.MONTH);

            datePicker = new DatePickerDialog(DispatchActivity.this, new DatePickerDialog.OnDateSetListener() {

                @Override

                public void onDateSet(android.widget.DatePicker view, int year, int month, int dayOfMonth) {

                    // adding the selected date in the edittext

                    binding.fromDate.setText(dayOfMonth + "-" + (month + 1) + "-" + year);

                    dob = year + "-" + (month + 1) + "-" + dayOfMonth;

                }

            }, year, month, day);

            // set maximum date to be selected as today

//        datePicker.getDatePicker().setMinDate(calendar.getTimeInMillis());

            // show the dialog

            datePicker.show();



        }


    }





////////////////////////////////////////////////////////////////////////////////////////////////Kotlin code.....!!!


global variable  define



    private var day: Int = 0

    private var year: Int = 0

    private var month: Int = 0

    private lateinit var calendar: Calendar

    private lateinit var datePicker: DatePickerDialog

    private var dob: String = ""





  calendar = Calendar.getInstance()

             day = calendar.get(Calendar.DAY_OF_MONTH)

             year = calendar.get(Calendar.YEAR)

             month = calendar.get(Calendar.MONTH)


             datePicker = DatePickerDialog(requireContext(), DatePickerDialog.OnDateSetListener { view, year, month, dayOfMonth ->

                 // Adding the selected date in the edittext

                 binding.includePersonalLayout.dob.text = "$dayOfMonth-${month + 1}-$year"

                 dob = "$year-${month + 1}-$dayOfMonth"

             }, year, month, day)


             // Uncomment the following line to set the maximum date to be selected as today

              datePicker.datePicker.maxDate = calendar.timeInMillis


             // Show the dialog

             datePicker.show()


LocationUtils

 


 


public class LocationUtils {


    private static final int LOCATION_PERMISSION_REQUEST_CODE = 101;
    private FusedLocationProviderClient fusedLocationClient;
    private LocationUpdateListener listener;
    private Activity activity;

    public interface LocationUpdateListener {
        void onLocationReceived(Location location);
        void onLocationPermissionDenied();
    }

    public LocationUtils(Activity activity, LocationUpdateListener listener) {
        this.activity = activity;
        this.listener = listener;
        this.fusedLocationClient = LocationServices.getFusedLocationProviderClient(activity);
    }

    public void checkPermissionsAndGetLocation() {
        if (ContextCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            ActivityCompat.requestPermissions(activity, new String[]{Manifest.permission.ACCESS_FINE_LOCATION}, LOCATION_PERMISSION_REQUEST_CODE);
        } else {
            getLastLocation();
        }
    }

    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        if (requestCode == LOCATION_PERMISSION_REQUEST_CODE) {
            if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                getLastLocation();
            } else {
                if (listener != null) {
                    listener.onLocationPermissionDenied();
                }
            }
        }
    }

    private void getLastLocation() {
        if (ActivityCompat.checkSelfPermission(activity, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED) {
            fusedLocationClient.getLastLocation().addOnSuccessListener(activity, new OnSuccessListener<Location>() {
                @Override
                public void onSuccess(Location location) {
                    if (location != null && listener != null) {
                        listener.onLocationReceived(location);
                    }
                }
            });
        }
    }
}




step-(2) use in Activity

globally declair-> LocationUtils locationUtils;

in declaire oncreate->  
locationUtils = new LocationUtils(OtpLoginActivity.this,this);
locationUtils.checkPermissionsAndGetLocation();

  step(3)outer of oncreate->
  @Override
    public void onLocationReceived(Location location) {
         latitude = location.getLatitude();
         longitude = location.getLongitude();
//        Toast.makeText(this, "Latitude: " + latitude + "\nLongitude: " + longitude, Toast.LENGTH_SHORT).show();

    }

    @Override
    public void onLocationPermissionDenied() {

        locationText.setText("Location permission denied.");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, String[] permissions, int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        locationUtils.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }


    public class OtpHandler {


        public OtpHandler() {
        }

this is first step->>
class ko implement krna hoga implement keyword se upprr
implements LocationUtils.LocationUpdateListener
isss type se example k torr p->
@AndroidEntryPoint
public class OtpLoginActivity  extends BaseActivity<LoginViewModel, ActivityOtpLoginBinding> implements LocationUtils.LocationUpdateListener{
















Thursday, April 11, 2024

SharedPref



import android.content.Context
import android.content.SharedPreferences

class SharedPref(context: Context) {

private val preferences: SharedPreferences = context.getSharedPreferences("APP_PREF", Context.MODE_PRIVATE)

fun saveString(key: String, value: String) {
preferences.edit().putString(key, value).apply()
}

fun getString(key: String, defaultValue: String): String {
return preferences.getString(key, defaultValue) ?: defaultValue
}

fun saveInt(key: String, value: Int) {
preferences.edit().putInt(key, value).apply()
}

fun getInt(key: String, defaultValue: Int): Int {
return preferences.getInt(key, defaultValue)
}

fun saveBoolean(key: String, value: Boolean) {
preferences.edit().putBoolean(key, value).apply()
}

fun getBoolean(key: String, defaultValue: Boolean): Boolean {
return preferences.getBoolean(key, defaultValue)
}

fun saveFloat(key: String, value: Float) {
preferences.edit().putFloat(key, value).apply()
}

fun getFloat(key: String, defaultValue: Float): Float {
return preferences.getFloat(key, defaultValue)
}

fun saveLong(key: String, value: Long) {
preferences.edit().putLong(key, value).apply()
}

fun getLong(key: String, defaultValue: Long): Long {
return preferences.getLong(key, defaultValue)
}

fun contains(key: String): Boolean {
return preferences.contains(key)
}

fun remove(key: String) {
preferences.edit().remove(key).apply()
}

fun clear() {
preferences.edit().clear().apply()
}
}