KEMBAR78
Android Cheat Sheet | PDF | Computer Programming | Software Engineering
0% found this document useful (0 votes)
34 views2 pages

Android Cheat Sheet

The document outlines various components of Android development, including RecyclerView, ListView, ViewModel, and Services. It provides code snippets for implementing these components, such as creating adapters, handling user interactions, and managing permissions. Additionally, it covers the use of WorkManager for background tasks and BroadcastReceiver for network change notifications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
34 views2 pages

Android Cheat Sheet

The document outlines various components of Android development, including RecyclerView, ListView, ViewModel, and Services. It provides code snippets for implementing these components, such as creating adapters, handling user interactions, and managing permissions. Additionally, it covers the use of WorkManager for background tasks and BroadcastReceiver for network change notifications.
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 2

▶ RecyclerView - Activity ▶ Fragment

val recyclerView = class MyFragment : Fragment() {


findViewById<RecyclerView>(R.id.recyclerView) override fun onCreateView(inflater: LayoutInflater,
recyclerView.layoutManager = LinearLayoutManager(this) container: ViewGroup?, savedInstanceState: Bundle?): View?
val adapter = PersonAdapter(personList) {
recyclerView.adapter = adapter return inflater.inflate(R.layout.fragment_my,
container, false)
}

override fun onViewCreated(view: View,


▶ RecyclerView - Adapter savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
class PersonAdapter(private val personList: List<Person>) : button.setOnClickListener {
RecyclerView.Adapter<PersonAdapter.PersonViewHolder>() { textView.text = "Bouton cliqué !"
class PersonViewHolder(itemView: View) : }
RecyclerView.ViewHolder(itemView) { }
val name = itemView.textViewName }
val age = itemView.textViewAge
}

override fun onCreateViewHolder(parent: ViewGroup,


viewType: Int): PersonViewHolder { ▶ Afficher une image
val view =
LayoutInflater.from(parent.context).inflate(R.layout.item_p val imageView: ImageView = findViewById(R.id.imageView)
erson, parent, false) val imgFile =
return PersonViewHolder(view) File("/storage/emulated/0/Download/sample_image.jpg")
} if (imgFile.exists()) {
val bitmap =
override fun onBindViewHolder(holder: PersonViewHolder, BitmapFactory.decodeFile(imgFile.absolutePath)
position: Int) { imageView.setImageBitmap(bitmap)
val person = personList[position] }
holder.name.text = person.name
holder.age.text = "Age: ${person.age}" // Avec Glide
} val url = "https://example.com/image.jpg"
Glide.with(this).load(url).into(imageView)
override fun getItemCount(): Int = personList.size
}

