Skip to content

Instantly share code, notes, and snippets.

@m07med176
Created February 17, 2023 23:10
Show Gist options
  • Save m07med176/4f0b1b560a0a91edcd93645210dcd238 to your computer and use it in GitHub Desktop.
Save m07med176/4f0b1b560a0a91edcd93645210dcd238 to your computer and use it in GitHub Desktop.
Lab2
object Constants {
const val IMAGE_KEY = "IMAGE_KEY"
const val ACTION_KEY = "ACTION_KEY"
}
private const val TAG = "DownloadService"
class DownloadService : Service() {
override fun onCreate() {
super.onCreate()
downloadImage()
}
private fun downloadImage() {
RetrofitInstance.getApi().getImage().enqueue(object : Callback<ResponseBody> {
override fun onResponse(
call: Call<ResponseBody>,
response: Response<ResponseBody>,
) {
if (response.isSuccessful){
val file = File(applicationContext.cacheDir,"myImage.jpg")
val fos = FileOutputStream(file)
try {
fos.write(response.body()?.bytes())
val myImage = file.toURI()
Log.d(TAG, "onResponse Image success: ${myImage.toString()}")
sendToBroadCast(myImage.toString())
}catch (e: IOException){
Log.d(TAG, "onFailure: Error happend ${e.message}")
}
}
}
override fun onFailure(call: Call<ResponseBody>, t: Throwable) {
Log.d(TAG, "onFailure: ${t.message}")
}
})
}
override fun onDestroy() {
super.onDestroy()
Log.d(TAG, "onDestroy: ")
}
override fun onBind(intent: Intent): IBinder? = null
private fun sendToBroadCast(imageUrl:String) {
val braodCastIntent= Intent()
braodCastIntent.action = Constants.ACTION_KEY
braodCastIntent.flags = Intent.FLAG_INCLUDE_STOPPED_PACKAGES
braodCastIntent.putExtra(Constants.IMAGE_KEY,imageUrl)
sendBroadcast(braodCastIntent)
}
}
class ImageActivity : AppCompatActivity() {
lateinit var imageShow:ImageView
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_image)
imageShow = findViewById(R.id.image_show)
if (intent.getStringExtra(Constants.IMAGE_KEY)!=null){
val myImage = intent.getStringExtra(Constants.IMAGE_KEY) as Uri
imageShow.setImageURI(myImage)
}
}
}
private const val TAG = "MainActivity"
class MainActivity : AppCompatActivity() {
lateinit var editText: EditText
lateinit var button: Button
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
editText = findViewById(R.id.imageUrl)
button = findViewById(R.id.button)
val myImageReciever = MyImageReciever(this)
val intentFilter = IntentFilter(Constants.ACTION_KEY)
registerReceiver(myImageReciever,intentFilter )
button.setOnClickListener {
val myUrl = editText.text.toString().trim()
if (myUrl.isEmpty()) return@setOnClickListener
val service = Intent(this@MainActivity,DownloadService::class.java)
startService(service)
}
}
}
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:networkSecurityConfig="@xml/network_security_config"
android:dataExtractionRules="@xml/data_extraction_rules"
android:fullBackupContent="@xml/backup_rules"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:supportsRtl="true"
android:theme="@style/Theme.DownloadImage"
tools:targetApi="31">
<receiver
android:name=".MyImageReciever"
android:enabled="true"
android:exported="true">
</receiver>
<service
android:name=".DownloadService"
android:enabled="true"
android:exported="true" />
<activity
android:name=".ImageActivity"
android:exported="false" />
<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
private const val TAG = "MyImageReciever"
class MyImageReciever(val activity: Activity) : BroadcastReceiver() {
override fun onReceive(context: Context, intent: Intent) {
if (intent.getStringExtra(Constants.IMAGE_KEY)!=null){
val imageUrl = intent.getStringExtra(Constants.IMAGE_KEY)
Log.d(TAG, "onReceive: $imageUrl")
val intentImage = Intent(activity,ImageActivity::class.java)
intentImage.putExtra(Constants.IMAGE_KEY,imageUrl?.toUri())
activity.startActivity(intentImage)
}
}
}
interface ImageDownloader{
@GET("1.jpg")
fun getImage():Call<ResponseBody> //@Path("imageName") imageName:String
}
class RetrofitInstance {
companion object{
fun getApi():ImageDownloader{
val retrofit = Retrofit.Builder()
.baseUrl("https://i.dummyjson.com/data/products/1/")
.build()
return retrofit.create(ImageDownloader::class.java)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment