Hallo Sahabat CAN Creative, kembali lagi dengan artikel tutorial dari CAN Creative yang siap menambah wawasan Anda. Kali ini kita akan membuat sebuah permintaan izin untuk menggunakan fitur di aplikasi kita. Sering kita lihat ketika aplikasi ingin mengakses GPS, akan selalu tampil pertanyaan “aplikasi membutuhkan akses GPS “ dan anda akan mendapat pilihan diizinkan ataupun ditolak. Tapi untuk android 10+ pilihan di ganti menjadi tolak, di izinkan ketika buka aplikasi dan tanya selalu. Izin aplikasi ini sendiri mulai hadir di android 23 atau di versi marshmallows, untuk versi di bawahnya seperti KitKat, Lollipop dan lainnya semua mendapatkan izin dan tidak perlu meminta nya.
meminta izin menggunakan GPS
Dalam studi kali ini kita akan minta ijin untuk meminta izin menggunakan GPS. pertama siapkan terlebih dahulu projek. Setelah selesai membuat projek barunya. Silahkan buka main_activity.xml nya. Dan tambahkan kode seperti di bawah ini :
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<TextView
android:textSize="20dp"
android:layout_centerInParent="true"
android:id="@+id/main_tv_status"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Tidak ada izin untuk GPS"
app:layout_constraintBottom_toBottomOf="parent"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent" />
<Button
android:layout_marginTop="10dp"
android:layout_centerHorizontal="true"
android:layout_below="@+id/main_tv_status"
android:text="Request"
android:textAllCaps="false"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/main_btn_call"/>
</RelativeLayout>
Di halaman ini kita hanya menampilkan 1 TextView untuk menampilkan status izin aplikasinya dan 1 button untuk aksi meminta izin. Selanjutnya kita buka AndroidManifest.xml karena kita ingin menggunkan GPS maka tambahkan
Menampilkan Status Izin Aplikasi
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
Ini bertujuan untuk memberitahukan bahwa aplikasi menggunakan izin tersebut. Selengkapnya untuk kode di manifest.
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="can.co.id.myrequestpermission">
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:roundIcon="@mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="@style/Theme.MyRequestPermission">
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Langkah selanjutnya buka terlebih dahulu MainActivity.class kalian dan tambahkan inisialisasi request_code di bawah ini.
val REQUEST_CODE = 445 |
Selanjutnya kita buat method izinLokasi(). Di method ini kita akan mengecek apakah aplikasi sudah mempunyai izin untuk mengakses lokasi dengan ContextCompat.checkSelfPermission() bila izin tidak diberikan kita akan meminta izin tersebut dengan bantuan method ActivityCompat.requestPermissions . langsung saja tanpa lama-lama bisa lihat kode di bawah ini.
fun izinLokasi(): Boolean {
val r_lokasi = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
val r_lokasi_coarse = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
val listPermissionsNeed = ArrayList<String>()
if (r_lokasi != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeed.add(Manifest.permission.ACCESS_FINE_LOCATION)
}
if (r_lokasi_coarse != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeed.add(Manifest.permission.ACCESS_COARSE_LOCATION)
}
if (!listPermissionsNeed.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeed.toTypedArray(), REQUEST_CODE)
return false
}
return true
}
Di metode tersebut selain meminta izin juga akan mengembalikan nilai apakah aplikasi sudah memiliki izin atau belum, itu berfungsi ketika kita akan menggunakan fitur bila izin sudah di berikan maka kita akan lanjut ke kode berikutnya.
Selanjutnya setelah kita membuat method untuk meminta ijin, kita akan mengambil hasil dari permintaan tersebut di method onRequestPermissionsResult. Apakah di berikan oleh user ataupun tidak dan bila izin tidak di berikan kita bisa menambahkan kode peringatan atau lainnya sesuai dengan kebutuhan aplikasi. Langsung saja bisa lihat kode di bawah ini.
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_CODE){
if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Izin diberikan", Toast.LENGTH_SHORT).show()
}else{
Toast.makeText(this, "Izin tidak diberikan", Toast.LENGTH_SHORT).show()
}
}
}
Langkah selanjutnya setelah kita mendapatkan hasil dari permintaan izin adalah mengimplementasikan method izinLokasi() ke dalam onCreate(). Kita akan memanggil method tersebut ketika Button di tekan, langsung lihat kode dibawah ini.
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
val btnMain = findViewById<Button>(R.id.main_btn_call)
btnMain.setOnClickListener {
if (izinLokasi()){
Toast.makeText(this, "Izin sudah diberikan", Toast.LENGTH_SHORT).show()
}else{
Toast.makeText(this, "Meminta izin akses lokasi", Toast.LENGTH_SHORT).show()
}
}
}
Setelah selesai mari kita coba jalankan aplikasinya. Dan hasilnya akan seperti di bawah ini.
Kode di atas belum dengan menampilkan status izin ke TextView yang sudah kita buat. Berikut kode lengkap untuk MainActivity.class yang sudah menggunakan TextView tersebut.
import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import java.util.*
class MainActivity : AppCompatActivity() {
val REQUEST_CODE = 445
lateinit var tvStatusIzin:TextView
lateinit var btnMain:Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
tvStatusIzin = findViewById(R.id.main_tv_status)
btnMain = findViewById(R.id.main_btn_call)
btnMain.setOnClickListener {
if (izinLokasi()){
Toast.makeText(this, "Izin sudah diberikan", Toast.LENGTH_SHORT).show()
tvStatusIzin.text = "Izin sudah diberikan"
}else{
tvStatusIzin.text = "Meminta izin akses lokasi"
}
}
if (izinLokasi()){
tvStatusIzin.text = "Izin sudah diberikan"
btnMain.visibility = View.GONE
}
}
fun izinLokasi(): Boolean {
val r_lokasi = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION)
val r_lokasi_coarse = ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION)
val listPermissionsNeed = ArrayList<String>()
if (r_lokasi != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeed.add(Manifest.permission.ACCESS_FINE_LOCATION)
}
if (r_lokasi_coarse != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeed.add(Manifest.permission.ACCESS_COARSE_LOCATION)
}
if (!listPermissionsNeed.isEmpty()) {
ActivityCompat.requestPermissions(this, listPermissionsNeed.toTypedArray(), REQUEST_CODE)
return false
}
return true
}
override fun onRequestPermissionsResult(requestCode: Int, permissions: Array<out String>, grantResults: IntArray) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults)
if (requestCode == REQUEST_CODE){
if (grantResults.size > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Toast.makeText(this, "Izin diberikan", Toast.LENGTH_SHORT).show()
tvStatusIzin.text = "Izin diberikan"
btnMain.visibility = View.GONE
}else{
tvStatusIzin.text = "Izin tidak diberikan"
}
}
}
}
Selamat mencoba, semoga sefruit tutorial ini berguna untuk sahabat CAN Creative yang berminat menekuni bidang IT khususnya menjadi developer. Anda juga dapat mengetahui promo menarik seputar penawaran website, aplikasi, digital marketing ataupun SEO melalui website kami can.co.id. Kami juga aktif di media sosial instagram @cancreative, Line @cancreative. source code lengkap di unggah di Github : https://github.com/ramcona/permissionruntimeexample.
Referensi : https://developer.android.com/training/permissions/requesting?hl=id
Refenresi : https://developer.android.com/guide/topics/permissions/overview
Качественные WordPress ссылки в комментариях от 5000 уник. доменов заказать здесь .
Качественные WordPress ссылки в комментариях от 5000 уник. доменов заказать здесь .
I don’t need to tell you how important it is to optimize every step in your SEO pipeline. But unfortunately, it’s nearly impossible to cut out time or money when it comes to getting good content. At least that’s what I thought until I came across Article Forge… Built by a team of AI researchers from MIT, Carnegie Mellon, Harvard, Article Forge is an artificial intelligence (AI) powered content writer that uses deep learning models to write entire articles about any topic in less than 60 seconds. Their team trained AI models on millions of articles to teach Article Forge how to draw connections between topics so that each article it writes is relevant, interesting and useful. All their hard work means you just enter a few keywords and Article Forge will write a complete article from scratch making sure every thought flows naturally into the next, resulting in readable, high quality, and unique content. Put simply, this is a secret weapon for anyone who needs content. I get how impossible that sounds so you need to see how Article Forge writes a complete article in less than 60 seconds! order here.
Use artificial intelligence to cut turnaround time, extend your budget, and create more high-quality content that Google and readers will love. How It Works? WordAi is extremely fast and intuitive. Just enter your content, click rewrite, and in a matter of seconds, WordAi will rewrite an entire piece of content for you. WordAi comes up with different ways to express the same ideas by rewriting every sentence from scratch. This not only removes duplicate content, it also makes the rewritten content read completely naturally. Scale Your Business Make your entire content production process 10x more efficient. Use AI to create more high-quality, unique content that impresses clients and engages readers, all without having to put in more hours Register here and get a bonus.
I was pretty pleased to discover this great site. I need to to thank you for your time for this particularly fantastic read!! I definitely appreciated every part of it and I have you book marked to see new stuff on your blog
Meminta App Permission Di Android Dengan Kotlin – Jasa Pembuatan Aplikasi Mobile Android IOS | CAN Creative
pcnqjqoiw http://www.gi7afw5l0m3c517r80rmz83567nw65hms.org/
apcnqjqoiw
[url=http://www.gi7afw5l0m3c517r80rmz83567nw65hms.org/]upcnqjqoiw[/url]
viagra without doctor prescription
ed natural remedies buy generic ed pills online best pill for ed
buy sildenafil 50mg – viagra 150mg uk sildenafil ca
ivermectin studies 2021 ivermectin generic does ivermectin kill tapeworms
rhino laboratories cialis cialis usa prescription cialis trial coupon
5 mg prednisone daily order prednisone where can i buy prednisone online without a prescription
oral prednisolone 20mg – order tadalafil free shipping cialis
5mg of cialis purchasing cialis in the usa Go Now
Ss 316m8 Carriage Bolt
Railroad Ink Arcade Expansion Pack
http://b25.chip.jp/ai514ru/
https://gdf4gs.shiga-saku.net/
LR018354
Jigger Dyeing
cialis costco purchasing cialis in the usa cialis pills australia
super active cialis with no prescription cialis 20 mg best price generic cialis priligy australia
https://ae674i.weblog.to/
L Track Systems
Carbon Fiber Arm
augmentin 375mg cheap – tadalafil 10mg tablet tadalafil 10mg cost
ivermectin mites ivermectin covid 19 ivermectin meta-analysis
https://aoeq6d.2chblog.jp/
Pedestal Solar Pillar Lamp
blood bank centrifuge price
Sodium Per Carbonate
http://b30.chip.jp/bgfngh/
Sextuple Arm Articulating TV Wall Mount for TV Size 26″-55″
finasteride 5mg finasteride for sale propecia buy without per
https://er4tgg.exblog.jp/
Ratchet Buckle
Fogg Spray Machine
sildenafil without a doctor’s prescription ed meds online without doctor prescription canadian medications
buy bactrim 960mg generic – buy viagra 50mg sildenafil 50mg uk
https://aerf4.cocolog-nifty.com/
Air Purifier With Light
Modular Chillers
who makes ivermectin stock ivermectin studies 1 ivermectin dosage for dogs
Intermediate Shaft Socket and Wrench Multifunctional Bike Repair Tools
Smallest Wireless Earbuds
http://fdupf.ffsagami.com/
https://tr5thbfdg.ko-co.jp/
Construction Machinery Steel Forging Parts
Bic Disposable Razors
anti fungal pills without prescription meds online without doctor prescription pet antibiotics without vet prescription
Laser Cutter Machine
Olopatadine Hydrochloride
https://ad9k8.teamblog.jp/
finasteride online propecia hair loss finasteride 1mg
Jigsaw Puzzles
Kids Rain Coat Raincoat
https://wqiqy.golog.jp/
cephalexin 500mg price – cephalexin price erythromycin pill
erectile dysfunction medicines ed drugs list ed pills that work
National Standard Two-core 1.5 Square Cable RVV 2×1
Galvanized Steel Sectional Water Tank
http://fdsg.jugem.jp/
stromectol without a doctor prescription stromectol stromectol 3 mg tablets price
generic fildena 50mg – nolvadex 20mg cost cost of ivermectin
Automatic Door Glass
Rechargeable Disposable Device 3500 Puffs
http://cgvsdfsdf.ffsagami.com/
top erection pills treatments for ed the best ed pills
erection pills what is the best ed pill ed medication