<|start_filename|>app/src/main/java/com/showlin/simpleQRCode/ShowApplication.kt<|end_filename|>
package com.showlin.simpleQRCode


import android.app.Application

class ShowApplication : Application() {
    override fun onCreate() {
        super.onCreate()
    }
}


<|start_filename|>app/src/main/java/com/showlin/simpleQRCode/activity/ResultActivity.kt<|end_filename|>
package com.showlin.simpleQRCode.activity

import android.content.Context
import android.content.Intent
import android.net.Uri
import android.net.wifi.WifiConfiguration
import android.net.wifi.WifiManager
import android.os.Bundle
import android.support.v7.app.AlertDialog
import android.util.ArrayMap
import android.view.MenuItem
import android.view.View
import com.showlin.simpleQRCode.R
import com.showlin.simpleQRCode.Utility.KEY_RESULT
import kotlinx.android.synthetic.main.activity_result.*


class ResultActivity : BaseActivity() {

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_result)

        val bundle = intent.extras

        supportActionBar!!.title = getString(R.string.result)
        supportActionBar!!.setDisplayHomeAsUpEnabled(true)

        pareInfo(bundle.getString(KEY_RESULT))
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            finish()
            return true
        }
        return super.onOptionsItemSelected(item)
    }

    private fun pareInfo(resultString: String){
        when {
            resultString.indexOf("WIFI:") == 0 -> // WIFI
                getWIFI(resultString)
            resultString.indexOf("http") == 0 -> // Website
                getWebsite(resultString)
            resultString.indexOf("smsto:") == 0 -> //SMS
                getSMS(resultString)
            resultString.indexOf("geo:") == 0 -> //GEO
                getGEO(resultString)
            resultString.indexOf("tel:") == 0 -> //TEL
                getTEL(resultString)
            resultString.indexOf("mailto:") == 0 -> //MAIL
                getMail(resultString)
//            resultString.indexOf("MECARD:") == 0 -> {
//                //MECARD
//            }
//            resultString.indexOf("BEGIN:VCARD") == 0 -> //VCARD
//                getVcard()
//            resultString.indexOf("BEGIN:VEVENT") == 0 -> {
//                //VEVENT
//            }
            else -> //TEXT
                getTextType(resultString)
        }
    }

    private fun getWIFI(stringResult : String){
        ll_wifi.visibility = View.VISIBLE
        text_wifi_string.text = stringResult

        val subString = stringResult.substring(5)
        val strings = subString.split(";".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()
        val map = ArrayMap<String, String>()
        strings.indices
                .map { i -> strings[i].split(":".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray() }
                .forEach { map[it[0]] = it[1] }
        btn_wifi.setOnClickListener {
            val alertDialog = AlertDialog.Builder(this)
                    .setTitle(getString(R.string.hi))
                    .setMessage(String.format(getString(R.string.wifi_connect), map["S"]))
                    .setNeutralButton(getString(R.string.ok), { dialog, _ ->
                        val wifiManager = applicationContext.getSystemService(Context.WIFI_SERVICE) as WifiManager
                        val configuration = WifiConfiguration()
                        configuration.SSID = "\"" + map["S"] + "\""
                        configuration.status = WifiConfiguration.Status.ENABLED

                        if (map.containsKey("T")) {
                            if (map["T"].equals("WPA")) {
                                configuration.preSharedKey = "\"" + map["P"] + "\""
                                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK)
                                configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP)
                                configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP)
                                configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.TKIP)
                                configuration.allowedPairwiseCiphers.set(WifiConfiguration.PairwiseCipher.CCMP)
                                configuration.allowedProtocols.set(WifiConfiguration.Protocol.RSN)
                                configuration.allowedProtocols.set(WifiConfiguration.Protocol.WPA)
                            } else if (map["T"].equals("WEP")) {
                                configuration.wepKeys[0] = "\"" + map["P"] + "\""
                                configuration.wepTxKeyIndex = 0
                                configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE)
                                configuration.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40)
                            }
                        } else {
                            configuration.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE)
                        }

                        val netID = wifiManager.addNetwork(configuration)
                        wifiManager.enableNetwork(netID, true)
                        wifiManager.reconnect()

                        dialog.dismiss()
                    })
                    .setPositiveButton(getString(R.string.cancel), { dialog, _ -> dialog.dismiss() })
                    .create()
            alertDialog.show()
        }
    }

    private fun getWebsite(resultString: String) {
        ll_url.visibility = View.VISIBLE
        text_url_string.text = resultString
        btn_url.setOnClickListener {
            val intent = Intent()
            intent.action = Intent.ACTION_VIEW
            intent.data = Uri.parse(resultString)
            startActivity(intent)
        }
    }

    private fun getSMS(resultString: String) {
        ll_sms.visibility = View.VISIBLE
        text_sms_string.text = resultString
        val strResult = resultString.split(":".toRegex()).dropLastWhile({ it.isEmpty() }).toTypedArray()

        btn_sms.setOnClickListener {
            val uri = Uri.fromParts("sms", strResult[1], null)
            val intent = Intent(Intent.ACTION_SENDTO, uri)
            intent.putExtra("sms_body", strResult[2])
            startActivity(intent)
        }
    }

    private fun getGEO(resultString: String) {
        ll_geo.visibility = View.VISIBLE
        text_geo_string.text = resultString
        btn_geo.setOnClickListener {
            val uri = Uri.parse(resultString)
            val intent = Intent(Intent.ACTION_VIEW, uri)
            startActivity(intent)
        }
    }

    private fun getTEL(resultString: String) {
        ll_tel.visibility = View.VISIBLE
        text_tel_string.text = resultString
        btn_tel.setOnClickListener {
            val uri = Uri.parse(resultString)
            val intent = Intent(Intent.ACTION_DIAL)
            intent.data = uri
            startActivity(intent)
        }
    }

    private fun getMail(resultString: String) {
        ll_email.visibility = View.VISIBLE
        text_email_string.text = resultString

        btn_email.setOnClickListener {
            val intent = Intent(Intent.ACTION_SENDTO)
            intent.data = Uri.parse(resultString)
            startActivity(intent)
        }
    }

    private fun getTextType(resultString: String) {
        ll_text.visibility = View.VISIBLE
        text_text_string.text = resultString
    }

    private fun getVcard() {
//        var contentProviderOperation = ContentProviderOperation.newInsert(Content)
    }



}


