Advertisement
eveeeeef21

MyWorker Class

Jan 26th, 2024
99
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Kotlin 4.94 KB | Source Code | 0 0
  1. package com.example.myworkmanager
  2.  
  3. import android.app.NotificationChannel
  4. import android.app.NotificationManager
  5. import android.content.Context
  6. import android.os.Build
  7. import android.os.Looper
  8. import android.util.Log
  9. import androidx.core.app.NotificationCompat
  10. import androidx.work.Worker
  11. import androidx.work.WorkerParameters
  12. import com.loopj.android.http.AsyncHttpResponseHandler
  13. import com.loopj.android.http.SyncHttpClient
  14. import com.squareup.moshi.Moshi
  15. import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory
  16. import cz.msebera.android.httpclient.Header
  17. import org.json.JSONObject
  18. import java.text.DecimalFormat
  19.  
  20. class MyWorker(context: Context, workerParams: WorkerParameters) : Worker(context, workerParams) {
  21.  
  22.     companion object {
  23.         private val TAG = MyWorker::class.java.simpleName
  24.         const val EXTRA_CITY = "city"
  25.         const val NOTIFICATION_ID = 1
  26.         const val CHANNEL_ID = "channel_01"
  27.         const val CHANNEL_NAME = "dicoding channel"
  28.     }
  29.     private var resultStatus: Result? = null
  30.  
  31.     override fun doWork(): Result {
  32.         val dataCity = inputData.getString(EXTRA_CITY)
  33.         return getCurrentWeather(dataCity)
  34.     }
  35.  
  36.     private fun getCurrentWeather(city: String?): Result {
  37.         Log.d(TAG, "getCurrentWeather: Mulai.....")
  38.         Looper.prepare()
  39.         val client = SyncHttpClient()
  40.         val url = "https://api.openweathermap.org/data/2.5/weather?q=$city&appid=${BuildConfig.APP_ID}"
  41.         Log.d(TAG, "getCurrentWeather: $url")
  42.         client.post(url, object : AsyncHttpResponseHandler() {
  43.             override fun onSuccess(statusCode: Int, headers: Array<Header?>?, responseBody: ByteArray) {
  44.                 val result = String(responseBody)
  45.                 Log.d(TAG, result)
  46.                 try {
  47. //                    Hapus kode ini
  48. //                    val responseObject = JSONObject(result)
  49. //                    val currentWeather: String = responseObject.getJSONArray("weather").getJSONObject(0).getString("main")
  50. //                    val description: String = responseObject.getJSONArray("weather").getJSONObject(0).getString("description")
  51. //                    val tempInKelvin = responseObject.getJSONObject("main").getDouble("temp")
  52.  
  53.                     val moshi = Moshi.Builder()
  54.                         .addLast(KotlinJsonAdapterFactory())
  55.                         .build()
  56.                     val jsonAdapter = moshi.adapter(Response::class.java)
  57.                     val response = jsonAdapter.fromJson(result)
  58.  
  59.                     response?.let {
  60.                         val currentWeather = it.weatherList[0].main
  61.                         val description = it.weatherList[0].description
  62.                         val tempInKelvin = it.main.temperature
  63.  
  64.                         val tempInCelsius = tempInKelvin - 273
  65.                         val temperature: String = DecimalFormat("##.##").format(tempInCelsius)
  66.                         val title = "Current Weather in $city"
  67.                         val message = "$currentWeather, $description with $temperature celsius"
  68.                         showNotification(title, message)
  69.                     }
  70.                     Log.d(TAG, "onSuccess: Selesai.....")
  71.                     resultStatus = Result.success()
  72.                 } catch (e: Exception) {
  73.                     showNotification("Get Current Weather Not Success", e.message)
  74.                     Log.d(TAG, "onSuccess: Gagal.....")
  75.                     resultStatus = Result.failure()
  76.                 }
  77.             }
  78.             override fun onFailure(statusCode: Int, headers: Array<Header?>?, responseBody: ByteArray?, error: Throwable) {
  79.                 Log.d(TAG, "onFailure: Gagal.....")
  80.                 // ketika proses gagal, maka jobFinished diset dengan parameter true. Yang artinya job perlu di reschedule
  81.                 showNotification("Get Current Weather Failed", error.message)
  82.                 resultStatus = Result.failure()
  83.             }
  84.         })
  85.         return resultStatus as Result
  86.     }
  87.     private fun showNotification(title: String, description: String?) {
  88.         val notificationManager = applicationContext.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
  89.         val notification: NotificationCompat.Builder = NotificationCompat.Builder(applicationContext, CHANNEL_ID)
  90.             .setSmallIcon(R.drawable.baseline_notifications_24)
  91.             .setContentTitle(title)
  92.             .setContentText(description)
  93.             .setPriority(NotificationCompat.PRIORITY_HIGH)
  94.             .setDefaults(NotificationCompat.DEFAULT_ALL)
  95.         if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
  96.             val channel = NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH)
  97.             notification.setChannelId(CHANNEL_ID)
  98.             notificationManager.createNotificationChannel(channel)
  99.         }
  100.         notificationManager.notify(NOTIFICATION_ID, notification.build())
  101.     }
  102. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement