Android SDK Setting

From AdLocus
Jump to: navigation, search

Getting Start with AdLocus

環境設置

  • Min SDK : 19
  • Compile Sdk Version : 31

Project build.gradle

buildscript {
   repositories {
       google()
       mavenCentral()
       jcenter()
   }
}

Dependency lib

Hyxen SDK

//implementation(name: 'adlocusaar-debug', ext: 'aar')
implementation ('io.github.vfhhu:adlocusaar:4.1.50')

系統

implementation 'com.android.support:appcompat-v7:26.1.0'
testImplementation 'junit:junit:4.12'
androidTestImplementation 'com.android.support.test:runner:1.0.2'
androidTestImplementation 'com.android.support.test.espresso:espresso-core:3.0.2'


Security

// Security
implementation "androidx.security:security-crypto:1.1.0-alpha02"


Json parser

// Json parser
annotationProcessor 'com.bluelinelabs:logansquare-compiler:1.3.6'
implementation 'com.bluelinelabs:logansquare:1.3.7'
implementation "com.github.aurae.retrofit2:converter-logansquare:1.4.1"

Http agent

// Http agent
implementation 'com.squareup.retrofit2:retrofit:2.2.0'

RxJava

implementation 'io.reactivex.rxjava2:rxjava:2.0.6'
implementation 'io.reactivex.rxjava2:rxandroid:2.0.1'
implementation 'com.squareup.retrofit2:adapter-rxjava2:2.2.0'

Google

// 如果有用到 Google Ads 請使用以下版本
implementation 'com.google.android.gms:play-services-ads:21.3.0'

Init SDK設置

  • App First Activity
  • FCM APP key
  • 在AD Locus後台的App key
  • 在Application嘗試取得FCM token,init SDK:
//Init new AdLocus SDK
private void initAdlocus(){
    FirebaseApp.initializeApp(this);
    String token = FirebaseInstanceId.getInstance().getToken();
    if(BuildConfig.DEBUG){
        AdLocus.getInstance(this).checkUserStatement
         (token , {your fcm app key},getPackageName(), {your hynex app key});
        //以下方式不會跳出隱私權視窗(V4.1.45)
        //AdLocus.getInstance(this).registerApp
        // (token , {your fcm app key},getPackageName(), {your hynex app key});
    }else{
        AdLocus.getInstance(this).checkUserStatement
         (token , ‘pass’,getPackageName(), {your hynex app key});
        //以下方式不會跳出隱私權視窗(V4.1.45)
        //AdLocus.getInstance(this).registerApp
        // (token , ‘pass’,getPackageName(), {your hynex app key});
    }
    AdLocus.SetAppName(this,getString(R.string.app_name));//推撥時顯示app名稱,可移除不設定
    if(BuildConfig.DEBUG)AdLocus.testAD(this,0);//測試顯示廣告版面,可移除(0-3種類,0:全部)
}
  • Example: android 10之後需要驗證ACCESS_BACKGROUND_LOCATION才能取得定位資訊
  • Example: android 13之後需要POST_NOTIFICATIONS才會跳廣告通知
if(android.os.Build.VERSION.SDK_INT>= Build.VERSION_CODES.TIRAMISU ){            
    if(ActivityCompat.checkSelfPermission(this, android.Manifest.permission.POST_NOTIFICATIONS) != PackageManager.PERMISSION_GRANTED){
        ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.POST_NOTIFICATIONS}, TAG_NOTIFICATIONS);
    }
}
boolean isReqBackAccess=true;
if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q ){
    isReqBackAccess=ActivityCompat.checkSelfPermission(this, android.Manifest.permission.ACCESS_BACKGROUND_LOCATION) == PackageManager.PERMISSION_GRANTED;
}
if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) == PackageManager.PERMISSION_GRANTED
       && isReqBackAccess) {
 
   initAdlocus();
} else {
   ActivityCompat.requestPermissions(MainActivity.this, new String[]{Manifest.permission.ACCESS_COARSE_LOCATION}, TAG_LOCATION);
}
  • Permission result(不管是否允許permission,都需要init new SDK)
@Override
public void onRequestPermissionsResult(int requestCode,
                                      String permissions[], int[] grantResults) {
   switch (requestCode) {
       case TAG_LOCATION: {
           if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    if(android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q )ActivityCompat.requestPermissions(RailTimeline.this, new String[]{Manifest.permission.ACCESS_BACKGROUND_LOCATION}, TAG_LOCATION_BACKGROUND);
                    else initAdlocus();
                } else {
                    initAdlocus();
                }   
           return;
       }
       case TAG_LOCATION_BACKGROUND:
            initAdlocus();
            return;
   }
}
  • 建立FCM Token receiver:
public class MyFirebaseInstanceIDService extends FirebaseInstanceIdService {
   private final static String TAG = MyFirebaseInstanceIDService.class.getSimpleName();
 
   @Override
   public void onTokenRefresh() {
       // Get updated InstanceID token.
       String refreshedToken = FirebaseInstanceId.getInstance().getToken();
       Logger.d(TAG, "Refreshed token: " + refreshedToken);
 
       // If you want to send messages to this application instance or
       // manage this apps subscriptions on the server side, send the
       // Instance ID token to your app server.
       sendRegistrationToServer(refreshedToken);
   }
   // [END refresh_token]
 
   /**
    * Persist token to third-party servers.
    * <p>
    * Modify this method to associate the user's FCM InstanceID token with any server-side account
    * maintained by your application.
    *
    * @param token The new token.
    */
   private void sendRegistrationToServer(String token) {
       AdLocus.getInstance().updatePushToken(token);
   }
}
  • 建立FCM Message receiver
  • 將收到GetFCMDataResponse.TAG_TARGET的Key若mapping到Constants.TAG_FCM_TARGET則callAdLocus.getInstance().sendFCMMessage(this,data)將FCM傳入SDK
public class MyFirebaseMessagingService extends FirebaseMessagingService {
 
   private static final String TAG = "MyFirebaseMsgService";
 
   /**
    * Called when message is received.
    *
    * @param remoteMessage Object representing the message received from Firebase Cloud Messaging.
    */
   // [START receive_message]
   @Override
   public void onMessageReceived(RemoteMessage remoteMessage) {
       Logger.d(TAG, "From: " + remoteMessage.getFrom());
 
       // Check if message contains a data payload.
       if (remoteMessage.getData().size() > 0) {
           Map<String, String> data = remoteMessage.getData();
           Logger.d(TAG, "Message data payload: " + remoteMessage.getData());
           if (TextUtils.equals(data.get(GetFCMDataResponse.TAG_TARGET), Constants.TAG_FCM_TARGET))
               AdLocus.getInstance().sendFCMMessage(this,data);
           if (/* Check if data needs to be processed by long running job */ true) {
               // For long-running tasks (10 seconds or more) use Firebase Job Dispatcher.
//                scheduleJob();
           } else {
               // Handle message within 10 seconds
//                handleNow();
           }
       }
   }
}
  • 在manifests將FCM message reveiver與FCM token receiver import:
  • Android 10之後須在message reveiver宣告android:foregroundServiceType才能使用定位
<!-- FCM -->
<service android:name=".MyFirebaseInstanceIDService">
   <intent-filter>
       <action android:name="com.google.firebase.INSTANCE_ID_EVENT" />
   </intent-filter>
</service>
 
<service android:name=".MyFirebaseMessagingService"
   android:foregroundServiceType="location">
   <intent-filter>
       <action android:name="com.google.firebase.MESSAGING_EVENT" />
   </intent-filter>
</service>
  • Android 13之後須在添加 NOTIFICATIONS 權限
<uses-permission android:name="android.permission.POST_NOTIFICATIONS"/>

備註

  • 如有使用混淆程式碼,必須在 proguard-android.txt 加入
 keep class com.hyxen.adlocusaar.** {*;}
 keep interface com.hyxen.adlocusaar.** {*;}
 keep enum com.hyxen.adlocusaar.** {*;}
 dontwarn com.squareup.okhttp3.**
 keep class com.squareup.okhttp3.** { *;}
 dontwarn okio.**
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
  • android 13(API 32)之後須加入權限 com.google.android.gms.permission.AD_ID
<uses-permission android:name="com.google.android.gms.permission.AD_ID"/>


  • fcm key只需要在debug模式送出
  • release送出fcm key可能會有洩漏風險
  • 所以只需輸入pass字串
  • 注意1:必須至少執行一次debug模式且帶入fcm key
  • 注意2:BuildConfig 須注意別 import 到其他 Module 的 BuildConfig
  • BuildConfig 須注意別 import 到其他 Module 的 BuildConfig
  • 特別注意,如有app使用 4.1.37 以前的版本,且曾經被play下架或是拒絕過

必須使用4.1.37版及之後或是沒問題的版本並發布到play所有測試及正式區 並設定成100%發布,用以覆蓋所有有問題的版本