▶ Service
class MyService : Service() {
▶ CustomAdapter (ListView) override fun onBind(intent: Intent?): IBinder? = null
val listView: ListView = findViewById(R.id.listView)
val adapter = CustomAdapter(this, listOf("Item 1", "Item override fun onStartCommand(intent: Intent?, flags:
2", "Item 3")) Int, startId: Int): Int {
listView.adapter = adapter Toast.makeText(this, "Service Started",
Toast.LENGTH_SHORT).show()
return START_STICKY
}

▶ ArrayAdapter (ListView) override fun onDestroy() {


super.onDestroy()
val listView: ListView = findViewById(R.id.listView) Toast.makeText(this, "Service Destroyed",
val data = arrayOf("Item 1", "Item 2", "Item 3") Toast.LENGTH_SHORT).show()
val adapter = ArrayAdapter(this, }
android.R.layout.simple_list_item_1, data) }
listView.adapter = adapter

▶ BroadcastReceiver
▶ ViewModel
class NetworkChangeReceiver : BroadcastReceiver() {
class SimpleViewModel : ViewModel() { override fun onReceive(context: Context, intent:
val text = MutableLiveData<String>() Intent) {
init { text.value = "Bonjour, ViewModel !" } val connectivityManager =
context.getSystemService(Context.CONNECTIVITY_SERVICE) as
fun updateText(newText: String) { ConnectivityManager
text.value = newText val networkInfo: NetworkInfo? =
} connectivityManager.activeNetworkInfo
} if (networkInfo?.isConnected == true) {
Toast.makeText(context, "Connected to the
viewModel.text.observe(this, Observer { newText -> internet", Toast.LENGTH_SHORT).show()
textView.text = newText } else {
}) Toast.makeText(context, "Disconnected from the
internet", Toast.LENGTH_SHORT).show()
button.setOnClickListener { }
viewModel.updateText("Le texte a changé !") }
} }

val networkChangeReceiver = NetworkChangeReceiver()


val intentFilter =
IntentFilter("android.net.conn.CONNECTIVITY_CHANGE")
registerReceiver(networkChangeReceiver, intentFilter)
WorkerParameters) : Worker(appContext, workerParams) {
override fun doWork(): Result {
try {
▶ Notification // traitement
} catch (e: Exception) {
val CHANNEL_ID = "example_channel" return Result.failure()
} return Result.success()
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
val channel = NotificationChannel(CHANNEL_ID, "Exemple
de notifications", NotificationManager.IMPORTANCE_DEFAULT)
val notificationManager =
getSystemService(NotificationManager::class.java) ▶ Handler
notificationManager.createNotificationChannel(channel)
} val handler = Handler(Looper.getMainLooper())
handler.postDelayed({
val notification = NotificationCompat.Builder(this, // Code à exécuter après 1 seconde
CHANNEL_ID) }, 1000)
.setSmallIcon(android.R.drawable.ic_dialog_info)
.setContentTitle("Titre de la notification")
.setContentText("Voici le contenu de la notification.")
.setPriority(NotificationCompat.PRIORITY_DEFAULT)
.build() ▶ EasyPermissions
val notificationManager = class MainActivity : AppCompatActivity(),
NotificationManagerCompat.from(this) EasyPermissions.PermissionCallbacks {
notificationManager.notify(1, notification)
private val REQUEST_CODE_CAMERA = 100

override fun onCreate(savedInstanceState: Bundle?) {


super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
▶ Intent (Navigation entre activités) checkCameraPermission()
// Depuis 1ère Activity }
val intent = Intent(this, MainActivity::class.java)
intent.putExtra("data1", "valeur") private fun checkCameraPermission() {
intent.putExtra("data2", 123) if (EasyPermissions.hasPermissions(this,
startActivity(intent) Manifest.permission.CAMERA)) {
Toast.makeText(this, "Permission déjà
// Dans 2ème Activity accordée", Toast.LENGTH_SHORT).show()
val data1 = intent.getStringExtra("data1") } else {
val data2 = intent.getIntExtra("data2", 0) EasyPermissions.requestPermissions(
this,
"Nous avons besoin de la caméra pour
prendre des photos",
REQUEST_CODE_CAMERA,
Manifest.permission.CAMERA
▶ JobScheduler )
val jobScheduler = }
getSystemService(Context.JOB_SCHEDULER_SERVICE) as }
JobScheduler
val componentName = ComponentName(this, override fun onPermissionsGranted(requestCode: Int,
MyJobService::class.java) perms: MutableList<String>) {
val jobInfo = JobInfo.Builder(1, componentName) Toast.makeText(this, "Permission accordée",
.setRequiredNetworkType(JobInfo.NETWORK_TYPE_UNMETERED) Toast.LENGTH_SHORT).show()
.setRequiresCharging(true) }
.build()
jobScheduler.schedule(jobInfo) override fun onPermissionsDenied(requestCode: Int,
perms: MutableList<String>) {
class MyJobService : JobService() { if
override fun onStartJob(params: JobParameters): Boolean (EasyPermissions.somePermissionPermanentlyDenied(this,
= true perms)) {
override fun onStopJob(params: JobParameters): Boolean Toast.makeText(this, "Permission refusée",
= true Toast.LENGTH_SHORT).show()
} }
}
}

▶ WorkManager
val constraints = Constraints.Builder()
.setRequiredNetworkType(NetworkType.CONNECTED)
.setRequiresBatteryNotLow(true)
.build()

val workRequest = OneTimeWorkRequestBuilder<MyWorker>()


.setConstraints(constraints)
.build()

WorkManager.getInstance(this).enqueue(workRequest)

val periodicWork = PeriodicWorkRequestBuilder<MyWorker>(15,


TimeUnit.MINUTES).build()
WorkManager.getInstance(this).enqueue(periodicWork)

class MyWorker(appContext: Context, workerParams:

You might also like