Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

week8-seorin #40

Merged
merged 1 commit into from
Nov 28, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
14 changes: 14 additions & 0 deletions CloneCoding/app/build.gradle.kts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,9 @@ plugins {
id("com.android.application")
id("org.jetbrains.kotlin.android")
id("kotlin-kapt")
// Add the Google services Gradle plugin
id("com.google.gms.google-services")

}

val localPropertiesFile = rootProject.file("local.properties")
Expand Down Expand Up @@ -62,4 +65,15 @@ dependencies {
//Retrofit
implementation("com.squareup.retrofit2:retrofit:2.9.0")
implementation("com.squareup.retrofit2:converter-gson:2.9.0")

// Google map
implementation("com.google.android.gms:play-services-maps:19.0.0")
implementation("com.google.android.gms:play-services-maps-license:12.0.1")

//firebase
implementation(platform("com.google.firebase:firebase-bom:33.6.0"))
implementation("com.google.firebase:firebase-analytics")

//admob
implementation("com.google.android.gms:play-services-ads:23.5.0")
}
29 changes: 29 additions & 0 deletions CloneCoding/app/google-services.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
{
"project_info": {
"project_number": "600435955305",
"project_id": "airquality1-31914",
"storage_bucket": "airquality1-31914.firebasestorage.app"
},
"client": [
{
"client_info": {
"mobilesdk_app_id": "1:600435955305:android:fccfcff31cd66d93d4b4f8",
"android_client_info": {
"package_name": "com.rinylecture.airquality"
}
},
"oauth_client": [],
"api_key": [
{
"current_key": "AIzaSyB3JQsTlwSiTpXkUxgz6-PKn13AWwvVvmU"
}
],
"services": {
"appinvite_service": {
"other_platform_oauth_client": []
}
}
}
],
"configuration_version": "1"
}
24 changes: 18 additions & 6 deletions CloneCoding/app/src/main/AndroidManifest.xml
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools">
xmlns:tools="http://schemas.android.com/tools"
package="com.rinylecture.AirQuality">

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />

<application
android:allowBackup="true"
Expand All @@ -16,15 +17,26 @@
android:supportsRtl="true"
android:theme="@style/Theme.CloneCoding"
tools:targetApi="31">

<activity
android:name=".MapActivity"
android:exported="false" />

<meta-data
android:name="com.google.android.geo.API_KEY"
android:value="AIzaSyAIl-iGqkzKv71tfr2qyTjyKNk9nVsi_tE" />

<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="ca-app-pub-4436953205347547~4512638886" />

<activity
android:name=".MainActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>

</manifest>
Original file line number Diff line number Diff line change
Expand Up @@ -30,8 +30,8 @@ class LocationProvider (val context : Context){
return null
}else{
if(ActivityCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_FINE_LOCATION
context,
Manifest.permission.ACCESS_FINE_LOCATION
) != PackageManager.PERMISSION_GRANTED && ActivityCompat.checkSelfPermission(
context,
Manifest.permission.ACCESS_COARSE_LOCATION
Expand Down
144 changes: 134 additions & 10 deletions CloneCoding/app/src/main/java/com/rinylecture/AirQuality/MainActivity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -10,13 +10,24 @@ import android.location.Geocoder
import android.location.LocationManager
import android.os.Bundle
import android.provider.Settings
import android.util.Log
import android.widget.Toast
import androidx.activity.result.ActivityResult
import androidx.activity.result.ActivityResultCallback
import androidx.activity.result.ActivityResultLauncher
import androidx.activity.result.contract.ActivityResultContracts
import androidx.appcompat.app.AlertDialog
import androidx.appcompat.app.AppCompatActivity
import androidx.core.app.ActivityCompat
import androidx.core.content.ContextCompat
import com.google.android.gms.ads.AdError
import com.google.android.gms.ads.AdListener
import com.google.android.gms.ads.AdRequest
import com.google.android.gms.ads.FullScreenContentCallback
import com.google.android.gms.ads.LoadAdError
import com.google.android.gms.ads.MobileAds
import com.google.android.gms.ads.interstitial.InterstitialAd
import com.google.android.gms.ads.interstitial.InterstitialAdLoadCallback
import com.rinylecture.AirQuality.databinding.ActivityMainBinding
import com.rinylecture.AirQuality.retrofit.AirQualityResponse
import com.rinylecture.AirQuality.retrofit.AirQualityService
Expand All @@ -33,18 +44,40 @@ import java.util.Locale

class MainActivity : AppCompatActivity() {

var mInterstitialAd : InterstitialAd? = null

lateinit var binding : ActivityMainBinding

// 위도와 경도를 가져올 때 필요
lateinit var locationProvider: LocationProvider

// 런타임 권한 요청 시 필요한 요청 코드
private val PERMISSIONS_REQUEST_CODE = 100

var latitude : Double? = 0.0
var longitude : Double? = 0.0

// 요청할 권한 목록
val REQUIRED_PERMISSIONS = arrayOf(
Manifest.permission.ACCESS_FINE_LOCATION,
Manifest.permission.ACCESS_COARSE_LOCATION
)

// 위치 서비스 요청 시 필요한 런처
lateinit var getGPSPermissionLauncher : ActivityResultLauncher<Intent>

val startMapActivityResult = registerForActivityResult(ActivityResultContracts.StartActivityForResult(),
object : ActivityResultCallback<ActivityResult>{
override fun onActivityResult(result: ActivityResult) {
if(result?.resultCode?: 0 == Activity.RESULT_OK){
latitude = result?.data?.getDoubleExtra("latitude",0.0) ?: 0.0
longitude = result?.data?.getDoubleExtra("longitude",0.0) ?: 0.0
updateUI()
}
}
}
)

override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
Expand All @@ -53,34 +86,90 @@ class MainActivity : AppCompatActivity() {
checkAllPermissions()
updateUI()
setRefreshButton()

setFab()
setBannerAds()
}

override fun onResume() {
super.onResume()
setInterstitialAds()
}

private fun setInterstitialAds(){
val adRequest = AdRequest.Builder().build()

InterstitialAd.load(this, "/21775744923/example/interstitial", adRequest, object : InterstitialAdLoadCallback(){
override fun onAdLoaded(p0: InterstitialAd) {
super.onAdLoaded(p0)

Log.d("Ads Log", "전면 광고가 로드 성공했습니다.")
mInterstitialAd = p0
}

override fun onAdFailedToLoad(p0: LoadAdError) {
super.onAdFailedToLoad(p0)
Log.d("Ads Log", "전면 광고가 ")
}
})
}

private fun setBannerAds(){
MobileAds.initialize(this)
val adRequest = AdRequest.Builder().build()
binding.adsBanner.loadAd(adRequest)

binding.adsBanner.adListener = object : AdListener(){
override fun onAdLoaded() {
super.onAdLoaded()
Log.d("Ads Log", "배너 광고가 로드 되었습니다.")
}

override fun onAdFailedToLoad(p0: LoadAdError) {
super.onAdFailedToLoad(p0)
Log.d("Ads Log", "배너 광고가 로드 실패되었습니다.")
}

override fun onAdClicked() {
super.onAdClicked()
Log.d("Ads Log", "배너 광고가 클릭되었습니다.")
}
}
}

private fun updateUI(){
locationProvider = LocationProvider(this@MainActivity)

val latitude: Double? = locationProvider.getLocationLatitude()
val longitude: Double? = locationProvider.getLocationLongitude()
if(latitude == 0.0 && longitude == 0.0) {
// 위도와 경도 정보 가져오기
latitude = locationProvider.getLocationLatitude()
longitude = locationProvider.getLocationLongitude()
}

if(latitude != null && longitude != null){
// 1. 현재 위치 가져오고 UI 업데이트
val address = getCurrentAddress(latitude, longitude)
// 현재 위치 가져오기
val address = getCurrentAddress(latitude!!, longitude!!)

// 주소가 null이 아닐 경우 UI 업데이트
address?.let{
binding.tvLocationTitle.text = "${it.thoroughfare}"
binding.tvLocationSubtitle.text = "${it.countryName} ${it.adminArea}"
}
// 2. 미세먼지 농도 가져오고 UI 업데이트
getAirQualityData(latitude, longitude)
getAirQualityData(latitude!!, longitude!!)
}else{
Toast.makeText(this,"위도, 경도 정보를 가져올 수 없습니다.", Toast.LENGTH_LONG).show()
}
}

private fun getAirQualityData(latitude: Double, longitude: Double){
// Retrofit API 인터페이스 생성
var retrofitAPI = RetrofitConnection.getInstance().create(
AirQualityService::class.java
)

// API 호출 실행
retrofitAPI.getAirQualityData(
latitude.toString(),
longitude.toString(),
Expand All @@ -102,9 +191,7 @@ class MainActivity : AppCompatActivity() {
t.printStackTrace()
Toast.makeText(this@MainActivity, "데이터를 가져오는 데 실패했습니다.", Toast.LENGTH_LONG).show()
}
}
)
// execute
})
}

private fun updateAirUI(airQualityData : AirQualityResponse){
Expand Down Expand Up @@ -148,6 +235,43 @@ class MainActivity : AppCompatActivity() {
}
}

private fun setFab(){
binding.fab.setOnClickListener{

if(mInterstitialAd!=null){
mInterstitialAd!!.fullScreenContentCallback = object : FullScreenContentCallback(){
override fun onAdDismissedFullScreenContent() {
super.onAdDismissedFullScreenContent()
Log.d("Ads Log", "전면 광고 닫혔습니다.")
val intent = Intent(this@MainActivity, MapActivity::class.java)
intent.putExtra("currentLat", latitude)
intent.putExtra("currentLng", longitude)
startMapActivityResult.launch(intent)
}

override fun onAdFailedToShowFullScreenContent(p0: AdError) {
super.onAdFailedToShowFullScreenContent(p0)
Log.d("Ads Log", "전면 광고 열기 실패했습니다.")
}

override fun onAdShowedFullScreenContent() {
super.onAdShowedFullScreenContent()
Log.d("Ads Log", "전면 광고 열기 성공했습니다.")
mInterstitialAd = null
}
}

mInterstitialAd!!.show(this@MainActivity)

}else{
Log.d("Ads Log", "전면 광고가 로딩이 안 되었습니다.")
Toast.makeText(this, "잠시 후 시도해주세요.", Toast.LENGTH_LONG).show()
}


}
}

private fun getCurrentAddress(latitude: Double, longitude: Double) : Address? {
val geoCoder = Geocoder(this, Locale.KOREA)
val addresses : List<Address>?
Expand All @@ -171,14 +295,14 @@ class MainActivity : AppCompatActivity() {
}

private fun checkAllPermissions(){
if(!isLocationServiceAvailabale()){
if(!isLocationServiceAvailable()){
showDialogForLocationServiceSetting()
}else {
isRunTimePermissionGranted()
}
}

private fun isLocationServiceAvailabale() : Boolean{
private fun isLocationServiceAvailable() : Boolean{
val locationManager = getSystemService(LOCATION_SERVICE) as LocationManager

return (locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER) || locationManager.isProviderEnabled((LocationManager.NETWORK_PROVIDER)))
Expand Down Expand Up @@ -225,7 +349,7 @@ class MainActivity : AppCompatActivity() {
ActivityResultContracts.StartActivityForResult()
){ result ->
if(result.resultCode == Activity.RESULT_OK){
if(isLocationServiceAvailabale()){
if(isLocationServiceAvailable()){
isRunTimePermissionGranted()
}else{
Toast.makeText(this, "위치 서비스를 사용할 수 없습니다.", Toast.LENGTH_LONG).show()
Expand Down
Loading