티스토리 뷰
[개요]
- 안드로이드 프로그래밍 관련 게시물
- 예제의 기능은 두 개의 수를 입력하여 그 곱을 출력
- 앱 화면 하단에 광고를 표시하도록 함.
- 유료 결제 사용자인 경우, 광고가 제거되도록 설정됨.
package com.example.multiplyapp
import android.os.Bundle
import android.widget.Button
import android.widget.EditText
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.android.billingclient.api.*
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.AdView
import com.google.android.gms.ads.MobileAds
class MainActivity : AppCompatActivity(), PurchasesUpdatedListener {
private lateinit var adView: AdView
private lateinit var billingClient: BillingClient
private val removeAdsProductId = "remove_ads" // Replace with your product ID from Play Console
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// Initialize AdMob
MobileAds.initialize(this)
adView = findViewById(R.id.adView)
// Initialize Play Billing Client
billingClient = BillingClient.newBuilder(this)
.enablePendingPurchases()
.setListener(this)
.build()
billingClient.startConnection(object : BillingClientStateListener {
override fun onBillingSetupFinished(billingResult: BillingResult) {
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK) {
checkPurchaseStatus()
}
}
override fun onBillingServiceDisconnected() {
// Handle billing service disconnection
}
})
// UI Elements
val num1EditText: EditText = findViewById(R.id.editTextNumber1)
val num2EditText: EditText = findViewById(R.id.editTextNumber2)
val resultTextView: TextView = findViewById(R.id.resultTextView)
val multiplyButton: Button = findViewById(R.id.multiplyButton)
val removeAdsButton: Button = findViewById(R.id.removeAdsButton)
// Multiply Button Click Listener
multiplyButton.setOnClickListener {
val num1 = num1EditText.text.toString().toDoubleOrNull()
val num2 = num2EditText.text.toString().toDoubleOrNull()
if (num1 != null && num2 != null) {
val result = num1 * num2
resultTextView.text = "Result: $result"
} else {
resultTextView.text = "Please enter valid numbers"
}
}
// Remove Ads Button Click Listener
removeAdsButton.setOnClickListener {
startPurchaseFlow()
}
}
private fun startPurchaseFlow() {
val skuList = listOf(removeAdsProductId)
val params = SkuDetailsParams.newBuilder()
.setSkusList(skuList)
.setType(BillingClient.SkuType.INAPP)
.build()
billingClient.querySkuDetailsAsync(params) { billingResult, skuDetailsList ->
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK && !skuDetailsList.isNullOrEmpty()) {
val skuDetails = skuDetailsList[0]
val flowParams = BillingFlowParams.newBuilder()
.setSkuDetails(skuDetails)
.build()
billingClient.launchBillingFlow(this, flowParams)
}
}
}
private fun checkPurchaseStatus() {
val purchaseResult = billingClient.queryPurchases(BillingClient.SkuType.INAPP)
val purchasesList = purchaseResult.purchasesList
if (purchasesList != null) {
for (purchase in purchasesList) {
if (purchase.skus.contains(removeAdsProductId)) {
handlePurchase(purchase)
return
}
}
}
// Show ads if purchase not found
loadAds()
}
private fun loadAds() {
val adRequest = AdRequest.Builder().build()
adView.loadAd(adRequest)
}
override fun onPurchasesUpdated(billingResult: BillingResult, purchases: MutableList<Purchase>?) {
if (billingResult.responseCode == BillingClient.BillingResponseCode.OK && purchases != null) {
for (purchase in purchases) {
if (purchase.skus.contains(removeAdsProductId)) {
handlePurchase(purchase)
}
}
}
}
private fun handlePurchase(purchase: Purchase) {
// Grant purchase benefits
savePurchaseStatus(true)
adView.visibility = AdView.GONE
}
private fun savePurchaseStatus(isPurchased: Boolean) {
val sharedPreferences = getSharedPreferences("app_prefs", MODE_PRIVATE)
sharedPreferences.edit().putBoolean("ads_removed", isPurchased).apply()
}
private fun isPurchaseSaved(): Boolean {
val sharedPreferences = getSharedPreferences("app_prefs", MODE_PRIVATE)
return sharedPreferences.getBoolean("ads_removed", false)
}
}
[build.gradle]
implementation 'com.google.android.gms:play-services-ads:22.2.0'
implementation 'com.android.billingclient:billing:6.0.1'
[AndroidManifest.xml]
<uses-permission android:name="android.permission.INTERNET" />
<application>
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="YOUR_ADMOB_APP_ID" /> <!-- Replace with your AdMob App ID -->
</application>
[activity_main.xml]
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="16dp">
<EditText
android:id="@+id/editTextNumber1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter first number"
android:inputType="numberDecimal" />
<EditText
android:id="@+id/editTextNumber2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Enter second number"
android:inputType="numberDecimal" />
<Button
android:id="@+id/multiplyButton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Multiply" />
<TextView
android:id="@+id/resultTextView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Result will appear here"
android:textSize="18sp"
android:layout_marginTop="16dp"/>
<com.google.android.gms.ads.AdView
android:id="@+id/adView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
ads:adSize="BANNER"
ads:adUnitId="ca-app-pub-3940256099942544/6300978111" /> <!-- Test Ad Unit ID -->
</LinearLayout>
Play Console에서 인앱 상품 설정
반응형
'SWDesk > App' 카테고리의 다른 글
[Android] ImageView Event Treatment (0) | 2024.06.18 |
---|---|
[Kotlin] Treat Key Event (0) | 2024.06.14 |
[Android] Fragment 개념 (1) | 2024.04.08 |
[Android] 그래프 예제 (2) | 2024.04.06 |
[Android] RecyclerView 예제 (0) | 2024.04.04 |
반응형
250x250
최근에 올라온 글
최근에 달린 댓글
- Total
- Today
- Yesterday
링크
TAG
- Innovations
- 절연형
- Video
- 전류
- 아두이노
- DYOV
- 혁신과허들
- image
- badp
- 빌리언트
- 심심풀이치매방지기
- 오블완
- Decorator
- Innovation&Hurdles
- 전압전류모니터링
- 혁신
- 치매
- bilient
- Innovations&Hurdles
- arduino
- Hurdles
- 허들
- 전압
- BSC
- 티스토리챌린지
- 둎
- 심심풀이
- ServantClock
- 배프
- 치매방지
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | 3 | 4 | |||
5 | 6 | 7 | 8 | 9 | 10 | 11 |
12 | 13 | 14 | 15 | 16 | 17 | 18 |
19 | 20 | 21 | 22 | 23 | 24 | 25 |
26 | 27 | 28 | 29 | 30 | 31 |
글 보관함