<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Mert Melih Aytemur on Medium]]></title>
        <description><![CDATA[Stories by Mert Melih Aytemur on Medium]]></description>
        <link>https://medium.com/@aytemurmertmelih?source=rss-b3e02897b105------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*08CI68LatX-fSfXBBQMvJQ.jpeg</url>
            <title>Stories by Mert Melih Aytemur on Medium</title>
            <link>https://medium.com/@aytemurmertmelih?source=rss-b3e02897b105------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 23:57:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@aytemurmertmelih/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[ Deep Copy vs Shallow Copy in Kotlin — What Developers Should Really Know]]></title>
            <link>https://medium.com/@aytemurmertmelih/deep-copy-vs-shallow-copy-in-kotlin-what-developers-should-really-know-e035f196863c?source=rss-b3e02897b105------2</link>
            <guid isPermaLink="false">https://medium.com/p/e035f196863c</guid>
            <dc:creator><![CDATA[Mert Melih Aytemur]]></dc:creator>
            <pubDate>Wed, 12 Nov 2025 13:56:17 GMT</pubDate>
            <atom:updated>2025-11-12T13:56:17.703Z</atom:updated>
            <content:encoded><![CDATA[<h3>🧠 Deep Copy vs Shallow Copy in Kotlin — What Developers Should Really Know</h3><p>When working with Kotlin (or any object-oriented language), we often face situations where we need to <em>duplicate</em> an object — whether to modify it safely, keep a snapshot of state, or avoid unexpected side effects.</p><p>But not all copies are created equal.</p><p>In Kotlin, as in many languages, there are two main types of object copying: <strong>shallow copy</strong> and <strong>deep copy</strong>.<br>Understanding the difference between them can save you from subtle and frustrating bugs.</p><h3><strong>🪞 The Core Idea</strong></h3><p>When you copy an object, you’re trying to create a <strong>new instance</strong> that looks like the original.<br> But the real question is:</p><blockquote><em>“Do we copy </em>only the object itself<em>, or </em>everything inside it<em>, recursively?”</em></blockquote><p>That’s what separates <strong>shallow</strong> from <strong>deep</strong> copying.</p><h3>⚡ Shallow Copy: Quick but Risky</h3><p>A <strong>shallow copy</strong> creates a new object but <strong>copies only the top-level fields</strong>.<br>If the object has properties that are references to other objects, both the original and the copy will <strong>share</strong> those references.</p><p>Let’s see this in Kotlin:</p><pre>data class Address(var city: String)<br>data class User(var name: String, var address: Address)<br><br>fun main() {<br>    val user1 = User(&quot;Mert&quot;, Address(&quot;Istanbul&quot;))<br>    val user2 = user1.copy() // Kotlin&#39;s data class copy() is shallow<br><br>    user2.address.city = &quot;Ankara&quot;<br><br>    println(user1.address.city) // Output: &quot;Ankara&quot; 😱<br>}</pre><p>Even though user1 and user2 are different User objects, they <strong>share the same Address instance</strong>.<br> So changing one affects the other.</p><h3>🌊 Deep Copy: True Independence</h3><p>A <strong>deep copy</strong>, on the other hand, duplicates <em>everything inside</em> the object — including all referenced objects.<br> This means the new instance is <strong>completely independent</strong> from the original.</p><p>Example:</p><pre>fun User.deepCopy(): User {<br>    return User(<br>        name = this.name,<br>        address = Address(this.address.city) // manually clone nested object<br>    )<br>}<br><br>fun main() {<br>    val user1 = User(&quot;Mert&quot;, Address(&quot;Istanbul&quot;))<br>    val user2 = user1.deepCopy()<br><br>    user2.address.city = &quot;Ankara&quot;<br><br>    println(user1.address.city) // Output: &quot;Istanbul&quot; ✅<br>}</pre><p>Now user1 and user2 don’t share anything — they are entirely separate in memory.</p><h4>⚖️ Comparison Table</h4><pre>| Aspect            | Shallow Copy                | Deep Copy                      |<br>| ----------------- | --------------------------- | ------------------------------ |<br><br>| What is copied    -&gt; Only top-level fields       | All nested objects recursively |<br>                   <br>| Performance       -&gt; Fast                        | Slower    <br>                  <br>| Memory usage      -&gt; Lower                       | Higher     <br>                   <br>| Independence      -&gt; Changes may affect original | Fully independent    <br>                   <br>| Typical in Kotlin -&gt; `copy()` (default)          | Must implement manually        |</pre><h4>💪 Advantages of Deep Copy</h4><ul><li>✅ <strong>True isolation</strong> — changes in one object don’t affect the other.</li><li>✅ <strong>Safe state management</strong> — ideal when working with mutable nested data.</li><li>✅ <strong>Reliable immutability patterns</strong> — helps maintain data consistency in concurrent or UI-driven systems (like Jetpack Compose states).</li></ul><h4>⚠️ Disadvantages of Deep Copy</h4><ul><li>❌ <strong>Performance cost</strong> — creating many deep copies can be expensive in time and memory.</li><li>❌ <strong>Implementation complexity</strong> — you often have to manually write copy logic for nested objects.</li><li>❌ <strong>Risk of recursion</strong> — circular references (A → B → A) can cause infinite loops if not handled carefully.</li></ul><h4>🔥 Common Risks and Pitfalls</h4><ul><li><strong>Accidental shared references</strong><br> You think you cloned an object, but it’s still pointing to the same data.<br> → This leads to bugs that are <em>hard to trace</em> because changes appear “magically” in the original.</li><li><strong>Unnoticed performance hits</strong><br> Overusing deep copies (for example, in large lists or state updates) can cause lag or memory bloat.</li><li><strong>Hidden mutation leaks</strong><br> Especially in concurrent or reactive systems, a shallow copy can leak internal state to other threads or views.</li></ul><h3>🧩 Best Practices</h3><ul><li>Prefer <strong>immutable data classes</strong> whenever possible — this often removes the need for deep copies entirely.</li><li>When using deep copies, <strong>implement them carefully</strong> — consider writing dedicated deepCopy() functions.</li><li>For complex structures, consider <strong>serialization-based cloning</strong> (e.g., using kotlinx.serialization or JSON encode-decode) to automatically create deep copies.</li><li>Always <strong>test cloning logic</strong> if your objects hold mutable references.</li></ul><h3>🚀 Final Thoughts</h3><p>Copying objects might sound simple, but it’s one of those details that separates clean, predictable code from confusing bugs.</p><p>Remember:</p><ul><li>Shallow copy = fast but risky</li><li>Deep copy = safe but heavier</li></ul><p>If your data is immutable, you rarely need deep copies.<br> But if you’re dealing with mutable nested structures — like state trees, cache models, or configurations — deep copy can save you from a world of unexpected behavior.</p><blockquote><em>✍️ Written by Mert Melih Aytemur<br> 💬 If you found this helpful, consider sharing or leaving a comment — let’s keep making Kotlin code safer and cleaner!</em></blockquote><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e035f196863c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Kotlin Projelerimizde Dependency Injection için Koin Kütüphanesinin Kullanımı]]></title>
            <link>https://medium.com/appcent/android-kotlin-projelerimizde-dependency-injection-i%C3%A7in-koin-k%C3%BCt%C3%BCphanesinin-kullan%C4%B1m%C4%B1-f388450fa13b?source=rss-b3e02897b105------2</link>
            <guid isPermaLink="false">https://medium.com/p/f388450fa13b</guid>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[koin]]></category>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Mert Melih Aytemur]]></dc:creator>
            <pubDate>Thu, 04 Apr 2024 05:38:50 GMT</pubDate>
            <atom:updated>2024-04-04T05:38:50.638Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AgwRNFsEwKLO9wH9gsTKBw.png" /></figure><p>Bu yazıda, Android Kotlin projelerimizde dependency injection (bağımlılık enjeksiyonu) işlemlerini nasıl daha etkin ve düzenli bir şekilde yönetebileceğimizi ele alacağız.</p><p>Koin kütüphanesinin temel özelliklerini, bu kütüphaneyi projelerimize nasıl entegre edebileceğimizi ve Koin’in sunduğu avantajları detaylı bir şekilde inceleyeceğiz. Pratik örneklerle desteklenen içeriğimiz, Kotlin tabanlı Android uygulama geliştirme sürecinizi iyileştirmek için kapsamlı bir rehber sunacak.</p><blockquote>Öncelikle Dependency Injection Nedir?</blockquote><p>Dependency Injection (DI), nesne yönelimli programlamada kullanılan bir tasarım desenidir. Bu desen, bir sınıfın bağımlılıklarını (yani, işlevselliği için gerekli olan diğer sınıflar veya modüller) doğrudan oluşturmak yerine, dışarıdan sağlama yöntemidir. Dependency Injection, sınıflar arasındaki bağımlılıkları azaltmaya ve kodun test edilebilirliğini artırmaya yardımcı olur.</p><ul><li><strong>Bağımlılıkların Dışarıdan Sağlanması:</strong> Bir sınıfın ihtiyaç duyduğu nesneler, sınıf içinde doğrudan oluşturulmaz. Bunun yerine, bu nesneler sınıfa dışarıdan, örneğin bir yapılandırıcı metot (constructor) aracılığıyla enjekte edilir.</li><li><strong>Modülerlik ve Yeniden Kullanılabilirlik:</strong> Sınıflar, belirli bir görevi yerine getirir ve bağımlılıkları dışarıdan sağlandığı için farklı bağlamlarda yeniden kullanılabilir hale gelir.</li><li><strong>Test Edilebilirlik</strong>: Bağımlılıkların dışarıdan enjekte edilmesi, özellikle birim testleri sırasında, test edilmek istenen sınıfa alternatif (mock veya stub) nesnelerin sağlanmasını kolaylaştırır, böylece sınıfın işlevselliği izole bir şekilde test edilebilir.</li></ul><blockquote>Koin Kütüphanesi Android Projemize Nasıl Entegre Edilir?</blockquote><p>Projenizi Koin ile kullanmaya başlamadan önce, build.gradle dosyanıza gerekli Koin bağımlılıklarını eklemeniz gerekmektedir. Bu, hem projenizin kök build.gradle dosyasında hem de modülünüzün build.gradle dosyasında yapılacak değişiklikleri içerir.</p><p>Kök build.gradle dosyasında, Koin sürümünüzü bir değişken olarak ekleyebilirsiniz:</p><pre>ext {<br>    koin_version = &#39;x.x.x&#39; // Koin&#39;in güncel sürümünü kullanın<br>}</pre><p>Modülünüzün build.gradle dosyasında ise, Koin bağımlılıklarını ekleyin:</p><pre>dependencies {<br>    implementation &quot;io.insert-koin:koin-android:$koin_version&quot;<br>    // Diğer gerekli Koin modülleri, örneğin:<br>    // implementation &quot;io.insert-koin:koin-androidx-viewmodel:$koin_version&quot;<br>}</pre><h4>Koin’i Başlatalım:</h4><p>Koin’i başlatmak için, Android uygulamanızın Application sınıfında Koin modüllerinizi yükleyerek startKoin fonksiyonunu çağırmanız gerekmektedir. Eğer bir Application sınıfınız yoksa, oluşturmanız ve Android manifest dosyanızda tanımlamanız gerekecektir.</p><p>startKoin fonksiyonu: Koin&#39;in başlatılmasını sağlar. Bu işlem genellikle uygulamanın Application sınıfının onCreate metodunda yapılır. androidLogger() fonksiyonu, Koin&#39;in loglamasını aktif hale getirir, androidContext(this@MyApplication) ile uygulamanın context&#39;i Koin&#39;e aktarılır, ve modules(appModule) ile Koin&#39;e hangi modüllerin kullanılacağı belirtilir.</p><pre>class MyApplication : Application() {<br>    override fun onCreate() {<br>        super.onCreate()<br>        startKoin {<br>            androidLogger() // Loglamayı aktifleştirir (isteğe bağlı)<br>            androidContext(this@MyApplication)<br>            modules(appModule) // Koin modüllerinizi burada belirtin<br>        }<br>    }<br>}</pre><p><em>Şimdi sizlerle örnek bir servis isteği senaryosu üzerinden bağımlılıklarımızı nasıl yönetebileceğimizi göstereceğim.</em></p><p>Uygulamamızda servisten güncel haberleri çekeceğimiz varsayalım. Öncelikle Servis arayüzümüzü oluşturalım.</p><p>Retrofit ile HTTP isteklerini tanımlayan bir arayüzdür.</p><p>Retrofit: HTTP isteklerini tanımlamak için kullanılan bir kütüphane. @GET(&quot;my/endpoint&quot;) annotation&#39;ı, belirli bir HTTP endpoint&#39;e GET isteği yapılacağını belirtir ve bu metod asenkron olarak haberleri çeker.</p><pre>interface NewsApi {<br>    @GET(&quot;my/endpoint&quot;)<br>    suspend fun fetchNews()<br>}</pre><p>Sonrasında (Clean Architecture ve Mvvm kullandığımızı varsayarak) Ağ çağrıları için Repository arayüzümüzü oluşturalım.</p><p>fetchNewsCall: Haberleri çekmek için kullanılan metoddur. Repository deseni, veri erişim katmanını soyutlayarak, veri kaynağının değişmesi durumunda uygulamanın diğer bölümlerinin etkilenmemesini sağlar.</p><pre>interface NewsRepository {<br>    suspend fun fetchNewsCall()<br>}</pre><p>Ve bu repository’i implement edeceğimiz RepositoryImpl sınıfımızı oluşturalım. NewsRepositoryImpl, NewsApi üzerinden ağ çağrılarını gerçekleştiren sınıftır.</p><p>Bu sınıf, NewsRepository arayüzünü implement eder ve NewsApi üzerinden ağ çağrılarını gerçekleştirir.</p><pre>class NewsRepositoryImpl(<br>    private val api: NewsApi<br>): MainRepository {<br><br>    override suspend fun fetchNewsCall() {<br>        api.callApi()<br>    }<br>}</pre><p>Şimdi ise View modelimizi oluşturalım ve ağ çağrısına hazır hale getirelim</p><pre>class NewsViewModel(<br>    private val repository: NewsRepository<br>): ViewModel() {<br><br>    fun fetchNewsCall() {<br>        viewModelScope.launch{<br>            repository.fetchNewsCall()<br>        }<br>    }<br>}</pre><p>Kullanıcı Arayüzüne geçmeden önce, koin app modülümüzü oluşturalım.</p><p>appModule: Retrofit ile HTTP istekleri için gerekli yapılandırmaları içerir. NewsApi ve Repository&#39;nin nasıl oluşturulacağını tanımlar.</p><ul><li>single: Bir sınıfın tek bir instance&#39;ını (nesnesini) oluşturmak ve bunu uygulama boyunca kullanmak için kullanılır. Bu, yalnızca bir kez oluşturulan ve ihtiyaç duyulduğunda tekrar kullanılan singleton nesneler tanımlamak için kullanılır.</li><li>viewModel: Android ViewModel nesnelerini yönetmek için kullanılır. viewModel bloğu içinde tanımlanan bir ViewModel, Lifecycle bilincine sahip olacak şekilde oluşturulur ve uygulamanın UI ile ilgili verileri yönetmek ve saklamak için kullanılır.</li></ul><pre>// appModule, uygulama genelinde kullanılacak bağımlılıkları tanımlar.<br>val appModule = module {<br>    single {<br>        Retrofit.Builder()<br>            .baseUrl(&quot;https://google.com&quot;)<br>            .addConverterFactory(MoshiConverterFactory.create())<br>            .build()<br>            .create(NewsApi::class.java) // Retrofit ile NewsApi&#39;nin bir örneği oluşturulur.<br>    }<br>    single&lt;MainRepository&gt; {<br>        MainRepositoryImpl(get()) // NewsRepositoryImpl, NewsApi bağımlılığı ile oluşturulur.<br>    }<br>    viewModel {<br>        MainViewModel(get()) // NewsViewModel, NewsRepository bağımlılığı ile oluşturulur.<br>    }<br>}</pre><p>Son olarak activity için bağımlılık modülümüzü oluşturalım</p><ul><li>activityModule: Activity özelinde bağımlılıkları tanımlar. Örneğin, named(&quot;hello&quot;) ve named(&quot;bye&quot;) ile isimlendirilmiş bağımlılıklar tanımlanabilir.</li></ul><pre>// activityModule, MainActivity ile ilgili bağımlılıkları tanımlar.<br>val activityModule = module {<br>    scope&lt;MainActivity&gt; {<br>        scoped(qualifier = named(&quot;hello&quot;)) { &quot;Hello&quot; }<br>        scoped(qualifier = named(&quot;bye&quot;)) { &quot;Bye&quot; }<br>    }<br>}</pre><p>ve activity üzerinde kullanımı</p><pre>// MainActivity, uygulamanın ana aktivitesidir ve bağımlılıkların kullanıldığı yerdir.<br>class MainActivity : AppCompatActivity() {<br>    private val viewModel by viewModel&lt;NewsViewModel&gt;() // Koin ile MainViewModel örneği alınır.<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        setContentView(R.layout.activity_main) // Layout belirlenir.<br><br>        val hello = inject&lt;String&gt;(named(&quot;bye&quot;)).value // &quot;bye&quot; adlı String bağımlılığını enjekte eder.<br>        println(hello)<br><br>        // ViewModel kullanılarak ağ çağrısı başlatılır.<br>        viewModel.fetchNewsCall()<br>    }<br>}</pre><p><em>Koin ile Android’de bağımlılık enjeksiyonunun nasıl etkili bir şekilde uygulanabileceğini ele aldığımız bu rehber, uygulamanızın yapılandırmasını ve yönetimini basitleştirmeye yönelik adımları göstermektedir. Umarım, bu makale sizlere Koin’in gücünü keşfetme ve Android projelerinizde daha temiz, modüler ve test edilebilir bir kod tabanı oluşturma konusunda ilham vermiştir.</em></p><p>İyi Çalışmalar Dilerim.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f388450fa13b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/appcent/android-kotlin-projelerimizde-dependency-injection-i%C3%A7in-koin-k%C3%BCt%C3%BCphanesinin-kullan%C4%B1m%C4%B1-f388450fa13b">Android Kotlin Projelerimizde Dependency Injection için Koin Kütüphanesinin Kullanımı</a> was originally published in <a href="https://medium.com/appcent">Appcent</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Projelerimizde S.O.L.I.D Prensiplerinin Uygulanması]]></title>
            <link>https://medium.com/appcent/android-projelerimizde-s-o-l-i-d-prensiplerinin-uygulanmas%C4%B1-c7efa33547e4?source=rss-b3e02897b105------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7efa33547e4</guid>
            <category><![CDATA[mobile-app-development]]></category>
            <category><![CDATA[mobile-apps]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[solid-principles]]></category>
            <category><![CDATA[android]]></category>
            <dc:creator><![CDATA[Mert Melih Aytemur]]></dc:creator>
            <pubDate>Mon, 18 Mar 2024 08:11:56 GMT</pubDate>
            <atom:updated>2024-03-18T08:11:56.856Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8r-Z7ttOx9KEUhemuBuq2Q.jpeg" /></figure><p>Android projelerimizin mimarisini geliştirirken, SOLID prensiplerini uygulamak, sürdürülebilir ve ölçeklenebilir bir yapı oluşturmanın anahtarıdır.</p><p>Bu yazıda, bu beş temel prensibi nasıl entegre edebileceğimizi ve Android uygulama geliştirmedeki başarımıza nasıl katkıda bulunacaklarını detaylı bir şekilde ele alacağız.</p><blockquote>Öncelikle S.O.L.I.D Nedir?</blockquote><p><em>SOLID, nesne yönelimli programlamada kullanılan beş temel prensibi ifade eder ve daha temiz, düzenli ve esnek yazılım geliştirme sürecini destekler. 2000&#39;lerin başında Robert C. Martin tarafından popüler hale getirilen bu prensipler, yazılımın bakımını ve güncellenmesini kolaylaştırır. SOLID, her bir harfi aşağıdaki prensipleri temsil eder:</em></p><p><strong>1)Single Responsibility Principle (SRP):</strong> Bir sınıfın tek bir sorumluluğu olmalıdır. Birden fazla görevi üstlenen bir sınıf ayrılmalı, böylece kod daha anlaşılır ve bakımı kolaylaşır. Örneğin, bir restoranda her çalışanın ayrı bir görevi vardır; aşçı pişirir, garson servis yapar, bulaşıkçı yıkar. Yazılımda da her sınıfın belirli bir işlevi olmalıdır.</p><p><strong>2)Open/Closed Principle (OCP):</strong> Yazılım entiteleri genişlemeye açık fakat değişikliğe kapalı olmalıdır. Yeni işlevler eklenirken mevcut kod değiştirilmemelidir. Bu, yazılımın gelişimini kolaylaştırır. Bir lego seti gibi, mevcut yapıya zarar vermeden yeni parçalar eklenebilir.</p><p><strong>3)Liskov Substitution Principle (LSP):</strong> Alt sınıflar, üst sınıflarının yerine geçebilmelidir. Alt sınıfların, üst sınıfın işlevlerini değiştirmeden genişletebilmesi gerekir. Örneğin, oyuncaklar farklı şekillerde olabilir, ancak hepsi aynı kutuya sığmalıdır.</p><p><strong><em>4)Interface Segregation Principle (ISP)</em></strong>: Sınıflar, kullanmadıkları yöntemleri içeren arayüzleri uygulamamalıdır. Daha küçük, özelleşmiş arayüzler kullanılmalıdır, böylece gereksiz bağımlılıklardan kaçınılır. Öğrencilerin sadece ilgi alanlarına yönelik dersleri alması gibi, sınıflar da yalnızca gereken işlevleri içeren arayüzleri uygulamalıdır.</p><p><strong>5)Dependency Inversion Principle (DIP): </strong>Yüksek seviyeli modüller, düşük seviyeli modüllere doğrudan bağımlı olmamalıdır; her iki modül de arayüzlere veya soyutlamalara bağımlı olmalıdır. Bu, yazılımın esnekliğini ve genişletilebilirliğini artırır. Elektrik prizleri ve cihazlar gibi, farklı cihazlar aynı priz tipine bağlanabilir.</p><blockquote>Hadi şimdi sizlerle bu prensiplerin Android projelerimizdeki olabilecek karşılıklarına bir bakalım</blockquote><h4>Single Responsibility Principle:</h4><p>Yanlış Kullanım:</p><p>Bu örnekte Logger sınıfı, hem konsola loglama işlemini hem de dosyaya loglama işlemini yapıyor. Bu, SRP&#39;ye aykırıdır çünkü bir sınıfın tek bir sorumluluğu olmalıdır.</p><pre>class Logger {<br>    fun log(message: String) {<br>        // Konsola loglama<br>        println(message)<br><br>        // Dosyaya loglama<br>        val fileWriter = FileWriter(&quot;log.txt&quot;, true)<br>        fileWriter.write(message)<br>        fileWriter.close()<br>    }<br>}</pre><p>Doğru Kullanım:</p><p>Burada, ConsoleLogger ve FileLogger sınıfları birer sorumluluğu üstlenir: biri konsola loglama, diğeri ise dosyaya loglama işlemlerini yapar. Bu şekilde, SRP&#39;ye uygun bir yapı elde edilir.</p><pre>class ConsoleLogger {<br>    fun log(message: String) {<br>        // Yalnızca konsola loglama<br>        println(message)<br>    }<br>}<br><br>class FileLogger {<br>    fun log(message: String) {<br>        // Yalnızca dosyaya loglama<br>        val fileWriter = FileWriter(&quot;log.txt&quot;, true)<br>        fileWriter.write(message)<br>        fileWriter.close()<br>    }<br>}</pre><h4>Open Closed Principle:</h4><p>Yanlış Kullanım:</p><p>Bu örnekte, MusicPlayer sınıfı sadece MP3 dosyalarını çalabilir durumdadır. Yeni bir ses formatı eklemek için sınıfı değiştirmek gerekecektir, bu da OCP&#39;ye aykırıdır.</p><pre>class MusicPlayer {<br>    fun playMP3(file: File) {<br>        // MP3 dosyasını çal<br>    }<br>}</pre><p>Doğru Kullanım:</p><p>Burada, AudioPlayer arayüzü tüm ses dosyalarını çalmak için bir şablon sağlar ve yeni bir ses formatı eklemek, mevcut kodu değiştirmeden mümkündür. Bu, OCP&#39;nin sağladığı esneklik ilkesini takip eder.</p><pre>interface AudioPlayer {<br>    fun play(file: File)<br>}<br><br>class MP3Player : AudioPlayer {<br>    override fun play(file: File) {<br>        // MP3 dosyasını çal<br>    }<br>}<br><br>class FLACPlayer : AudioPlayer {<br>    override fun play(file: File) {<br>        // FLAC dosyasını çal<br>    }<br>}<br><br>class WAVPlayer : AudioPlayer {<br>    override fun play(file: File) {<br>        // WAV dosyasını çal<br>    }<br>}</pre><h4>Liskov Substitution Principle</h4><pre>class MainRepository(<br> private val fileLogger : FileLogger<br>){<br>    suspend fun login(){<br>        try{<br>            //Login operations that can cause error<br>        }catch(e : Exception){<br>            fileLogger.logFile(e.message.toString())<br>        }<br>    }<br>}</pre><p>Yanlış Kullanım:</p><p>Burada, CustomFileLogger sınıfı, FileLogger sınıfından türemesine rağmen logFile metodunu override etmemiştir. Bu durumda, LSP&#39;ye aykırı olabilir çünkü FileLogger ile CustomFileLogger arasında beklenmeyen davranış farklılıkları olabilir.</p><pre>open class FileLogger{<br>    open fun logFile(errorMessage : String){<br>        val file : File(&quot;errors.txt&quot;)<br>        file.appendText(<br>            text = errorMessage<br>        )<br>    }<br>}<br><br>class CustomFileLogger : FileLogger() {<br>    fun customErrorLog(errorMessage : String){<br>        val file : File(&quot;custom_errors.txt&quot;)<br>        file.appendText(<br>            text = errorMessage<br>        )<br>    }<br>}</pre><p>Doğru Kullanım:</p><p>Burada, CustomFileLogger sınıfı logFile metodunu override ederek, temel sınıfın beklenen davranışını sağlar ve LSP&#39;yi uygular.</p><pre>open class FileLogger{<br>    open fun logFile(errorMessage : String){<br>        val file : File(&quot;errors.txt&quot;)<br>        file.appendText(<br>            text = errorMessage<br>        )<br>    }<br>}<br><br>class CustomFileLogger : FileLogger() {<br>    override fun logFile(errorMessage : String){<br>        val file : File(&quot;custom_errors.txt&quot;)<br>        file.appendText(<br>            text = errorMessage<br>        )<br>    }<br>}</pre><h4>Interface Segregation Principle</h4><p>Hatalı Kullanım:</p><p>Bu örnekte, FileLogger arayüzü hem logFile hem de printLog metodlarını içerir. Ancak, CustomFileLogger sınıfı printLog metodunu kullanmaz, bu da ISP&#39;ye aykırıdır çünkü kullanılmayan metodları içeren arayüzler genellikle kötü bir tasarımı işaret eder.</p><pre>interface FileLogger{<br>    <br>    fun logFile(errorMessage : String)<br>    fun printLog(errorMessage : String)<br>   <br>    <br>}<br><br>class CustomFileLogger : FileLogger {<br>    override fun printLog(errorMessage : String) {<br>        // Not using but bad usage<br>    }<br>    override fun logFile(errorMessage : String){<br>        val file : File(&quot;custom_errors.txt&quot;)<br>        file.appendText(<br>            text = errorMessage<br>        )<br>    }<br>}</pre><p>Doğru Kullanım:</p><p>Burada, FileLogger arayüzü varsayılan bir gövde sağlayarak printLog metodunu içerir. Böylece, CustomFileLogger sınıfı printLog metodunu override etmek zorunda kalmadan, isteğe bağlı olarak kullanabilir ve ISP&#39;yi uygular.</p><pre>interface FileLogger{<br>    <br>    fun logFile(errorMessage : String)<br>    fun printLog(errorMessage : String) {<br>        // default body prevents force override<br>    }<br>   <br>    <br>}<br><br>class CustomFileLogger : FileLogger {<br>    <br>    //No need to override anymore<br>    <br>    override fun logFile(errorMessage : String){<br>        val file : File(&quot;custom_errors.txt&quot;)<br>        file.appendText(<br>            text = errorMessage<br>        )<br>    }<br>}</pre><h4>Dependency Inversion:</h4><p>Yanlış Kullanım:</p><p>Bu örnekte, PaymentProcessor sınıfı doğrudan PayPalProvider sınıfına bağımlıdır. Bu, DIP&#39;ye aykırıdır çünkü yüksek seviyeli bir sınıf, düşük seviyeli bir sınıfa doğrudan bağımlı olmamalıdır.</p><pre>class PaymentProcessor {<br>    private val paymentProvider = PayPalProvider()<br><br>    fun processPayment(amount: Double) {<br>        paymentProvider.pay(amount)<br>    }<br>}<br><br>class PayPalProvider {<br>    fun pay(amount: Double) {<br>        println(&quot;Payment processed via PayPal: $amount&quot;)<br>        // PayPal&#39;a gerçek ödeme isteği gönderilir<br>    }<br>}</pre><p>Doğru kullanım:</p><p>Burada, PaymentProcessor sınıfı PaymentProvider arayüzüne bağımlıdır ve bu sayede farklı ödeme sağlayıcıları eklemek kolaylaşır, bu da DIP&#39;yi uygular.</p><pre>// PaymentProvider arayüzü<br>interface PaymentProvider {<br>    fun pay(amount: Double)<br>}<br><br>// PayPalProvider sınıfı, PaymentProvider arayüzünü implement eder<br>class PayPalProvider : PaymentProvider {<br>    override fun pay(amount: Double) {<br>        println(&quot;Payment processed via PayPal: $amount&quot;)<br>        // PayPal&#39;a gerçek ödeme isteği gönderilir<br>    }<br>}<br><br>// StripeProvider sınıfı, PaymentProvider arayüzünü implement eder<br>class StripeProvider : PaymentProvider {<br>    override fun pay(amount: Double) {<br>        println(&quot;Payment processed via Stripe: $amount&quot;)<br>        // Stripe&#39;a gerçek ödeme isteği gönderilir<br>    }<br>}<br><br>// PaymentProcessor sınıfı, PaymentProvider arayüzüne bağımlıdır<br>class PaymentProcessor(private val paymentProvider: PaymentProvider) {<br>    fun processPayment(amount: Double) {<br>        paymentProvider.pay(amount)<br>    }<br>}</pre><h4>Sonuç</h4><p><em>Android projelerimizin mimarisini geliştirirken, SOLID prensiplerini uygulamak, sürdürülebilir ve ölçeklenebilir bir yapı oluşturmanın anahtarıdır. Bu prensipler, her bir harfi temsil ettiği SRP, OCP, LSP, ISP ve DIP ilkeleriyle yazılım geliştirme sürecinde daha temiz ve esnek bir yaklaşım sunar. Bu sayede, kodun daha anlaşılır, bakımı daha kolay ve yeni işlevlerin eklenmesi daha sorunsuz hale gelir. SOLID prensiplerini doğru şekilde uygulamak, Android uygulama geliştirmenin başarısını artırır ve kod tabanını daha sağlam hale getirir.</em></p><p>İyi Çalışmalar Dilerim.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7efa33547e4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/appcent/android-projelerimizde-s-o-l-i-d-prensiplerinin-uygulanmas%C4%B1-c7efa33547e4">Android Projelerimizde S.O.L.I.D Prensiplerinin Uygulanması</a> was originally published in <a href="https://medium.com/appcent">Appcent</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Projeleremizde Google Maps SDK Kurulumu ve Kolay Kullanımı]]></title>
            <link>https://medium.com/appcent/android-projeleremizde-google-maps-sdk-kurulumu-ve-kolay-kullan%C4%B1m%C4%B1-3c8fcda107cf?source=rss-b3e02897b105------2</link>
            <guid isPermaLink="false">https://medium.com/p/3c8fcda107cf</guid>
            <dc:creator><![CDATA[Mert Melih Aytemur]]></dc:creator>
            <pubDate>Mon, 18 Dec 2023 08:51:21 GMT</pubDate>
            <atom:updated>2023-12-18T08:51:21.529Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XJ_oEaZUBZ0PFJAJhix1gQ.png" /></figure><p>Google Maps, mobil uygulamalarınıza güçlü bir konum tabanlı hizmet eklemenin harika bir yoludur. Bu makalede, Android uygulamanıza Google Maps SDK’nın nasıl kurulacağını ve kolay kullanımını nasıl gerçekleştireceğinizi adım adım öğreneceksiniz.</p><p>Bu makalemizde kullanıcının konumunu GPS üzerinden alıp google maps üzerinde göstereceğiz</p><h4>Projemize Google Maps SDK ekleyelim</h4><p>Gradle Scripts -&gt; build.gradle (Module :app)</p><p><a href="https://developers.google.com/android/guides/setup"><em>Google Maps SDK güncel sürüm için tıklayın.</em></a></p><pre>plugins {<br>    id(&quot;com.google.android.libraries.mapsplatform.secrets-gradle-plugin&quot;)<br>}<br><br>dependencies {<br><br>    //Google Maps SDK<br>    implementation(&quot;com.google.android.gms:play-services-maps:x.y.z&quot;)<br>}</pre><p>Gradle Scripts -&gt; build.gradle (Project)</p><pre>// Top-level build file where you can add configuration options common to all sub-projects/modules.<br>plugins {<br>    id(&quot;com.android.application&quot;) version &quot;8.1.4&quot; apply false<br>    id(&quot;org.jetbrains.kotlin.android&quot;) version &quot;1.9.0&quot; apply false<br>}<br><br>buildscript {<br>    dependencies {<br>        classpath(&quot;com.android.tools.build:gradle:7.3.0&quot;)<br>        classpath(&quot;com.google.gms:google-services:4.4.0&quot;)<br>        classpath(&quot;com.google.android.libraries.mapsplatform.secrets-gradle-plugin:secrets-gradle-plugin:2.0.1&quot;)<br>    }<br>}</pre><h3>Layout Dosyamıza Haritamızı ve Butonumuzu Ekleyelim</h3><p>Haritamız bir fragment üzerinde çalışacaktır. Butonumuz ise GPS üzerinden kullanıcının anlık konumunu alıp harita üzerinde marker ile gösterecektir.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*t_7mE_4617Yb2Ak8GuVUMQ.png" /></figure><h3>Şimdi Google Cloud Console Hesabımız Üzerinden Bir Proje Oluşturalım</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Wzqgps1m-lWOGZxbMdIqqQ.png" /></figure><h4>Sonrasında API &amp; Services kısmından Maps SDK for Android Özelliğimiz Aktif Edelim</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/920/1*Hg8SdZ9916VfcxNzBVFkQQ.png" /></figure><blockquote>Artık Bizim İçin Oluşturulan Google Maps API Key ile uygulamamızda haritamızı kullanabiliriz. (Bizim için $200 dolarlık aylık ücretsiz bir kullanım sunmaktadır)</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b3hSrUZOsqK6gF7XbamNFQ.png" /></figure><h4>Manifest.xml dosyamıza Google Cloud Console üzerinden aldığımız API KEY’i meta data tag’i ile yerleştirelim.</h4><pre>&lt;?xml version=&quot;1.0&quot; encoding=&quot;utf-8&quot;?&gt;<br>&lt;manifest xmlns:android=&quot;http://schemas.android.com/apk/res/android&quot;<br>    xmlns:tools=&quot;http://schemas.android.com/tools&quot;&gt;<br><br>    &lt;uses-permission android:name=&quot;android.permission.INTERNET&quot; /&gt;<br>    &lt;uses-permission android:name=&quot;android.permission.ACCESS_COARSE_LOCATION&quot; /&gt;<br><br>    &lt;application&gt;<br><br>        &lt;!-- Diğer aktiviteler ve ayarlar --&gt;<br><br>        &lt;meta-data<br>            android:name=&quot;com.google.android.geo.API_KEY&quot;<br>            android:value =&quot;YOUR_API_KEY&quot; /&gt;<br><br>    &lt;/application&gt;<br><br>&lt;/manifest&gt;</pre><blockquote>UYARI: Google Maps API, konum tabanlı hizmetlerin entegre edilmesi için popüler bir seçenek sunar. Ancak, API Keyi’i güvenli bir şekilde saklamak, uygulamanızın güvenliğini önemli ölçüde etkiler. Şimdi Google Maps API Keyimizi nasıl güvenli bir şekilde saklayabileceğinizi keşfedeceğiz.</blockquote><h3>Local Properties Nedir?</h3><p>Local Properties, projenizin kök dizininde bulunan ve özel anahtar-değer çiftlerini içeren bir dosyadır. Bu dosya, hassas bilgilerinizi içerir ve kodunuz içinde sert kodlamak yerine bu dosyadan değerleri okuyarak kullanmanıza olanak tanır.</p><pre># local.properties<br><br>MAPS_API_KEY=my_secret_key</pre><pre>// app/build.gradle<br><br>android {<br><br>    val key: String = gradleLocalProperties(rootDir).getProperty(&quot;MAPS_API_KEY&quot;)<br><br>    buildTypes {<br>        getByName(&quot;debug&quot;) {<br>            buildConfigField(&quot;String&quot;, &quot;MAPS_API_KEY&quot;, key)<br>        }<br>    }<br><br>}</pre><p>Bu şekilde, API anahtarınızı kod içine sert kodlamak yerine, daha güvenli bir Local Properties dosyasından alarak kullanabilirsiniz.</p><h4>local.properties dosyamızı .gitignore’a eklemek</h4><p>Local Properties dosyasını projenizin sürüm kontrol sistemine eklememeniz önemlidir. Bu dosya, hassas bilgileri içerir ve bu bilgilerin paylaşılmasını önlemek için .gitignore dosyanıza eklenmelidir. .gitignore dosyasına eklenirse, dosyanız sürüm kontrol sistemine dahil edilmez ve projeyi paylaşırken veya depolarken güvenli kalır.</p><pre># .gitignore<br><br># Local Properties dosyasını eklemeyin<br>local.properties</pre><p>Bu örnek, <a href="http://local.properties/">local.properties</a> dosyasının sürüm kontrol sistemine dahil edilmemesini sağlar, böylece bu dosyadaki hassas bilgileri güvenli bir şekilde koruruz.</p><h3>Sunucu Tabanlı Güvenlik ile API Anahtarını Saklama</h3><p>Sunucu tabanlı bir yaklaşım benimsemek, API anahtarınızı uygulama içinde değil, bir güvenli sunucuda saklamayı içerir. Bu şekilde, uygulama içinde anahtara erişim daha zor hale gelir ve daha güvenli olur.</p><ol><li>Sunucu API Hizmeti Oluşturma: Bir sunucu API hizmeti oluşturun. Bu hizmet, Google Haritalar API ile iletişim kuracak ve uygulamanızdan gelen istekleri işleyecektir.</li><li>API Key’i Sunucuda Saklama: API anahtarınızı sunucuda saklayın ve sadece bu sunucu üzerinden Haritalar API’ye erişim sağlayın.</li><li>Uygulamada Sunucu API’yi Kullanma: Uygulamanızdaki harita istekleri, sunucu API üzerinden yapılarak güvenli bir şekilde gerçekleştirilir.</li></ol><p>Bu yöntem, API Keyimizi uygulama içinde değil, güvenli bir sunucuda saklayarak daha yüksek bir güvenlik seviyesi sağlar.</p><blockquote><em>Bu projemizde Api Keyimizi locale.properties dosyamızda saklayarak örneklerimize devam edeceğiz.</em></blockquote><blockquote><em>Artık meta-data tag’e android:value=”${MAPS_API_KEY}” değerini verebiliriz.</em></blockquote><h4>Şimdi kullanıcının konumunu almadan haritamızda statik bir lokasyon gösterelim.</h4><pre>class MainActivity : AppCompatActivity(){<br><br>    private lateinit var binding: ActivityMainBinding<br><br>    private val callback = OnMapReadyCallback { googleMap -&gt;<br>        /**<br>         * Manipulates the map once available.<br>         * This callback is triggered when the map is ready to be used.<br>         * This is where we can add markers or lines, add listeners or move the camera.<br>         * In this case, we just add a marker near Sydney, Australia.<br>         * If Google Play services is not installed on the device, the user will be prompted to<br>         * install it inside the SupportMapFragment. This method will only be triggered once the<br>         * user has installed Google Play services and returned to the app.<br>         */<br>        val sydney = LatLng(-34.0, 151.0)<br>        googleMap.addMarker(MarkerOptions().position(sydney).title(&quot;Marker in Sydney&quot;))<br>        googleMap.moveCamera(CameraUpdateFactory.newLatLng(sydney))<br>    }<br><br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        binding = ActivityMainBinding.inflate(layoutInflater)<br>        setContentView(binding.root)<br><br>        val mapFragment = supportFragmentManager.findFragmentById(R.id.googleMapsFragment) as SupportMapFragment<br>        mapFragment.getMapAsync(callback)<br>    }<br>}</pre><p>Uygulamamızı çalıştırdığımızda verdiğimiz statik enlem boylam bilgilerinin olduğu loksayonda bir adet markerımızı göreceğiz.</p><h4>Kullanıcı Konumunu Alma</h4><p>Şimdi, GPS aracılığyla kullanıcının anlık konumu alarak haritamız üzerinde göstereceğiz. Bunun için öncelikle kullanıcıdan konum izni almamız, sonrasında ise kullanıcının gps’ini açmasını isteyeceğiz.</p><h4>İzinler için <a href="https://github.com/Karumi/Dexter">dexter</a> permission kütüphanesini kullanacağız.</h4><p>PermissionManager adlı objemizi yaratalım</p><pre>object PermissionManager {<br><br>    fun requestRuntimeLocationPermission(<br>        context: Context,<br>        onPermissionGranted: () -&gt; Unit,<br>        onPermissionDenied: () -&gt; Unit<br>    ) {<br>        Dexter.withContext(context)<br>            .withPermission(<br>                Manifest.permission.ACCESS_FINE_LOCATION<br>            )<br>            .withListener(<br>                object : PermissionListener {<br>                    override fun onPermissionGranted(p0: PermissionGrantedResponse?) {<br>                        onPermissionGranted()<br>                    }<br><br>                    override fun onPermissionDenied(p0: PermissionDeniedResponse?) {<br>                        onPermissionDenied()<br>                    }<br><br>                    override fun onPermissionRationaleShouldBeShown(<br>                        p0: com.karumi.dexter.listener.PermissionRequest?,<br>                        token: PermissionToken?<br>                    ) {<br>                        token?.continuePermissionRequest()<br>                    }<br>                }<br>            )<br>            .withErrorListener {<br>                onPermissionDenied()<br>            }<br>            .onSameThread()<br>            .check()<br>    }<br><br>    fun hasAccessFineLocationPermission(activity: Activity) : Boolean{<br>        val permissionRequestAccessFineLocation = ContextCompat.checkSelfPermission(activity,<br>            Manifest.permission.ACCESS_FINE_LOCATION)<br>        return permissionRequestAccessFineLocation  == PackageManager.PERMISSION_GRANTED<br>    }<br>}</pre><p>Sonrasında ise activity üzerinde ilgili methodlarımızı yazıp çağıralım.</p><pre>class MainActivity : AppCompatActivity() {<br><br>    private lateinit var fusedLocationClient: FusedLocationProviderClient<br><br>    private lateinit var googleMap: GoogleMap<br><br>    private lateinit var binding: ActivityMainBinding<br><br>    private val callback = OnMapReadyCallback { map -&gt;<br>        googleMap = map<br>        // Harita hazır olduğunda yapılacak işlemler<br>        handleLocationPermission()<br>    }<br><br>    @SuppressLint(&quot;MissingPermission&quot;)<br>    override fun onCreate(savedInstanceState: Bundle?) {<br>        super.onCreate(savedInstanceState)<br>        binding = ActivityMainBinding.inflate(layoutInflater)<br>        setContentView(binding.root)<br><br>        fusedLocationClient = LocationServices.getFusedLocationProviderClient(this)<br><br>        val mapFragment =<br>            supportFragmentManager.findFragmentById(R.id.googleMapsFragment) as SupportMapFragment<br>        mapFragment.getMapAsync(callback)<br><br>        binding.btnUserLocation.setOnClickListener {<br>            setUserLocation(this)<br>        }<br>    }<br><br>    private fun setUserLocation(context: Context) {<br>        getUserLocation(onLocationSaved = {<br>            addMarkerToUserLocation(it)<br>        }, onResponseFailed = {<br>            getUserLocationWithLocationUtils(context, onLocationSaved = {<br>                addMarkerToUserLocation(it)<br>            })<br>        })<br>    }<br><br>    @SuppressLint(&quot;MissingPermission&quot;)<br>    @SuppressWarnings(&quot;OptionalWhenBraces&quot;)<br>    private fun getUserLocation(<br>        onLocationSaved: (LatLng) -&gt; Unit,<br>        onResponseFailed: () -&gt; Unit<br>    ) {<br>        fusedLocationClient.lastLocation.addOnSuccessListener { location -&gt;<br>            location?.let {<br>                val userLocation = LatLng(location.latitude, location.longitude)<br>                userLocation.let {<br>                    moveCameraToLocation(it)<br>                    onLocationSaved(it)<br>                }<br>            } ?: run(onResponseFailed)<br><br>        }.addOnFailureListener {<br>            onResponseFailed()<br>        }<br>    }<br><br>    private fun getUserLocationWithLocationUtils(<br>        context: Context,<br>        onLocationSaved: (LatLng) -&gt; Unit<br>    ) {<br>        val locationResult = object : GetLocationUtils.LocationResult() {<br>            override fun gotLocation(location: Location?) {<br>                location?.let {<br>                    val userLocation = LatLng(it.latitude, it.longitude)<br><br>                    userLocation.let { latlng -&gt;<br>                        moveCameraToLocation(latlng)<br>                        onLocationSaved(latlng)<br>                    }<br>                }<br>            }<br><br>            override fun onLocationUpdateFailed() {}<br>        }<br>        val userLocationProvider = GetLocationUtils()<br>        userLocationProvider.getLocation(context, locationResult)<br>    }<br><br>    private fun moveCameraToLocation(userPosition: LatLng) {<br>        addMarkerToUserLocation(userPosition)<br>        val zoomLevel = 12F<br>        googleMap.animateCamera(CameraUpdateFactory.newLatLngZoom(userPosition, zoomLevel))<br>    }<br><br>    /**<br>     * Add markers to [userLocation]<br>     */<br>    private fun addMarkerToUserLocation(latLng: LatLng) {<br>        googleMap.clear()<br>        googleMap.addMarker(<br>            MarkerOptions().position(latLng).title(&quot;Konumunuz&quot;)<br>        )<br>    }<br><br>    private fun handleLocationPermission() {<br>        if (!PermissionManager.hasAccessFineLocationPermission(this)) {<br>            PermissionManager.requestRuntimeLocationPermission(this,<br>                onPermissionGranted = {<br>                    setUserLocation(this)<br>                },<br>                onPermissionDenied = {<br>                    //show location needed info dialog or etc.<br>                })<br>        }<br>    }<br>}</pre><h3>1. setUserLocation Metodu</h3><p>Bu metod, kullanıcının konumunu belirleme işlevini yerine getirir. Kullanıcının konumunu almak için iki farklı yöntemi kullanır</p><ul><li>İlk olarak, getUserLocation metodunu kullanarak kullanıcının konumunu almaya çalışır.</li><li>Eğer konum alımı başarısız olursa (null dönerse), getUserLocationWithLocationUtils metodunu kullanarak alternatif bir yönteme geçer.</li></ul><h3>2. getUserLocation Metodu</h3><p>Bu metod, kullanıcının konumunu fused location client kullanarak almaya çalışır.</p><ul><li>fusedLocationClient kullanarak son bilinen konumu alır.</li><li>Eğer konum null değilse, bu bilgiyi LatLng objesine dönüştürür, kamerayı bu konuma hareket ettirir ve onLocationSaved callback&#39;ini çağırır.</li><li>Eğer konum null ise, onResponseFailed callback&#39;ini çağırır.</li></ul><h3>3. getUserLocationWithLocationUtils Metodu</h3><p>Bu metod, kullanıcının konumunu almak için özel bir yardımcı sınıf olan GetLocationUtils kullanır.</p><ul><li>Konum callback’lerini işlemek üzere bir LocationResult objesi oluşturur.</li><li>Daha sonra GetLocationUtils sınıfının bir örneğini oluşturur ve getLocation metodunu çağırarak LocationResult objesini ileterek konumu alır.</li></ul><h3>4. GetLocationUtils Sınıfı</h3><pre>class GetLocationUtils {<br>    private lateinit var timer1: Timer<br>    private lateinit var locationManager: LocationManager<br>    private lateinit var locationResult: LocationResult<br>    private var gpsEnabled = false<br>    private var networkEnabled = false<br>    private lateinit var context: Context<br><br>    /**<br>     * Get user location from gps or network location provider services<br>     */<br>    @SuppressLint(&quot;MissingPermission&quot;)<br>    @SuppressWarnings(&quot;ComplexMethod&quot;)<br>    fun getLocation(context: Context, result: LocationResult): Boolean {<br>        // I use LocationResult callback class to pass location value from MyLocation to user code<br>        this.context = context<br>        locationResult = result<br>        if (!this::locationManager.isInitialized) locationManager =<br>            context.getSystemService(Context.LOCATION_SERVICE) as LocationManager<br>        // exceptions will be thrown if provider is not permitted.<br>        try {<br>            gpsEnabled = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)<br>        } catch (ex: Exception) {<br>            ex.printStackTrace()<br>        }<br>        try {<br>            networkEnabled = locationManager.isProviderEnabled(LocationManager.NETWORK_PROVIDER)<br>        } catch (ex: Exception) {<br>            ex.printStackTrace()<br>        }<br>        // don&#39;t start listeners if no provider is enabled<br>        if (!gpsEnabled &amp;&amp; !networkEnabled) return false<br>        if (isFineLocationPermissionGranted() &amp;&amp;<br>            isCoarseLocationPermissionGranted()<br>        ) {<br>            if (gpsEnabled) {<br>                locationManager.requestLocationUpdates(<br>                    LocationManager.GPS_PROVIDER,<br>                    30L,<br>                    0F,<br>                    locationListenerGps<br>                )<br>            }<br>            if (networkEnabled) {<br>                locationManager.requestLocationUpdates(<br>                    LocationManager.NETWORK_PROVIDER,<br>                    30L,<br>                    0F,<br>                    locationListenerNetwork<br>                )<br>            }<br>        }<br><br>        timer1 = Timer()<br>        timer1.schedule(GetLastLocation(), 15000)<br>        return true<br>    }<br><br>    var locationListenerGps: LocationListener = object : LocationListener {<br>        /**<br>         * get user location from gps<br>         */<br>        override fun onLocationChanged(location: Location) {<br>            timer1.cancel()<br>            locationResult.gotLocation(location)<br>            this@GetLocationUtils.locationManager.removeUpdates(this)<br>            this@GetLocationUtils.locationManager.removeUpdates(locationListenerNetwork)<br>        }<br>    }<br>    var locationListenerNetwork: LocationListener = object : LocationListener {<br>        /**<br>         * get user location from network<br>         */<br>        override fun onLocationChanged(location: Location) {<br>            timer1.cancel()<br>            locationResult.gotLocation(location)<br>            this@GetLocationUtils.locationManager.removeUpdates(this)<br>            this@GetLocationUtils.locationManager.removeUpdates(locationListenerGps)<br>        }<br>    }<br><br>    internal inner class GetLastLocation : TimerTask() {<br>        @SuppressLint(&quot;MissingPermission&quot;)<br>        @SuppressWarnings(&quot;ComplexMethod&quot;, &quot;ReturnCount&quot;, &quot;MandatoryBracesIfStatements&quot;)<br>        override fun run() {<br>            locationManager.removeUpdates(locationListenerGps)<br>            locationManager.removeUpdates(locationListenerNetwork)<br>            var netLoc: Location? = null<br>            var gpsLoc: Location? = null<br>            if (isFineLocationPermissionGranted() &amp;&amp;<br>                isCoarseLocationPermissionGranted()<br>            ) {<br>                if (gpsEnabled) {<br>                    gpsLoc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER)<br>                }<br>                if (networkEnabled) {<br>                    netLoc = locationManager.getLastKnownLocation(LocationManager.NETWORK_PROVIDER)<br>                }<br>            } else {<br>                locationResult.onLocationUpdateFailed()<br>                //Timber.e(&quot;Permission grant error Permission not granted&quot;)<br>            }<br>            // if there are both values use the latest one<br>            if (gpsLoc != null &amp;&amp; netLoc != null) {<br>                if (gpsLoc.time &gt; netLoc.time) {<br>                    locationResult.gotLocation(gpsLoc)<br>                } else locationResult.gotLocation(<br>                    netLoc<br>                )<br>                return<br>            }<br>            if (gpsLoc != null) {<br>                locationResult.gotLocation(gpsLoc)<br>                return<br>            }<br>            if (netLoc != null) {<br>                locationResult.gotLocation(netLoc)<br>                return<br>            }<br>            locationResult.gotLocation(null)<br>        }<br>    }<br><br>    private fun isFineLocationPermissionGranted():<br>            Boolean =<br>        ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_FINE_LOCATION) ==<br>                PackageManager.PERMISSION_GRANTED<br><br>    private fun isCoarseLocationPermissionGranted():<br>            Boolean =<br>        ActivityCompat.checkSelfPermission(context, Manifest.permission.ACCESS_COARSE_LOCATION) ==<br>                PackageManager.PERMISSION_GRANTED<br><br>    /**<br>     * Result class invokes on location received or failed<br>     */<br>    @SuppressWarnings(&quot;UnnecessaryAbstractClass&quot;)<br>    abstract class LocationResult {<br>        /**<br>         * return user location<br>         */<br>        abstract fun gotLocation(location: Location?)<br><br>        /**<br>         * invokes on user location finding failure<br>         */<br>        abstract fun onLocationUpdateFailed()<br>    }<br>}</pre><p>Bu, kullanıcının konumunu hem GPS hem de ağ sağlayıcıları kullanarak almak için bir yardımcı sınıftır.</p><ul><li>GPS ve ağ sağlayıcılarının etkin olup olmadığını kontrol etmek için LocationManager kullanır.</li><li>Her iki sağlayıcı için de konum güncellemelerini almak için konum dinleyicilerini kaydeder.</li><li>Belirli bir süre sonra konum güncellemelerini iptal etmek için bir zamanlayıcı kullanır.</li><li>GetLastLocation iç içe sınıfı, her iki sağlayıcıdan son bilinen konumu almak ve en güncel olanı belirlemekten sorumludur.</li></ul><p><em>Tebrikler! artık Android uygulamalarınızda Google Maps SDK kullanımını ve Kullanıcının Konumunu alıp harita üzerinde gösterme işlemlerini yapabilirsiniz.</em></p><p><em>Herkese iyi çalışmalar dilerim :)</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3c8fcda107cf" width="1" height="1" alt=""><hr><p><a href="https://medium.com/appcent/android-projeleremizde-google-maps-sdk-kurulumu-ve-kolay-kullan%C4%B1m%C4%B1-3c8fcda107cf">Android Projeleremizde Google Maps SDK Kurulumu ve Kolay Kullanımı</a> was originally published in <a href="https://medium.com/appcent">Appcent</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Uygulamalarında Veri Şifreleme: Jetpack Security ile Daha Güvenli Uygulamalar]]></title>
            <link>https://medium.com/appcent/android-uygulamalar%C4%B1nda-veri-%C5%9Fifreleme-jetpack-security-ile-daha-g%C3%BCvenli-uygulamalar-38f491f70ec1?source=rss-b3e02897b105------2</link>
            <guid isPermaLink="false">https://medium.com/p/38f491f70ec1</guid>
            <dc:creator><![CDATA[Mert Melih Aytemur]]></dc:creator>
            <pubDate>Wed, 13 Sep 2023 07:50:31 GMT</pubDate>
            <atom:updated>2023-09-13T07:50:31.200Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*f3GimdpugXKS__BkHaRBiA.png" /></figure><p>Android uygulamalarında hassas verileri güvenli bir şekilde saklamak her zaman önemlidir. Bu yazıda, Jetpack Securitykütüphanesini kullanarak Android uygulamalarında verilerin nasıl şifreleneceğini ve şifresinin nasıl çözüleceğini göstereceğiz.</p><p>Hadi başlayalım!</p><h3>Android Jetpack Security Kütüphanesi Nedir?</h3><p>Android Jetpack Security kütüphanesi, Android uygulamalarının hassas verilerini daha güvenli bir şekilde saklamak için kullanılan bir araçtır. Bu kütüphane, veri şifreleme ve şifre çözme işlemlerini kolaylaştırmak ve güvenlik önlemlerini artırmak amacıyla geliştirilmiştir. İşte Jetpack Security kütüphanesinin bazı temel özellikleri:</p><ol><li><strong>Veri Şifreleme</strong>: Jetpack Security, verilerinizi güçlü bir şekilde şifrelemek için kullanabilir. Bu sayede, verilerinizin yetkisiz erişimden korunmasını sağlayabilirsiniz.</li><li><strong>Hassas Verilerin Güvende Tutulması: </strong>Uygulamanızda sakladığınız kullanıcı şifreleri, API anahtarları veya diğer hassas bilgileri Jetpack Security ile güvende tutabilirsiniz. Bu veriler, şifresiz bir şekilde depolanmaz ve kötü niyetli kullanıcılardan korunur.</li><li><strong>Geliştirici Dostu: </strong>Jetpack Security kütüphanesi, geliştiriciler için kullanımı kolaydır. Android Jetpack bileşenleri ile uyumlu çalışır ve uygulamanızın performansını olumsuz etkilemez.</li><li><strong>Özelleştirilebilirlik: </strong>Kütüphane, şifreleme algoritmalarını ve anahtar yönetimini özelleştirmenize olanak tanır. Bu, uygulamanızın güvenlik gereksinimlerine göre ayarlanabilir.</li></ol><blockquote>Peki, Jetpack Security kütüphanesi kullanarak Android uygulamanızda veri şifrelemeyi nasıl başlatabilirsiniz?</blockquote><blockquote>(Bu senaryoda shared preferences ile lokalde tuttuğumuz verileri şifreleyeceğiz)</blockquote><p><strong>Kütüphane Eklemek:</strong></p><p>İlk adım olarak, uygulamanıza Jetpack Security kütüphanesini eklemeniz gerekecektir. Bu kütüphane, Android Jetpack kütüphaneleri içinde bulunur, bu yüzden Gradle dosyanıza gerekli bağımlılığı eklemelisiniz.</p><pre>implementation &quot;androidx.security:security-crypto:x.y.z&quot;</pre><p><strong>Anahtar Oluşturmak ve Yönetmek:</strong></p><p>Verilerinizi şifrelemek ve çözmek için bir anahtar oluşturmanız gerekecektir. Jetpack Security, bu anahtarların güvenli bir şekilde yönetilmesini sağlar.</p><pre>val masterKeyAlias = MasterKey.Builder(context)<br>        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)<br>        .build()</pre><p><strong>Verileri kaydetmek ve kullanmak için EncryptedSharedPreferences sınıfını kullanarak bir sharedPreferences nesnesi yaratalım.</strong></p><p><strong>EncryptedSharedPreferences</strong></p><p>SharedPreferences sınıfını sarmalar ve otomatik olarak anahtarları ve değerleri iki aşamalı bir yöntem kullanarak şifreler:</p><p>-Anahtarlar (Key), anahtar şifrelemesi algoritması kullanılarak öyle bir şekilde şifrelenir ki anahtar şifrelenebilir ve doğru bir şekilde aranabilir.</p><p>-Değerler (Value), AES-256 GCM kullanılarak şifrelenir.</p><pre>val sharedPreferences = EncryptedSharedPreferences.create(<br>        context,<br>        PREFS_NAME,<br>        masterKeyAlias,<br>        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,<br>        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM<br>    )</pre><blockquote>Context değerini bu yapıyı kullanacağınız ilgili sınıfa constructor injection ile verebilirsiniz.</blockquote><p><strong>Şimdi örnek olarak bir bu verileri yöneteceğimiz bir class ve şifreleyeceğimiz bir token oluşturalım.</strong></p><pre>class ClientPreferences @Inject constructor(<br>@ApplicationContext context: Context) {<br><br>    private val masterKeyAlias = MasterKey.Builder(context)<br>        .setKeyScheme(MasterKey.KeyScheme.AES256_GCM)<br>        .build()<br><br>    private val sharedPreferences = EncryptedSharedPreferences.create(<br>        context,<br>        PREFS_NAME,<br>        masterKeyAlias,<br>        EncryptedSharedPreferences.PrefKeyEncryptionScheme.AES256_SIV,<br>        EncryptedSharedPreferences.PrefValueEncryptionScheme.AES256_GCM<br>    )<br><br>    fun setToken(token: String) {<br>        sharedPreferences.edit().putString(KEY_TOKEN, token).apply()<br>    }<br><br>    fun getToken(): String? {<br>        return sharedPreferences.getString(KEY_TOKEN, null)<br>    }<br><br>    companion object {<br>        private const val PREFS_NAME = &quot;user_prefs&quot;<br>        private const val KEY_TOKEN = &quot;token&quot;<br>    }<br>}</pre><p>Tebrikler, artık Jetpack Security kütüphanesi sayesinde Android uygulamanızdaki hassas verileri güvende tutabilirsiniz. Bu kütüphaneyi kullanarak veri şifrelemeyi ve çözmeyi öğrenerek uygulamanızın güvenliğini artırabilirsiniz.</p><p><em>Okuduğunuz için teşekkür ederim. İyi çalışmalar.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38f491f70ec1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/appcent/android-uygulamalar%C4%B1nda-veri-%C5%9Fifreleme-jetpack-security-ile-daha-g%C3%BCvenli-uygulamalar-38f491f70ec1">Android Uygulamalarında Veri Şifreleme: Jetpack Security ile Daha Güvenli Uygulamalar</a> was originally published in <a href="https://medium.com/appcent">Appcent</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Force Update with Firebase Remote Config in Android Kotlin]]></title>
            <link>https://medium.com/appcent/implementing-force-update-with-firebase-remote-config-in-android-kotlin-9dac829ebd8c?source=rss-b3e02897b105------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dac829ebd8c</guid>
            <category><![CDATA[force-update]]></category>
            <category><![CDATA[remote-config]]></category>
            <category><![CDATA[kotlin]]></category>
            <category><![CDATA[firebase]]></category>
            <dc:creator><![CDATA[Mert Melih Aytemur]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 07:16:08 GMT</pubDate>
            <atom:updated>2023-08-29T07:16:08.972Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G2d96msYc_qNKiRnbpUJjA.png" /></figure><h3>Introduction</h3><p>Keeping your mobile app’s user base up-to-date with the latest features, bug fixes, and security enhancements is crucial. However, users might not always willingly update their apps, which can lead to compatibility issues and potential security vulnerabilities.</p><p>To tackle this challenge, Firebase Remote Config comes to the rescue. In this article, we’ll explore how to leverage Firebase Remote Config to implement a forced app update mechanism in an Android app using Kotlin.</p><blockquote>What is Firebase Remote Config?</blockquote><p>Firebase Remote Config is a cloud-based service provided by Firebase that enables you to customize the behavior and appearance of your app without publishing app updates.</p><p>It allows you to define key-value pairs in the Firebase console, which your app can fetch remotely and apply changes accordingly. This feature becomes particularly powerful when it comes to implementing forced app updates.</p><blockquote>Scenarios for Forced App Updates:</blockquote><ol><li>Critical Bug Fixes: If you discover a critical bug in your app that affects its functionality or security, you might need to force users to update to the latest version that contains the fix.</li><li>Mandatory Feature Rollouts: Sometimes, you might introduce new features that are essential for the app’s core functionality. To ensure a consistent user experience, you can force users to update and access those features.</li><li>Security Updates: Security vulnerabilities can emerge over time. By forcing users to update, you can ensure that they are protected from potential security threats.</li></ol><h3>Implementation Steps:</h3><h4>Step 1: Configure Firebase Project</h4><ol><li>Create a Firebase project if you haven’t already.</li><li>Add your Android app to the project and follow the setup instructions to integrate Firebase into your app.</li></ol><h4>Step 2: Set Up Firebase Remote Config</h4><ol><li>In the Firebase console, navigate to Remote Config and create a new parameters like “android_force_update_required”, “android_force_update_required_version”, “android_force_update_store_url”</li><li>Set the parameter value to true when a forced update is required.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BJdFfsNp5YkfDq1aPiQAjA.png" /></figure><h4>Step 3: Implement Remote Config in Your App</h4><p>1- Add the Firebase Remote Config dependency to your app-level build.gradle file:</p><pre>implementation &#39;com.google.firebase:firebase-config-ktx:x-y-z&#39;</pre><p>2- Initialize Firebase Remote Config in your application class or a relevant activity and fetch remote config values and check for a forced update:</p><p><em>Suggestion is creating ForceUpdateChecker class in here, (Dependency Injection applied via Dagger-Hilt)</em></p><pre>class ForceUpdateChecker @Inject constructor() {<br>    /**<br>     * About [setDefaultsAsync]<br>     * Provided default values for your parameters that act as fallbacks<br>     * in case the actual remote values are not available due to network issues or if the parameters haven&#39;t been fetched yet.<br>     * This helps ensure that your app doesn&#39;t break or behave unexpectedly if there&#39;s a delay in fetching remote configuration values.<br>     *<br>     * Set an interval for fetching config. (Default is 12 hours)<br>     *<br>     * Compare current and required versions.<br>     * If current version is lower than required one, fetch store url and set to Force Update Data Model<br>     * otherwise return null<br>     */<br>    fun checkForceUpdateRequired(updateRequired: (result: ForceUpdateDataModel?) -&gt; Unit) {<br>        val remoteConfig = FirebaseRemoteConfig.getInstance()<br>        remoteConfig.setDefaultsAsync(<br>            mapOf(<br>                KEY_UPDATE_REQUIRED to false,<br>                KEY_REQUIRED_VERSION to BuildConfig.VERSION_NAME,<br>                KEY_UPDATE_URL to &quot;store_url&quot;<br>            )<br>        ).addOnCompleteListener {<br>            remoteConfig.fetch(MINIMUM_FETCH_INTERVAL).addOnCompleteListener {<br>                if (it.isSuccessful) {<br>                    remoteConfig.activate().addOnCompleteListener {<br>                        if (remoteConfig.getBoolean(KEY_UPDATE_REQUIRED)) {<br>                            val currentVersion = (BuildConfig.VERSION_NAME).replace(&quot;.&quot;, &quot;&quot;).toInt()<br><br>                            val requiredVersion =<br>                                remoteConfig.getString(KEY_REQUIRED_VERSION).replace(&quot;.&quot;, &quot;&quot;)<br>                                    .toInt()<br>                            <br>                            if (currentVersion &lt; requiredVersion) {<br>                                updateRequired.invoke(<br>                                    UpdateRequiredModel(<br>                                        updateUrl = remoteConfig.getString(KEY_UPDATE_URL)<br>                                    )<br>                                )<br>                            } else {<br>                                updateRequired.invoke(null)<br>                            }<br>                        }<br>                    }<br>                } else {<br>                    updateRequired.invoke(null)<br>                }<br>            }<br>        }<br>    }<br><br>    companion object {<br>        const val KEY_UPDATE_REQUIRED = &quot;android_force_update_required&quot;<br>        const val KEY_REQUIRED_VERSION = &quot;android_force_update_required_version&quot;<br>        const val KEY_UPDATE_URL = &quot;android_force_update_store_url&quot;<br>        const val MINIMUM_FETCH_INTERVAL = 60L<br>    }<br>}<br><br>data class UpdateRequiredModel(<br>    val updateUrl: String? = null<br>)</pre><p>and use <strong>ForceUpdateChecker</strong> in your class that you want to check the incoming updates. eg: Splash Screen</p><pre>@Inject<br>lateinit var forceUpdateChecker: ForceUpdateChecker<br><br>private fun updateChecker() {<br>        forceUpdateChecker.checkForceUpdateRequired { updateRequiredModel -&gt;<br>            if (updateRequiredModel != null) {<br>                // pop up a non-cancellable dialog for giving information about new version <br>            } else {<br>                // do something<br>            }<br>        }<br>    }</pre><h3>Conclusion</h3><p>Firebase Remote Config simplifies the process of implementing forced app updates, ensuring that users have the latest version of your app containing critical fixes and features. By following the steps outlined in this article, you can enhance your app’s stability, security, and user experience while maintaining control over the update process.</p><p><em>That’s all. Thank you for reading!</em></p><h4>References:</h4><p><a href="https://firebase.google.com/docs/remote-config/get-started?platform=android">https://firebase.google.com/docs/remote-config/get-started?platform=android</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dac829ebd8c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/appcent/implementing-force-update-with-firebase-remote-config-in-android-kotlin-9dac829ebd8c">Implementing Force Update with Firebase Remote Config in Android Kotlin</a> was originally published in <a href="https://medium.com/appcent">Appcent</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Kotlin — Firebase Remote Config ile Force Update Kurulumu]]></title>
            <link>https://medium.com/appcent/android-kotlin-firebase-remote-config-ile-force-update-kurulumu-d223b9c809f2?source=rss-b3e02897b105------2</link>
            <guid isPermaLink="false">https://medium.com/p/d223b9c809f2</guid>
            <dc:creator><![CDATA[Mert Melih Aytemur]]></dc:creator>
            <pubDate>Tue, 29 Aug 2023 07:14:04 GMT</pubDate>
            <atom:updated>2023-08-29T07:14:04.818Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G2d96msYc_qNKiRnbpUJjA.png" /></figure><h3>Android-Kotlin: Firebase Remote Config ile Force Update Kurulumu</h3><h3>Giriş</h3><p>Mobil uygulamanızın kullanıcı tabanını en son özellikler, hata düzeltmeleri ve güvenlik güncellemeleriyle güncel tutmak son derece önemlidir. Ancak kullanıcılar uygulamalarını her zaman isteyerek güncellemezler. Bu da uyumluluk sorunlarına ve olası güvenlik açıklarına yol açabilir.</p><p>Bu zorluğun üstesinden gelmek için Firebase Remote Config devreye girer. Bu makalede, Kotlin kullanarak Android uygulamasında force update mekanizması uygulamak için Firebase Remote Config nasıl kullanacağımızı keşfedeceğiz.</p><blockquote>Firebase Remote Config Nedir?</blockquote><p>Firebase Uzaktan Yapılandırma, Firebase tarafından sağlanan bulut tabanlı bir hizmettir ve uygulamanızın davranışını ve görünümünü uygulama güncellemelerini yayınlamadan özelleştirmenizi sağlar.</p><p>Firebase konsolunda anahtar-değer çiftleri tanımlamanıza olanak tanır, uygulamanız bu değerleri uzaktan alabilir ve değişiklikleri buna göre uygulayabilir. Bu özellik, zorunlu uygulama güncellemelerini uygularken özellikle güçlü bir hale gelir.</p><blockquote>Force Update Senaryoları</blockquote><ol><li>Kritik Hata Düzeltmeleri: Uygulamanızda işlevselliği veya güvenliği etkileyen kritik bir hata keşfederseniz, kullanıcıları düzeltmeyi içeren en son sürüme zorlamak gerekebilir.</li><li>Zorunlu Özellik Dağıtımları: Ara sıra, uygulamanın temel işlevselliği için gereken yeni özellikler ekleyebilirsiniz. Tutarlı bir kullanıcı deneyimi sağlamak için kullanıcıları güncellemeye ve bu özelliklere erişmeye zorlayabilirsiniz.</li><li>Güvenlik Güncellemeleri: Zamanla güvenlik açıkları ortaya çıkabilir. Kullanıcıları güncellemeye zorlayarak potansiyel güvenlik tehditlerine karşı korunmalarını sağlayabilirsiniz.</li></ol><h3>Uygulama Adımları</h3><h4>1.Adım: Firebase Projesini Yapılandırma</h4><p>Henüz yapmadıysanız Firebase projesi oluşturun. Android uygulamanızı projeye ekleyin ve Firebase’i uygulamanıza entegre etmek için kurulum talimatlarını izleyin.</p><h4>2.Adım : Remote Config Parametreleri Girme</h4><ol><li>Firebase Remote Config Ayarları için Firebase konsolunda remote config alanına gidin ve “android_force_update_required”, “android_force_update_required_version”, “android_force_update_store_url” gibi yeni parametreler oluşturun.</li><li>Zorunlu bir güncelleme gerektiğinde “android_force_update_required_version” parametre değerini güncel versiyon olarak ayarlayın.</li><li>Force update’i kapatmak için “android_force_update_required” değerini false olarak değiştirebilirsiniz.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ThkRwrmm41mhCob3.png" /></figure><h4>3.Adım: Proje Üzerinde Firebase Remote Config Yapılandırması</h4><ol><li>Uygulama düzeyindeki build.gradle dosyanıza Firebase Uzaktan Yapılandırma bağımlılığını ekleyin</li></ol><pre>implementation &#39;com.google.firebase:firebase-config-ktx:x-y-z&#39;</pre><p>2. Uygulama sınıfınızda veya ilgili bir etkinlikte Firebase Remote Config’i başlatın ve config değerlerini alın. Zorunlu bir güncelleme için kontrol edin: Öneri: Burda oluşturulan ForceUpdateChekcer sınıfını referans alabilirsiniz.</p><p>(Dagger-Hilt Kullanılmıştır)</p><pre>class ForceUpdateChecker @Inject constructor() {<br>    /**<br>     * About [setDefaultsAsync]<br>     * Provided default values for your parameters that act as fallbacks<br>     * in case the actual remote values are not available due to network issues or if the parameters haven&#39;t been fetched yet.<br>     * This helps ensure that your app doesn&#39;t break or behave unexpectedly if there&#39;s a delay in fetching remote configuration values.<br>     *<br>     * Set an interval for fetching config. (Default is 12 hours)<br>     *<br>     * Compare current and required versions.<br>     * If current version is lower than required one, fetch store url and set to Force Update Data Model<br>     * otherwise return null<br>     */<br>    fun checkForceUpdateRequired(updateRequired: (result: ForceUpdateDataModel?) -&gt; Unit) {<br>        val remoteConfig = FirebaseRemoteConfig.getInstance()<br>        remoteConfig.setDefaultsAsync(<br>            mapOf(<br>                KEY_UPDATE_REQUIRED to false,<br>                KEY_REQUIRED_VERSION to BuildConfig.VERSION_NAME,<br>                KEY_UPDATE_URL to &quot;store_url&quot;<br>            )<br>        ).addOnCompleteListener {<br>            remoteConfig.fetch(MINIMUM_FETCH_INTERVAL).addOnCompleteListener {<br>                if (it.isSuccessful) {<br>                    remoteConfig.activate().addOnCompleteListener {<br>                        if (remoteConfig.getBoolean(KEY_UPDATE_REQUIRED)) {<br>                            val currentVersion = (BuildConfig.VERSION_NAME).replace(&quot;.&quot;, &quot;&quot;).toInt()<br><br>                            val requiredVersion =<br>                                remoteConfig.getString(KEY_REQUIRED_VERSION).replace(&quot;.&quot;, &quot;&quot;)<br>                                    .toInt()<br>                            <br>                            if (currentVersion &lt; requiredVersion) {<br>                                updateRequired.invoke(<br>                                    UpdateRequiredModel(<br>                                        updateUrl = remoteConfig.getString(KEY_UPDATE_URL)<br>                                    )<br>                                )<br>                            } else {<br>                                updateRequired.invoke(null)<br>                            }<br>                        }<br>                    }<br>                } else {<br>                    updateRequired.invoke(null)<br>                }<br>            }<br>        }<br>    }<br><br>    companion object {<br>        const val KEY_UPDATE_REQUIRED = &quot;android_force_update_required&quot;<br>        const val KEY_REQUIRED_VERSION = &quot;android_force_update_required_version&quot;<br>        const val KEY_UPDATE_URL = &quot;android_force_update_store_url&quot;<br>        const val MINIMUM_FETCH_INTERVAL = 60L<br>    }<br>}<br><br>data class UpdateRequiredModel(<br>    val updateUrl: String? = null<br>)</pre><p>Ve gelen güncellemeleri kontrol etmek istediğiniz sınıfta ForceUpdateChecker’ı kullanın. Örneğin: Splash Ekranı</p><pre>@Inject<br>lateinit var forceUpdateChecker: ForceUpdateChecker<br><br>private fun updateChecker() {<br>        forceUpdateChecker.checkForceUpdateRequired { updateRequiredModel -&gt;<br>            if (updateRequiredModel != null) {<br>                // pop up a non-cancellable dialog for giving information about new version <br>            } else {<br>                // do something<br>            }<br>        }<br>    }</pre><h3>Sonuç</h3><p>Firebase Remote Config, zorunlu uygulama güncellemelerini uygulamanın en son sürümünü içeren kritik düzeltmeler ve özelliklerle kullanıcıların sahip olmasını sağlayarak süreci basitleştirir. Bu makalede anlatılan adımları takip ederek, uygulamanızın kararlılığını, güvenliğini ve kullanıcı deneyimini artırabilir ve güncelleme süreci üzerinde kontrolünüzü koruyabilirsiniz.</p><p><em>Okuduğunuz için teşekkür ederim.</em></p><h4>Referanslar</h4><p><a href="https://firebase.google.com/docs/remote-config/get-started?platform=android">https://firebase.google.com/docs/remote-config/get-started?platform=android</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d223b9c809f2" width="1" height="1" alt=""><hr><p><a href="https://medium.com/appcent/android-kotlin-firebase-remote-config-ile-force-update-kurulumu-d223b9c809f2">Android Kotlin — Firebase Remote Config ile Force Update Kurulumu</a> was originally published in <a href="https://medium.com/appcent">Appcent</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Android Activity Launch Modes: A Powerful Tool to Manage Your Application]]></title>
            <link>https://medium.com/@aytemurmertmelih/android-activity-launch-modes-a-powerful-tool-to-manage-your-application-da08183cd56b?source=rss-b3e02897b105------2</link>
            <guid isPermaLink="false">https://medium.com/p/da08183cd56b</guid>
            <dc:creator><![CDATA[Mert Melih Aytemur]]></dc:creator>
            <pubDate>Sun, 23 Jul 2023 19:09:15 GMT</pubDate>
            <atom:updated>2023-07-23T19:25:26.105Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>In the process of Android app development, maximizing user experience and improving app performance are always important goals. To achieve these objectives, we can leverage a powerful tool in the Android platform called “Activity Launch Modes.” Activity Launch Modes determine how an activity should be launched and behave. In this article, we will explore what Android Activity Launch Modes are, their different types, and how they can be utilized in the app development process.</p><blockquote>What is an Activity in Android?</blockquote><p>In Android, an Activity is a fundamental component representing a single screen with a user interface. It plays a crucial role in user interaction and navigation within an app. Activities have a lifecycle and are started using Intents, allowing apps to switch between different screens or functionalities.</p><blockquote>What are Activity Launch Modes?</blockquote><p>Android uses the concept of Activity to allow interactions between different components of an app and within the app itself. Activity Launch Modes are a set of rules and options that determine how an activity will behave when it is launched.</p><blockquote>Types of Activity Launch Modes</blockquote><h4>1. Standard Launch Mode:</h4><p>This is the default Activity Launch Mode. Whenever an activity is started using the startActivity() method, it is launched in the standard mode. A new instance is always created, and the current activity is added to the back stack.</p><blockquote>A -&gt; B- &gt; C -&gt; B -&gt; C</blockquote><p>In this example, each arrow represents the user navigating from one activity to another. With the Standard Launch Mode, each time the user moves from Activity A to Activity B or from Activity B to Activity C, a new instance of the respective activity is created and added to the back stack.</p><p>When the user presses the back button, they will return to the previous activity in the back stack. So, after pressing the back button from Activity C, they will return to Activity B, and if they press the back button again, they will return to Activity A.</p><h4>2. SingleTop Launch Mode:</h4><p>In this mode, if the target activity is already at the top of the stack, instead of creating a new instance, the existing instance is reused. As a result, the onCreate() method is not called again, but the onNewIntent() method is invoked.</p><blockquote>A -&gt; B -&gt; A</blockquote><p>In this example, Activity A and Activity B are part of the same app. With SingleTop Launch Mode, when the user navigates from Activity A to Activity B, a new instance of Activity B is created and added to the back stack.</p><p>However, when the user navigates back to Activity A, the system checks if there is an existing instance of Activity A at the top of the back stack. If one exists, it reuses that instance instead of creating a new one. So, the back stack will look like: A -&gt; B -&gt; A.</p><h4>3. SingleTask Launch Mode:</h4><p>In this mode, the target activity is only created once, and all other activities are cleared. This is particularly useful for representing the main screen of an app. If the target activity is already present in the stack, a new instance is not created, and onNewIntent() is called.</p><blockquote>A -&gt; B -&gt; C -&gt; D to A-&gt; B</blockquote><ol><li>Activity A is launched. The back stack contains: A.</li><li>The user navigates from Activity A to Activity B. The back stack contains: A -&gt; B.</li><li>The user navigates from Activity B to Activity C. The back stack contains: A -&gt; B -&gt; C.</li><li>The user navigates from Activity C to Activity D. The back stack contains: A -&gt; B -&gt; C -&gt; D.</li><li>Now, suppose the user decides to start Activity B again. In SingleTask Launch Mode, when the user starts an activity that already exists in the back stack, the system reuses the existing instance of that activity and clears all activities on top of it. So, the back stack becomes: A -&gt; B.</li></ol><h4>4. SingleInstance Launch Mode:</h4><p>In this mode, the target activity can only be launched in its own task. This is ideal for an activity that requires interaction between different apps. For example, consider an activity used for making a phone call; this activity can be called from different apps and runs in its own private task space.</p><blockquote>(Task 1) A -&gt; B -&gt; C</blockquote><blockquote>(Task 2) D</blockquote><ol><li>Activity A is launched. The back stack for Task 1 contains: A.</li><li>The user navigates from Activity A to Activity B. The back stack for Task 1 contains: A -&gt; B.</li><li>The user navigates from Activity B to Activity C. The back stack for Task 1 contains: A -&gt; B -&gt; C.</li><li>Now, the user creates Activity D. Since Activity D has SingleInstance Launch Mode, it is launched in its own separate task. So, the back stack for Task 2 contains: D.</li></ol><p>At this point, Task 1 contains Activity A, Activity B, and Activity C in its back stack, while Task 2 contains Activity D.</p><h3>How to Use Activity Launch Modes?</h3><p>To specify Activity Launch Modes, you can add the launchMode attribute inside the &lt;activity&gt; tag in the manifest file. For example, to use SingleTop mode, you can specify it as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ApnipKAdWwTCL8HohaMD6Q.png" /></figure><blockquote>The Importance of Activity Launch Modes</blockquote><p>Activity Launch Modes can significantly impact your app’s behavior and performance. Choosing the right mode can enhance user experience and make transitions between activities smoother. Selecting appropriate modes is crucial, especially to prevent the back button from taking the user to an unexpected screen.</p><h3>Conclusion</h3><p>Android Activity Launch Modes are a powerful tool in the app development process. By choosing the right modes, you can improve app performance, enhance user experience, and make transitions between activities smoother. Each mode has its own characteristics, so remember to choose the one that suits your needs best. We hope this article has provided you with a fundamental understanding of Activity Launch Modes. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=da08183cd56b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>