Ошибка функции с кнопками, работающими только в определенном порядке - PullRequest
0 голосов
/ 23 мая 2019

Я новичок в этом.Мое приложение ниже работает, но по какой-то причине кнопки работают только в определенном порядке.Например, когда я нажимаю кнопку отправки по электронной почте, она не работает.Но если я нажимаю смс и отменяю опцию, затем нажимаю на электронную почту, она будет работать.Это крайне проблематично для новых установок.

Приложение работает функционально, но кнопки работают только в определенном порядке.

package com.example.travel
import android.Manifest
import android.Manifest.permission
import android.annotation.SuppressLint
import android.content.ActivityNotFoundException
import android.content.Intent
import android.content.pm.PackageManager
import android.location.Location
import android.net.Uri
import android.os.Build
import android.os.Bundle
import android.support.annotation.RequiresApi
import android.support.v4.app.ActivityCompat
import android.support.v4.content.ContextCompat
import android.support.v7.app.AppCompatActivity
import android.widget.Toast
import com.google.android.gms.location.FusedLocationProviderClient
import com.google.android.gms.location.LocationCallback
import com.google.android.gms.location.LocationResult
import com.google.android.gms.location.LocationServices
import kotlinx.android.synthetic.main.content_main.*


private val MY_PERMISSIONS_LOCATION = 101
private val MY_PERMISSIONS_SMS = 105
private val  MULTIPLE_PERMISSION = 110

class MainActivity : AppCompatActivity(), 
ActivityCompat.OnRequestPermissionsResultCallback {

@SuppressLint("NewApi")
@RequiresApi(Build.VERSION_CODES.M)
override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)


    requestPermissions(
        arrayOf(Manifest.permission.SEND_SMS, Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.CALL_PHONE),
        MULTIPLE_PERMISSION
    )
    if (ContextCompat.checkSelfPermission(this, permission.ACCESS_FINE_LOCATION)
        != PackageManager.PERMISSION_GRANTED
    ) {
        // Permission is not granted
    }


    if (ContextCompat.checkSelfPermission(this, permission.SEND_SMS)
        != PackageManager.PERMISSION_GRANTED
    ) {
        // Permission is not granted
    }

// Здесь thisActivity - текущая активность

    if (ContextCompat.checkSelfPermission(
            this,
            permission.ACCESS_FINE_LOCATION
        )
        != PackageManager.PERMISSION_GRANTED
    ) {

        // Permission is not granted
        // Should we show an explanation?
        if (ActivityCompat.shouldShowRequestPermissionRationale(
                this,
                permission.ACCESS_FINE_LOCATION
            )
        ) {

        } else {
            // No explanation needed, we can request the permission.
            ActivityCompat.requestPermissions(
                this,
                arrayOf(permission.ACCESS_FINE_LOCATION),
                MY_PERMISSIONS_LOCATION
            )
        }
    } else {
        // Permission has already been granted
    }

    fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<String>, grantResults: IntArray
    ) {
        when (requestCode) {
            MY_PERMISSIONS_LOCATION -> {
                // If request is cancelled, the result arrays are empty.
                if ((grantResults.isNotEmpty() && grantResults[0] == PackageManager.PERMISSION_GRANTED)) {

                }
                return
            }

            // Add other 'when' lines to check for other
            // permissions this app might request.
            else -> {
                // Ignore all other requests.
            }
        }
    }



    button4.setOnClickListener {
        val callIntent = Intent(Intent.ACTION_CALL)
        callIntent.data = Uri.parse("tel:+Enter Phone Number")
        startActivity(callIntent)
    }

    button5.setOnClickListener {
        val intent2 = Intent(this, privacyActivity::class.java)
        startActivity(intent2)
    }


    val fusedLocationClient: FusedLocationProviderClient =
        LocationServices.getFusedLocationProviderClient(this)

    lateinit var locationCallback: LocationCallback


    fusedLocationClient.lastLocation
        .addOnSuccessListener { location: Location? ->
            // Got last known location. In some rare situations this can be null.


            fun onCreate(savedInstanceState: Bundle?) {


                locationCallback = object : LocationCallback() {
                    override fun onLocationResult(locationResult: LocationResult?) {
                        locationResult ?: return
                        for (location in locationResult.locations) {

                        }
                    }
                }
            }

            var lat = location?.latitude
            var lon = location?.longitude
            var acc = location?.accuracy



            button.setOnClickListener {
                val intent = Intent(Intent.ACTION_VIEW, Uri.parse("sms:" + "Enter Phone Number"))
                intent.putExtra(
                    "sms_body",
                    "I have reached my destination." + " My location is: " + "Latitude: " + lat + " Longitude: " + lon
                )
                startActivity(intent)

            }
            button2.setOnClickListener {
                val intent = Intent(Intent.ACTION_VIEW, Uri.parse("sms:" + "Enter Phone Number"))
                intent.putExtra(
                    "sms_body",
                    "I am in immediate need of assistance, " + " My location is: " + "Latitude: " + lat + " Longitude: " + lon + " Accuracy:  " + acc
                )
                startActivity(intent)

                button6.setOnClickListener {
                    val emailIntent = Intent(Intent.ACTION_SENDTO)
                    emailIntent.data = Uri.parse("mailto:Enteremailaddress")

                    emailIntent.putExtra (Intent.EXTRA_SUBJECT, "Safety Check-in")
                    emailIntent.putExtra (Intent.EXTRA_TEXT, "I have reached my destination" + " My location is: " + "Latitude: " + lat + " Longitude: " + lon);
                    try {
                        startActivity(emailIntent)
                    } catch (e: ActivityNotFoundException) {
                        Toast.makeText(this, "There are no email applications installed.", Toast.LENGTH_SHORT)
                            .show()

                    }

                    button3.setOnClickListener {
                        val emailIntenthelp = Intent(Intent.ACTION_SENDTO)
                        emailIntenthelp.data = Uri.parse("mailto:Enter Email")
                        emailIntenthelp.putExtra(Intent.EXTRA_SUBJECT, "URGENT ASSISTANCE NEEDED")
                        emailIntenthelp.putExtra(Intent.EXTRA_TEXT   , "I am in need of immediate assistance" + " My location is: " + "Latitude: " + lat +  "Longitude: " + lon)
                        try {
                            startActivity(emailIntenthelp)
                        } catch (e: ActivityNotFoundException) {
                            Toast.makeText(this, "There are no email applications installed.", Toast.LENGTH_SHORT)
                                .show()

                        }
                    }
                }
            }
        }
}
}

1 Ответ

0 голосов
/ 23 мая 2019

Отступ вашего кода - подсказка к вашей проблеме.Вы можете установить OnClickListener на button6 только после выполнения OnClickListener на button2.OnClickListener on button3 не устанавливается до тех пор, пока не будет выполнен метод OnClickListener для button6.

Вам необходимо убедиться, что вы переводите вызовы на setOnClickListener() все вне методов,Это должно выглядеть так:

            button2.setOnClickListener {
                val intent = Intent(Intent.ACTION_VIEW, Uri.parse("sms:" + "Enter Phone Number"))
                intent.putExtra(
                    "sms_body",
                    "I am in immediate need of assistance, " + " My location is: " + "Latitude: " + lat + " Longitude: " + lon + " Accuracy:  " + acc
                )
                startActivity(intent)
            }
            button6.setOnClickListener {
                val emailIntent = Intent(Intent.ACTION_SENDTO)
                emailIntent.data = Uri.parse("mailto:Enteremailaddress")

                emailIntent.putExtra (Intent.EXTRA_SUBJECT, "Safety Check-in")
                emailIntent.putExtra (Intent.EXTRA_TEXT, "I have reached my destination" + " My location is: " + "Latitude: " + lat + " Longitude: " + lon);
                try {
                    startActivity(emailIntent)
                } catch (e: ActivityNotFoundException) {
                    Toast.makeText(this, "There are no email applications installed.", Toast.LENGTH_SHORT)
                            .show()
                }
            }
            button3.setOnClickListener {
                val emailIntenthelp = Intent(Intent.ACTION_SENDTO)
                emailIntenthelp.data = Uri.parse("mailto:Enter Email")
                emailIntenthelp.putExtra(Intent.EXTRA_SUBJECT, "URGENT ASSISTANCE NEEDED")
                emailIntenthelp.putExtra(Intent.EXTRA_TEXT   , "I am in need of immediate assistance" + " My location is: " + "Latitude: " + lat +  "Longitude: " + lon)
                try {
                    startActivity(emailIntenthelp)
                } catch (e: ActivityNotFoundException) {
                    Toast.makeText(this, "There are no email applications installed.", Toast.LENGTH_SHORT)
                                .show()
                }
            }
        }
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...