728x90 전체 글520 안드로이드 WokrManger 실행 조건 설정(Constraints) Worker import android.content.Context import android.util.Log import androidx.work.Worker import androidx.work.WorkerParameters import java.lang.Exception class UploadWorker(context: Context,params:WorkerParameters) : Worker(context,params) { override fun doWork(): Result { try { for (i in 0..600000) { Log.i("MYTAG", "Uploading $i") } return Result.success() } catch (e:Exception){ return Result... 2022. 12. 1. 안드로이드 WorkManager Worker 상태 업데이트 Worker import android.content.Context import android.util.Log import androidx.work.Worker import androidx.work.WorkerParameters import java.lang.Exception class UploadWorker(context: Context,params:WorkerParameters) : Worker(context,params) { override fun doWork(): Result { try { for (i in 0..600000) { Log.i("MYTAG", "Uploading $i") } return Result.success() } catch (e:Exception){ return Result... 2022. 12. 1. 안드로이드 Notification Reply Action reply action 추가 package com.anushka.notificationdemo import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import androidx.core.app.NotificationCompat imp.. 2022. 11. 28. 안드로이드 Notification Action Button action2, action3 을 만들고 NotificationCompat.Builder 에서 addAction으로 값을 넣어준다 package com.anushka.notificationdemo import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widg.. 2022. 11. 28. 안드로이드 Notification Tap Action package com.anushka.notificationdemo import android.app.NotificationChannel import android.app.NotificationManager import android.app.PendingIntent import android.content.Context import android.content.Intent import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import androidx.core.app.NotificationCompat class MainActivity .. 2022. 11. 28. 안드로이드 기본 Notification import android.app.NotificationChannel import android.app.NotificationManager import android.content.Context import android.os.Build import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.widget.Button import androidx.core.app.NotificationCompat class MainActivity : AppCompatActivity() { private val channelID = "com.anushka.notificationdemo.channel1" private var .. 2022. 11. 28. 안드로이드 Retrofit TimeOut import com.google.gson.GsonBuilder import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory import java.util.concurrent.TimeUnit class RetrofitInstance { companion object { val BASE_URL: String = "https://jsonplaceholder.typicode.com" val interceptor = HttpLoggingInterceptor().apply { this.level = Htt.. 2022. 11. 28. 안드로이드 Retrofit Intercepter 적용 import com.google.gson.GsonBuilder import okhttp3.OkHttpClient import okhttp3.logging.HttpLoggingInterceptor import retrofit2.Retrofit import retrofit2.converter.gson.GsonConverterFactory class RetrofitInstance { companion object { val BASE_URL: String = "https://jsonplaceholder.typicode.com" val interceptor = HttpLoggingInterceptor().apply { this.level = HttpLoggingInterceptor.Level.BODY } val .. 2022. 11. 28. 안드로이드 retrofit builder moshi builder를 넣어줘야 한다. 안 넣어주면 json object mapping시 매핑 실패 package com.ej.aboutme.di.module import com.ej.aboutme.api.AboutMeApi import com.ej.aboutme.api.AboutMeFetchr import com.ej.aboutme.util.ServerInfo import com.squareup.moshi.Moshi import com.squareup.moshi.kotlin.reflect.KotlinJsonAdapterFactory import dagger.Module import dagger.Provides import dagger.hilt.InstallIn import dagger.hilt.co.. 2022. 11. 27. MVVM패턴에서 ViewModel의 Event 전달하기 Event.kt open class Event(private val content: T) { var hasBeenHandled = false private set // Allow external read but not write /** * Returns the content and prevents its use again. */ fun getContentIfNotHandled(): T? { return if (hasBeenHandled) { null } else { hasBeenHandled = true content } } /** * Returns the content, even if it's already been handled. */ fun peekContent(): T = content } Viw.. 2022. 11. 26. 안드로이드 recycler AdapterView data binding 적용 list_item.xml ReyclerViewAdapter import android.view.LayoutInflater import android.view.ViewGroup import androidx.databinding.DataBindingUtil import androidx.recyclerview.widget.RecyclerView import com.anushka.roomdemo.databinding.ListItemBinding import com.anushka.roomdemo.db.Subscriber class MyRecyclerViewAdapter(private val subscribersList: List) : RecyclerView.Adapter() { override fun onCrea.. 2022. 11. 26. 안드로이드 코루틴 async, await import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import android.widget.Toast import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers.IO import kotlinx.coroutines.Dispatchers.Main import kotlinx.coroutines.async import kotlinx.coroutines.delay import kotlinx.coroutines.launch class MainActivity : AppCompatActivity() { override.. 2022. 11. 25. 안드로이드 코루틴 실행중인 Scope 변경 withContext로 변경한다 withContext사용시 외부 변수 사용 불가능 import androidx.appcompat.app.AppCompatActivity import android.os.Bundle import android.util.Log import kotlinx.android.synthetic.main.activity_main.* import kotlinx.coroutines.CoroutineScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class MainActivity : AppCompatActivity() { private .. 2022. 11. 25. 안드로이드 저장소 Internal Storage - Permission 없이 사용 가능 - 저장된 파일은 자신의 앱에서만 액세스 가능 - 앱을 지우면 파일도 함께 소멸 - 캐시파일의 개념과 비슷 External Storage - Permission 권한 필요 - SD카드 등의 외부저장소에 파일을 저장 - 스마트폰의 저장소 또한 이곳에 포함 (ex. Download 폴더 등) - getExternalStorageState() 함수를 호출하여 외부 저장소가 사용 가능한지에 대해 확인 //외부 저장소(External Storage)가 마운트(인식) 되었을 때 동작 //getExternalStorageState() 함수를 통해 외부저장장치가 Mount 되어 있는지를 확인 if(Environment.getExternalStorag.. 2022. 11. 16. 안드로이드 Corutine, Retrofit을 활용한 비동기 네트워킹 처리 중 에러 핸들링 개요 안드로이드에서 비동기 처리를 하는 대표적인 방법 중 하나는 Retrofit과 Coroutine을 활용하는 것이다. 이 과정에서 다양한 네트워크 오류 상황에 대응하기 위한 다양한 에러 핸들링 방법에 대해 소개하는 게시글이다. 1. try.. catch 블럭 가장 전통적인 방법이다. 단순히 네트워킹이 필요한 위치에 try..catch 블럭을 활용하면 된다. fun updateProfile(file: File) = viewModelScope.launch(Dispatchers.IO) { try{ repository.updateProfile(file) }catch(e: Exception){ //에러 처리 코드 } } 가장 흔하고 간단한 방법이지만 한 앱에서 여러 개의 네트워킹 처리 함수가 존재할텐데, 각 함.. 2022. 11. 3. Single Activity Architecture (SAA) SAA(Single Activity Architecture)란 단일 혹은 아주 적은 개수의 Activity만 사용하고 모두 Fragment로 구현한 구조이다. 2018년 구글 I/O에서 언급된 개념이다 Activity는 Fragment에 비해 상대적으로 무겁기 때문에 메모리나 속도 방면에서 Fragment를 사용하는 것이 훨씬 더 이득이다. 또한 비즈니스 로직을 Fragment 단위로 분리하여 의존성을 줄인다던지, Activity보다 유연한 UI 디자인을 지원하는 등 Fragment를 사용하는 이유는 상당히 많다고 볼 수 있다. 장점 1. Activity에 비행 상대적으로 가벼움 2. 데이터 공유 3. UI의 이점 4. 관심사의 분리가 편함 단점 1. Fragment간의 동작이 비동기로 처리되기 때문에 .. 2022. 11. 2. Android Intent Flag Android 에서 Intent를 공부하다보면 단순히 Activity 간의 이동이 아닌 Stack 구조를 가지고 있는 Task를 만나게 된다. "오늘은 이 Task를 어떻게 활용하면 좋을까?" 에 대한 학슥하고자 한다. 그내용이 바로 Flag이다. 1.왜 사용하는가? Activity를 호출하다보면 Activity에 대해 중복 문제가 발생하곤 한다. 이때 중복을 방지하거나 Activity에 대한 흐름을 제어하고 싶을 때 쓰인다. 2. Task Stack 구조로 되어 있으며, 어플리케이션에서 실행되는 Activity를 보관하고 관리하는 역할을 담당한다. 3. 어떻게 사용해야 하는가 3-1. AndroidManifest에서 제어 standard : Stack 중 어느 곳에나 위치 할 수 있으며, 여러개의 인스.. 2022. 11. 2. configChanges 설정 변경이 발생됐을때 지금의 상태를 지속하면서 화면 구성만 변경할 수 있는방법이다 Manifest에서 수정할 수 있는 Activity별 configChanges는 그런 편의성을 제공한다. Activity의 configChanges값에 "변경될 수 있는 설정"드를 지정해주면, 이 설정들이 변경되더라도 액티비티가 재시작되지않는다. 이렇게 하면 onDestroy() -> onCreate() 대신에 onConfigurationChanged() 메서드가 실행되어 view가 유지된다. 설정방법 Manifest.xml에 activity에 설정 onConfigurationChanged() configChanges에 설정해 둔 값들에 대해서는 onDestroy() -> onCrate() 대신 onConfiguratio.. 2022. 11. 2. QUERY_ALL_PACKAGES QUERY_ALL_PACKAGE권한은 해당 기기에 설치된 애플리케이션 전부를 확인할 수 있게 해주는데, 구글 측에서 위험성이 높거나 민감한 권한으로 간주해 백신 앱, 파일 관리자 등의 허용 이유를 제출해야한다. 이 권한을 사용하려면 앱의 아래의 혀옹되는 사용 범위에 속해야 하며 기기의 모든 앱을 검색하기 위한 핵심 목적이 있어야 한다. 2022. 11. 2. Fragment 생성자 조건 Fragment 생성시 newInstance() 사용하는 이유 1. 프래그먼트 재성성(화면 회전과 같은)시 빈 생성자가 있어야 한다 2. 재생성시 받아온 데이터를 유지하기 위해서 사용한다. 자주사용하는코드 companion object { private const val ARG_PARAM1 = "param1" private const val ARG_PARAM2 = "param2" @JvmStatic fun newInstance(param1: String, param2: String) = MainFragment().apply { arguments = Bundle().apply { putString(ARG_PARAM1, param1) putString(ARG_PARAM2, param2) } } } newIn.. 2022. 11. 1. 안드로이드 뷰 그려지는 과정 뷰가 그려지는 건 레이아웃 트리의 루트노드 부터 시작하게 된다. 레이아웃 트리는 말 그대로 레이아웃에 있는 뷰 그룹이나 뷰 들을 트리행태로 나타난건데 예를 들면 이런 구조로 되어 있다면 이를 오른쪽 처럼 전위순회 하면서 그려지는 방식이다. 레이아웃을 그리는 과정은 측정패스(Measure Pass)와 레이아웃패스(Layout Pass)가 있다. Measure Pass는 OnMeasure 메소드를 호출하는데 뷰의 크기를 결정하기 위한 메소드 이다. Layout Pass는 OnLayout메소드를 호출하는데 뷰의 위치를 결정하기 위해 호출되는 메소드 이다. 만약 저 위 상태의 레이아웃 호출되는 순서를 보면 오른쪽 표처럼 전위순회하면서 onMeasure 메소드를 호출하고 이후 루트노드부터 다시 onLayout 메.. 2022. 11. 1. 안드로이드 앱 서명 안드로이드 앱 서명이란 안드로이드의 모든 APK는 앱 서명 키를 사용하여 서명되어야 설치 될 수 있다. 안드로이드는 앱 업데이트가 기기에 설치된 앱의 업데이트인지 확인한다. 안드로이드는 앱 서명을 사용하여 앱 업데이트를 위한 신규 APK가 기존에 이미 설치된 앱과 같은곳(개발자, 배포처 등)으로부터 생성되어 진 것인지 확인 서명 검증을 통과하는 경우에만 앱 설치를 허용하여, 악성 앱 업데이트 위험을 줄인다. 전통적인 앱 서명 방식 전통적인 앱 서명 방식은 개발자가 앱 서명 키를 생성화고 앱 설치 검증을 위한 인증서를 직접 생성하여 업로드하는 자체 서명 키 사용 및 관리 방식이다. 이때의 사명값은 사용자의 단말에 설치될 때 검증을 위해 사용된다. 구글 플레이스토어와 같은 앱 스토어에 개발자는 앱(APK)을.. 2022. 10. 31. 안드로이드 앱 번들 APK 일반적인 APK는 APK 파일 하나를 통해 많은 디바이스의 호환을 지원한다. 그렇다 보니 APK 자체에 여러개의 ABI(Android Binary Interface)를 포함하게 되며, APK 파일의 크기는 커질 수 밖에 없다. APK 파일이 커지는 경우 스토어를 통해 앱을 다운받는 사용자에게 안좋은 경험을 제공할 수 밖에 없다. 앱을 다운받는데 시간이 오래걸린다. 앱 번들 (AAB) APK의 용랑 문제를 해결하기 위해 개발된게 AAB(Android Abb Bundle)이다. 기본 통빌드(APK)혹은 다중 APK를 통해 사용자에게 앱을 지원하는 방식을 사용했다면, 현재는 AAB를 통해 좀 더 경량화된 앱을 제공할 수 있다. 발생 배경 구글 플레이 앱 서명 기능이 출시되며 구글은 앱을 사이닝하는 과정.. 2022. 10. 31. 안드로이드 RecyclerView layout 설정 1. LinearLayoutManager 1-1. 코드에서 지정 layoutManager = LinearLayoutManager(context) 1-2. xml에서 지정 2. GridLayoutManager 2-1. 코드에서 지정 layoutManager = GridLayoutManager(view.context, 2 /* 열 갯수 */) 2-2. xml에서 지정 https://jamie-dev.tistory.com/57 [Android] RecyclerView의 LayoutManager를 지정하는 방법 1. LinearLayoutManager 1-1. 코드에서 지정 layoutManager = LinearLayoutManager(context) 1-2. xml에서 지정 2. GridLayoutManag.. 2022. 10. 28. 안드로이드 layout 남은 영역 채우기 orientation이 horizontal인 LinearLayout에서 양 끝에 width가 80dp인 버튼을 배치하고, 가운데의 남은 공간을 모두 사용하여(꽉 채워서) textview를 배치하고 싶을 때, 어플리케이션이 실행되는 기기의 화면의 크기가 얼마나 클지 예상할 수 없으므로, 임의의 값으로 설정하게 되면 기기의 화면 크기에 따라 textview가 원하는것보다 작거나, 화면의 크기가 작은 경우는 오히려 오른쪽의 버튼을 가려버릴 수도 있게 됩니다. 그저 남은 공간을 꽉 채워서 배치하고 싶은 것이라면, 위의 코드 예시와 같이 나머지 view들은 layout_weight값을 0으로 설정하고, 텍스트뷰의 layout_weight을 1로 설정하고, layout_width는 fill_parent로 설정해주면.. 2022. 10. 28. 안드로이드 RxJava : Subject, PublicshSubject, BehabiorSubject Subject RxJava에서 Subject 클래스는 구독하고 있는 관찰자(Observer)에게 새로운 값을 전달 할 때 사용하는 클래스다. 따로 Observable로 새로운 값을 만들 필요 없이 Subject 객체에 내장된 onNext 함수로 새로운 값을 옵저버에게 전달할 수 있기 때문에 짧은 코드로도 reactivi하게 구한하는 것이 가능하다. class Person { var publishName: PublishSubject = PublishSubject.create() } val person = Person() person.publishName.subscribe { Log.d(TAG, "publishName: " + it) } person.publishName.onNext("selfish") pe.. 2022. 10. 27. 코틀린 Companion object, 자바 static 차이 자바 static static이 붙은 변수와 메소드를 각각 클래스 변수, 클래스 메소드라 부른다. static이 붙지 않은 클래스 내의 변수와 메소드는 각각 인스턴스 변수, 인스턴스 메소드라 한다. static이 붙은 멤버는 클래스가 메모리에 적재될 때 자동으로 함께 생성되므로 인스턴스 생성 없이도 클래스명 다음에 점(.)을 쓰면 바로 참조할 수 있다. Companion object는 static이 아니고 객체이다 코틀린 companion object는 static이 아니며 사용하는 입장에서 static으로 동작하는 것처럼 보일 뿐입니다. companion object는 MyClass클래스가 메모리에 적재되면서 함께 생성되는 동반되는 객체이다. (클래스와 동반자 느낌) Companion object의 멤.. 2022. 10. 27. 안드로이드 Dalvik과 ART 작동방식 APK 컴파일 앱을 빌드하고 APK를 생성할 때 해당 APK의 일부는 .dex 파일이다 .dex 파일에는 사용하는 모든 라이브러리를 포함하여 앱의 소스코드가 포함되어있음 .dex 파일은 소프트웨어 인터프리터용으로 설계된 저수준 코드인 바이트코드로 작성되어있다. 사용자가 앱을 실행하면 .dex 파일에 작성된 바이트코드가 ART에 의해 기계어 코드로 변환 Dalvik (=Lollipop) ART에서는 AOT(Ahead Of Time) 컴파일이라는 전략을 사용했음 AOT 전략은 앱을 실행하기 전에 컴파일되어 앱이 실행될 때 기계어 코드가 이미 준비되어있는 상황이다. 장점 1. 기계어 코드 실행 속도가 JIT보다 약 20배 빠르기때문에 런타임 성능이 크게 향상 단점 1. Dalvik보다 씬 많은 RAM을 사용 .. 2022. 10. 26. RecyclerView XML에서 미리보기 tools:listitem 에 보여줄 xml을 선택해주면 된다. recyclerview가 수평으로 데이터를 보여줄 경우 tools:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" tools:listitem="@layout/group_member_card_item" 적용시켜주면 미리보기 화면에 수평으로 표시된다 2022. 10. 19. 실전! 코틀린과 스프링 부트로 도서관리 애플리케이션 개발하기 (Java 프로젝트 리팩토링) 2022-10-12 완강 2022. 10. 12. 이전 1 2 3 4 5 ··· 18 다음 728x90