<|start_filename|>app/src/main/java/com/showlin/simpleQRCode/activity/ScanActivity.kt<|end_filename|>
package com.showlin.simpleQRCode.activity

import android.app.Activity
import android.app.Service
import android.content.Intent
import android.os.Build
import android.os.Bundle
import android.os.Vibrator
import android.support.v4.content.ContextCompat
import android.view.View
import android.view.WindowManager
import com.google.zxing.ResultPoint
import com.journeyapps.barcodescanner.BarcodeCallback
import com.journeyapps.barcodescanner.BarcodeResult
import com.showlin.simpleQRCode.R
import com.showlin.simpleQRCode.Utility.KEY_RESULT
import kotlinx.android.synthetic.main.activity_scan.*


class ScanActivity : Activity(){
    private var isTorch = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val window = this.window
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.statusBarColor = ContextCompat.getColor(this, android.R.color.transparent)
        }

        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN

        setContentView(R.layout.activity_scan)
        barcode_view.decodeContinuous(callback)

        img_flash.setOnClickListener {
            if (isTorch){
                isTorch = false
                img_flash.setImageResource(R.drawable.flash_off)
            }else{
                isTorch = true
                img_flash.setImageResource(R.drawable.flash_on)
            }
            barcode_view.setTorch(isTorch)
        }
    }

    override fun onResume() {
        barcode_view.resume()
        super.onResume()
    }

    override fun onPause() {
        barcode_view.pause()
        super.onPause()
    }

    private val callback = object : BarcodeCallback{
        override fun possibleResultPoints(resultPoints: MutableList<ResultPoint>?) {

        }

        override fun barcodeResult(result: BarcodeResult?) {
            if (result!!.text != null){
                val intent = Intent()
                val bundle = Bundle()
                bundle.putString(KEY_RESULT, result.text.toString())
                intent.putExtras(bundle)
                setResult(Activity.RESULT_OK, intent)
                val vibrator = application.getSystemService(Service.VIBRATOR_SERVICE) as Vibrator
                vibrator.vibrate(100)
                finish()
            }
        }

    }
}


<|start_filename|>app/src/main/java/com/showlin/simpleQRCode/activity/BaseActivity.kt<|end_filename|>
package com.showlin.simpleQRCode.activity

import android.os.Build
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.view.WindowManager
import com.showlin.simpleQRCode.R

open class BaseActivity : AppCompatActivity(){
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        val window = this.window
        window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS)
            window.statusBarColor = ContextCompat.getColor(this, R.color.colorPrimary)
        }
        window.decorView.systemUiVisibility = View.SYSTEM_UI_FLAG_LAYOUT_STABLE or View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
    }
}

<|start_filename|>app/src/main/java/com/showlin/simpleQRCode/activity/TypeGenerateActivity.kt<|end_filename|>
package com.showlin.simpleQRCode.activity

import android.app.Dialog
import android.content.Context
import android.content.Intent
import android.content.res.ColorStateList
import android.graphics.drawable.StateListDrawable
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.LayoutInflater
import android.view.MenuItem
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import com.showlin.simpleQRCode.R
import com.showlin.simpleQRCode.Utility.KEY_CONTENT
import com.showlin.simpleQRCode.Utility.REQUEST_CODE
import kotlinx.android.synthetic.main.activity_type_generate.*
import kotlinx.android.synthetic.main.dialog_geo.*
import kotlinx.android.synthetic.main.dialog_mail.*
import kotlinx.android.synthetic.main.dialog_sms.*
import kotlinx.android.synthetic.main.dialog_tel.*
import kotlinx.android.synthetic.main.dialog_web.*
import kotlinx.android.synthetic.main.dialog_wifi.*


class TypeGenerateActivity : BaseActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_type_generate)

        supportActionBar!!.title = getString(R.string.type_generate)
        supportActionBar!!.setDisplayHomeAsUpEnabled(true)

        recycle_view.setHasFixedSize(true)
        recycle_view.layoutManager = GridLayoutManager(this, 3)
        recycle_view.adapter = TypeAdapter(this)
    }


    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            finish()
            return true
        }
        return super.onOptionsItemSelected(item)
    }


    fun sendResult(strResult : String){
        val intent = Intent()
        intent.putExtra(KEY_CONTENT, strResult)
        setResult(REQUEST_CODE, intent)
    }
}

class TypeAdapter(private val activity: TypeGenerateActivity) : RecyclerView.Adapter<TypeHolder>() {

    private val mTypeNameArray = intArrayOf(R.string.wifi, R.string.website, R.string.sms, R.string.geo, R.string.tel, R.string.mail, R.string.mecard, R.string.vcard, R.string.vevent)
    private val mTypeArray = intArrayOf(R.drawable.img_wifi, R.drawable.img_url, R.drawable.img_sms, R.drawable.img_geo, R.drawable.img_tel, R.drawable.img_mail, R.drawable.img_contactor, R.drawable.img_contactor, R.drawable.img_calendar)
    private val mTypePressArray = intArrayOf(R.drawable.img_wifi_press, R.drawable.img_url_press, R.drawable.img_sms_press, R.drawable.img_geo_press, R.drawable.img_tel_press, R.drawable.img_mail_press, R.drawable.img_contactor_press, R.drawable.img_contactor_press, R.drawable.img_calendar_press)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): TypeHolder {
        val view = LayoutInflater.from(parent.context).inflate(R.layout.item_type, parent, false)

        return TypeHolder(view)
    }

    override fun onBindViewHolder(holder: TypeHolder, position: Int) {
        setClickStatusImg(activity, mTypeArray[position], mTypePressArray[position], holder.imgLogo)
        setClickStatusTxt(activity, R.color.colorWhite, R.color.color2, holder.textTypeName)
        holder.textTypeName.setText(mTypeNameArray[position])


        holder.llGroup.setOnClickListener {
            when (position) {
                TYPE_WIFI -> {
                    val dialog = Dialog(activity)
                    dialog.setContentView(R.layout.dialog_wifi)
                    dialog.setCancelable(false)
                    dialog.group_radio.check(dialog.type_none.id)
                    dialog.show()
                    dialog.text_dialog_generate.setOnClickListener {
                        val strWifi = generateWifiString(dialog.edit_ssid.text.toString(), dialog.edit_password.text.toString(), dialog.group_radio.checkedRadioButtonId, dialog.check_box.isChecked, dialog)
                        activity.sendResult(strWifi)
                        activity.finish()
                        dialog.dismiss()
                    }
                    dialog.text_dialog_cancel.setOnClickListener {
                        dialog.dismiss()
                    }
                }
                TYPE_WEBSITE -> {
                    val dialog = Dialog(activity)
                    dialog.setCancelable(false)
                    dialog.setContentView(R.layout.dialog_web)
                    dialog.show()
                    dialog.text_dialog_generate_url.setOnClickListener {
                        val strURL = generateURLString(dialog.edit_url.text.toString())
                        activity.sendResult(strURL)
                        activity.finish()
                        dialog.dismiss()
                    }
                    dialog.text_dialog_cancel_url.setOnClickListener {
                        dialog.dismiss()
                    }
                }
                TYPE_SMS -> {
                    val dialog = Dialog(activity)
                    dialog.setCancelable(false)
                    dialog.setContentView(R.layout.dialog_sms)
                    dialog.show()
                    dialog.text_dialog_generate_sms.setOnClickListener {
                        val strURL = generateSMSString(dialog.edit_sms_tel.text.toString(), dialog.edit_sms_message.text.toString())
                        activity.sendResult(strURL)
                        activity.finish()
                        dialog.dismiss()
                    }
                    dialog.text_dialog_cancel_sms.setOnClickListener {
                        dialog.dismiss()
                    }
                }
                TYPE_GEO -> {
                    val dialog = Dialog(activity)
                    dialog.setCancelable(false)
                    dialog.setContentView(R.layout.dialog_geo)
                    dialog.show()
                    dialog.text_dialog_generate_geo.setOnClickListener {
                        val strURL = generateGEOString(dialog.edit_geo_latitude.text.toString(), dialog.edit_geo_longitude.text.toString(), dialog.edit_geo_query.text.toString())
                        activity.sendResult(strURL)
                        activity.finish()
                        dialog.dismiss()
                    }
                    dialog.text_dialog_cancel_geo.setOnClickListener {
                        dialog.dismiss()
                    }
                }
                TYPE_TEL -> {
                    val dialog = Dialog(activity)
                    dialog.setCancelable(false)
                    dialog.setContentView(R.layout.dialog_tel)
                    dialog.show()
                    dialog.text_dialog_generate_tel.setOnClickListener {
                        val strURL = generateTELString(dialog.edit_tel_number.text.toString())
                        activity.sendResult(strURL)
                        activity.finish()
                        dialog.dismiss()
                    }
                    dialog.text_dialog_cancel_tel.setOnClickListener {
                        dialog.dismiss()
                    }
                }
                TYPE_MAIL -> {
                    val dialog = Dialog(activity)
                    dialog.setCancelable(false)
                    dialog.setContentView(R.layout.dialog_mail)
                    dialog.show()
                    dialog.text_dialog_generate_mail.setOnClickListener {
                        val strURL = generateMAILString(dialog.edit_mail_address.text.toString())
                        activity.sendResult(strURL)
                        activity.finish()
                        dialog.dismiss()
                    }
                    dialog.text_dialog_cancel_mail.setOnClickListener {
                        dialog.dismiss()
                    }
                }
                TYPE_MECARD -> {
                }
                TYPE_VCARD -> {
                }
                TYPE_VEVENT -> {
                }
            }
        }

        holder.textTypeName.setOnClickListener { }
    }

    private fun generateMAILString(mail: String): String {
        var strResult = "mailto:"
        strResult += mail
        return strResult
    }

    private fun generateTELString(tel: String): String {
        var strResult = "tel:"
        strResult += tel
        return strResult
    }

    private fun generateGEOString(latitude: String, longitude: String, query: String): String {
        var strResult = "geo:"
        strResult += latitude + "," + longitude + "q=" + query
        return strResult
    }

    private fun generateSMSString(tel: String, message: String): String {
        var strResult = "smsto:"
        if (tel == ""){
            return ""
        }
        strResult += tel
        strResult += ":" + message
        return strResult
    }

    private fun generateURLString(url: String): String {
        var strResult = url
        if (url.indexOf("http") != 0){
            strResult = "http://" + url
        }
        return strResult
    }

    private fun generateWifiString(ssid: String, password: String, type: Int, hidden: Boolean, dialog: Dialog): String {
        if (ssid == ""){
            return ""
        }
        var strResult = "WIFI:"
        strResult += "S:$ssid;"
        if (password != ""){
            strResult += "P:$password;"
        }
        when(type){
            dialog.type_wep.id->{
                strResult += "T:WEP;"
            }
            dialog.type_wpa.id->{
                strResult += "T:WPA;"
            }
            dialog.type_none.id->{}
        }

        if (hidden){
            strResult += "H:true;"
        }
        strResult += ";"
        return strResult
    }



    override fun getItemCount(): Int {
        return mTypeNameArray.size - 3
    }

    private fun setClickStatusImg(context: Context, nNormal: Int, nPressed: Int, imgview: ImageView) {
        val states = StateListDrawable()
        states.addState(intArrayOf(android.R.attr.state_pressed), ContextCompat.getDrawable(context, nPressed))
        states.addState(intArrayOf(android.R.attr.state_focused), ContextCompat.getDrawable(context, nPressed))
        states.addState(intArrayOf(), ContextCompat.getDrawable(context, nNormal))
        imgview.setImageDrawable(states)
    }

    private fun setClickStatusTxt(context: Context, nNormal: Int, nPressed: Int, textView: TextView) {
        val colorStateList = ColorStateList(
                arrayOf(intArrayOf(android.R.attr.state_pressed), intArrayOf(android.R.attr.state_selected), intArrayOf(-android.R.attr.state_selected)),
                intArrayOf(ContextCompat.getColor(context, nPressed), ContextCompat.getColor(context, nPressed), ContextCompat.getColor(context, nNormal)))
        textView.setTextColor(colorStateList)
    }

    companion object {
        const val TYPE_WIFI = 0
        const val TYPE_WEBSITE = 1
        const val TYPE_SMS = 2
        const val TYPE_GEO = 3
        const val TYPE_TEL = 4
        const val TYPE_MAIL = 5
        const val TYPE_MECARD = 6
        const val TYPE_VCARD = 7
        const val TYPE_VEVENT = 8
    }
}

class TypeHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
    var llGroup: LinearLayout = itemView.findViewById(R.id.ll_group)
    var imgLogo: ImageView = itemView.findViewById(R.id.img_logo)
    var textTypeName: TextView = itemView.findViewById(R.id.text_type_name)

}



<|start_filename|>app/src/main/java/com/showlin/simpleQRCode/activity/GenerateActivity.kt<|end_filename|>
package com.showlin.simpleQRCode.activity

import android.content.ContentResolver
import android.content.ContentUris
import android.content.ContentValues
import android.content.Intent
import android.content.pm.PackageManager
import android.graphics.Bitmap
import android.graphics.Matrix
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.provider.MediaStore
import android.support.annotation.RequiresApi
import android.view.MenuItem
import android.view.View
import com.showlin.simpleQRCode.R
import com.showlin.simpleQRCode.Utility
import com.showlin.simpleQRCode.Utility.KEY_CONTENT
import com.showlin.simpleQRCode.Utility.REQUEST_CODE
import kotlinx.android.synthetic.main.activity_generate.*
import java.io.IOException
import java.util.*


class GenerateActivity : BaseActivity(){
    private var mTextInput : String? = null
    private var mQRBitmap : Bitmap? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_generate)

        supportActionBar!!.title = getString(R.string.generate)
        supportActionBar!!.setDisplayHomeAsUpEnabled(true)

        btn_go_generate.setOnClickListener {
            mQRBitmap = Utility.generateQR(edit_input.text.toString())
            if (mQRBitmap != null){
                mTextInput = edit_input.text.toString()
                img_qr_code.setImageBitmap(mQRBitmap)
                btn_save.visibility = View.VISIBLE
            }else{
                btn_save.visibility = View.INVISIBLE
                img_qr_code.setImageBitmap(null)
                mQRBitmap = null
            }
        }

        btn_save.setOnClickListener {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M){
                if (checkSelfPermission("android.permission.WRITE_EXTERNAL_STORAGE") != PackageManager.PERMISSION_GRANTED){
                    val strings = Array<String>(1) { "android.permission.WRITE_EXTERNAL_STORAGE" }
                    requestPermissions(strings, Utility.WRITE_PERMISSION)
                    return@setOnClickListener
                }
            }

            CapturePhotoUtils.insertImage(contentResolver, mQRBitmap, Date().time.toString(), this.mTextInput!!)
        }

        btn_type_generate.setOnClickListener {
            val intent = Intent(this@GenerateActivity, TypeGenerateActivity::class.java)
            startActivityForResult(intent, REQUEST_CODE)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        super.onActivityResult(requestCode, resultCode, data)
        if (requestCode == REQUEST_CODE){
            if (data != null){
                val strContent = data!!.getStringExtra(KEY_CONTENT)
                edit_input.setText(strContent)
                mQRBitmap = Utility.generateQR(edit_input.text.toString())
                if (mQRBitmap != null){
                    mTextInput = edit_input.text.toString()
                    img_qr_code.setImageBitmap(mQRBitmap)
                    btn_save.visibility = View.VISIBLE
                }else{
                    btn_save.visibility = View.INVISIBLE
                    img_qr_code.setImageBitmap(null)
                    mQRBitmap = null
                }
            }

        }
    }

    @RequiresApi(Build.VERSION_CODES.M)
    override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if(requestCode == Utility.WRITE_PERMISSION){
            for (i in permissions.indices ){
                if (grantResults.get(i) !=  PackageManager.PERMISSION_GRANTED){
                    val strings = Array<String>(1) { "android.permission.WRITE_EXTERNAL_STORAGE" }
                    requestPermissions(strings, Utility.WRITE_PERMISSION)
                }
            }
        }
    }

    override fun onOptionsItemSelected(item: MenuItem): Boolean {
        if (item.itemId == android.R.id.home) {
            finish()
            return true
        }
        return super.onOptionsItemSelected(item)
    }
}


object CapturePhotoUtils {

    fun insertImage(cr: ContentResolver,
                    source: Bitmap?,
                    title: String,
                    description: String): String? {

        val values = ContentValues()
        values.put(MediaStore.Images.Media.TITLE, title)
        values.put(MediaStore.Images.Media.DISPLAY_NAME, title)
        values.put(MediaStore.Images.Media.DESCRIPTION, description)
        values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg")
        // Add the date meta data to ensure the image is added at the front of the gallery
        values.put(MediaStore.Images.Media.DATE_ADDED, System.currentTimeMillis())
        values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis())

        var url: Uri? = null
        var stringUrl: String? = null    /* value to be returned */

        try {
            url = cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values)

            if (source != null) {
                assert(url != null)
                val imageOut = cr.openOutputStream(url!!)
                try {
                    source.compress(Bitmap.CompressFormat.JPEG, 50, imageOut)
                } finally {
                    assert(imageOut != null)
                    imageOut!!.close()
                }

                val id = ContentUris.parseId(url)
                // Wait until MINI_KIND thumbnail is generated.
                val miniThumb = MediaStore.Images.Thumbnails.getThumbnail(cr, id, MediaStore.Images.Thumbnails.MINI_KIND, null)
                // This is for backward compatibility.
                storeThumbnail(cr, miniThumb, id, MediaStore.Images.Thumbnails.MICRO_KIND)
            } else {
                assert(url != null)
                cr.delete(url!!, null, null)
                url = null
            }
        } catch (e: Exception) {
            if (url != null) {
                cr.delete(url, null, null)
                url = null
            }
        }

        if (url != null) {
            stringUrl = url.toString()
        }

        return stringUrl
    }

    private fun storeThumbnail(
            cr: ContentResolver,
            source: Bitmap,
            id: Long,
            kind: Int) {

        val matrix = Matrix()

        val scaleX = 50f / source.width
        val scaleY = 50f / source.height

        matrix.setScale(scaleX, scaleY)

        val thumb = Bitmap.createBitmap(source, 0, 0,
                source.width,
                source.height, matrix,
                true
        )

        val values = ContentValues(4)
        values.put(MediaStore.Images.Thumbnails.KIND, kind)
        values.put(MediaStore.Images.Thumbnails.IMAGE_ID, id.toInt())
        values.put(MediaStore.Images.Thumbnails.HEIGHT, thumb.height)
        values.put(MediaStore.Images.Thumbnails.WIDTH, thumb.width)

        val url = cr.insert(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, values)

        try {
            assert(url != null)
            val thumbOut = cr.openOutputStream(url!!)
            thumb.compress(Bitmap.CompressFormat.JPEG, 100, thumbOut)
            assert(thumbOut != null)
            thumbOut!!.close()
        } catch (ignored: IOException) {
        }

    }
}

<|start_filename|>app/src/main/java/com/showlin/simpleQRCode/activity/MainActivity.kt<|end_filename|>
package com.showlin.simpleQRCode.activity

import android.app.Activity
import android.content.Intent
import android.graphics.Typeface
import android.os.Build
import android.os.Bundle
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.view.WindowManager
import android.view.animation.AccelerateInterpolator
import android.view.animation.Animation
import android.view.animation.RotateAnimation
import android.view.animation.TranslateAnimation
import com.showlin.simpleQRCode.R
import com.showlin.simpleQRCode.Utility
import com.showlin.simpleQRCode.Utility.REQUEST_CODE
import kotlinx.android.synthetic.main.activity_main.*
import android.app.ActivityManager.TaskDescription
import android.content.res.Resources
import android.graphics.BitmapFactory
import android.graphics.Bitmap




class MainActivity : BaseActivity() {
    var isSwitch = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP){
            val bm = BitmapFactory.decodeResource(resources, R.drawable.logo)
            val taskDesc = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                TaskDescription(getString(R.string.app_name), bm, ContextCompat.getColor(this, R.color.color1))
            } else {
                TODO("VERSION.SDK_INT < LOLLIPOP")
            }
            setTaskDescription(taskDesc)
        }


        btn_capture.setOnClickListener{
            val animation = RotateAnimation(0f, -360f, Animation.ABSOLUTE, btn_capture.pivotX, Animation.ABSOLUTE, btn_capture.pivotY + 100)
            animation.duration = 600
            animation.interpolator = object : AccelerateInterpolator(){}
            img_bear_white.startAnimation(animation)
            animation.setAnimationListener(object :Animation.AnimationListener{
                override fun onAnimationRepeat(animation: Animation?) {
                }

                override fun onAnimationEnd(animation: Animation?) {
                    runOnUiThread {Utility.scan(this@MainActivity)}
                }

                override fun onAnimationStart(animation: Animation?) {
                }

            })
        }

        img_bear_white.setOnClickListener {
            val animation = RotateAnimation(0f, -360f, Animation.ABSOLUTE, btn_capture.pivotX, Animation.ABSOLUTE, btn_capture.pivotY + 100)
            animation.duration = 600
            animation.interpolator = object : AccelerateInterpolator(){}
            img_bear_white.startAnimation(animation)
        }

        btn_generate.setOnClickListener {
            val animation = RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
            animation.duration = 300
            img_bear_brown.startAnimation(animation)
            animation.setAnimationListener(object :Animation.AnimationListener{
                override fun onAnimationRepeat(animation: Animation?) {
                }

                override fun onAnimationEnd(animation: Animation?) {
                    runOnUiThread {
                        val intent = Intent(this@MainActivity, GenerateActivity::class.java)
                        startActivity(intent)
                    }
                }

                override fun onAnimationStart(animation: Animation?) {
                }

            })
        }

        img_bear_brown.setOnClickListener {
            val animation = RotateAnimation(0f, 360f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f)
            animation.duration = 300
            img_bear_brown.startAnimation(animation)
        }

        text_title.typeface = Typeface.createFromAsset(assets, "fonts/font.ttf")
        text_title.setOnClickListener{
            isSwitch = !isSwitch
            val oneX = img_bird_1.x
            val twoX = img_bird_2.x
            val offset = Math.abs(oneX - twoX)

            val animation = TranslateAnimation(0f, offset, 0f, 0f)
            animation.duration = 300
            animation.isFillEnabled = true
            animation.fillAfter = true
            animation.setAnimationListener(object : Animation.AnimationListener{
                override fun onAnimationRepeat(animation: Animation?) {

                }

                override fun onAnimationEnd(animation: Animation?) {
                    if (isSwitch){
                        img_bird_1.setImageResource(R.drawable.img_bird_2)
                    }else{
                        img_bird_1.setImageResource(R.drawable.img_bird_1)
                    }
                    img_bird_1.clearAnimation()
                }

                override fun onAnimationStart(animation: Animation?) {
                }

            })
            img_bird_1.startAnimation(animation)


            val animation2 = TranslateAnimation(0f, -offset, 0f, 0f)
            animation2.duration = 300
            animation2.isFillEnabled = true
            animation2.fillAfter = true
            animation2.setAnimationListener(object : Animation.AnimationListener{
                override fun onAnimationRepeat(animation: Animation?) {

                }

                override fun onAnimationEnd(animation: Animation?) {
                    if (isSwitch){
                        img_bird_2.setImageResource(R.drawable.img_bird_1)
                    }else{
                        img_bird_2.setImageResource(R.drawable.img_bird_2)
                    }
                    img_bird_2.clearAnimation()
                }

                override fun onAnimationStart(animation: Animation?) {

                }

            })
            img_bird_2.startAnimation(animation2)
        }
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        if (requestCode == REQUEST_CODE){
            if (resultCode == Activity.RESULT_OK){
                val bundleResult = data!!.extras
                val intent = Intent(this, ResultActivity::class.java)
                intent.putExtras(bundleResult)
                startActivity(intent)
            }
        }
    }
}


<|start_filename|>app/src/main/java/com/showlin/simpleQRCode/Utility.kt<|end_filename|>
package com.showlin.simpleQRCode

import android.app.Activity
import android.content.Intent
import android.graphics.Bitmap
import android.graphics.Color
import com.google.zxing.BarcodeFormat
import com.google.zxing.EncodeHintType
import com.google.zxing.MultiFormatWriter
import com.google.zxing.WriterException
import com.google.zxing.common.BitMatrix
import com.google.zxing.common.CharacterSetECI
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel
import com.showlin.simpleQRCode.activity.ScanActivity
import java.util.*


object Utility {
    const val KEY_RESULT = "KEY_RESULT"
    const val KEY_CONTENT = "KEY_CONTENT"

    const val REQUEST_CODE= 2304
    const val WRITE_PERMISSION = 2134

    fun scan(activity: Activity){
        val intent = Intent(activity, ScanActivity::class.java)
        activity.startActivityForResult(intent, REQUEST_CODE)
    }

    @Throws(WriterException::class)
    fun generateQR(value: String) : Bitmap? {
        val bitMatrix: BitMatrix
        try {
            val hints = EnumMap<EncodeHintType, Any>(EncodeHintType::class.java)
            hints[EncodeHintType.ERROR_CORRECTION] = ErrorCorrectionLevel.H
            hints[EncodeHintType.CHARACTER_SET] = CharacterSetECI.UTF8

            bitMatrix = MultiFormatWriter().encode(
                    value,
                    BarcodeFormat.QR_CODE,
                    500,
                    500,
                    hints
            )
        }catch (Illegalargumentexception : IllegalArgumentException){
            return null
        }

        val bitMatrixWidth = bitMatrix.width

        val bitMatrixHeight = bitMatrix.height

        val pixels = IntArray(bitMatrixWidth * bitMatrixHeight)

        for (y in 0 until bitMatrixHeight) {
            val offset = y * bitMatrixWidth

            for (x in 0 until bitMatrixWidth) {

                pixels[offset + x] = if (bitMatrix.get(x, y))
                    Color.BLACK
                else
                    Color.WHITE
            }
        }
        val bitmap = Bitmap.createBitmap(bitMatrixWidth, bitMatrixHeight, Bitmap.Config.ARGB_4444)
        bitmap.setPixels(pixels, 0, 500, 0, 0, bitMatrixWidth, bitMatrixHeight)

        return bitmap
    }
}