Do parent build.gradle přidat:
buildscript { repositories { google() jcenter() maven {url 'http://developer.huawei.com/repo/'} } dependencies { classpath "com.android.tools.build:gradle:4.0.0" classpath 'com.huawei.agconnect:agcp:1.4.0.300' // NOTE: Do not place your application dependencies here; they belong // in the individual module build.gradle files } } allprojects { repositories { google() jcenter() maven { url 'http://developer.huawei.com/repo/' } } } task clean(type: Delete) { delete rootProject.buildDir }
Projektový build.gradle:
apply plugin: 'com.android.application' android { compileSdkVersion 29 buildToolsVersion "30.0.0" defaultConfig { applicationId "cz.inited.test.huawei.push" minSdkVersion 23 targetSdkVersion 29 versionCode 1 versionName "1.0" } } dependencies { implementation fileTree(dir: "libs", include: ["*.jar"]) implementation 'androidx.appcompat:appcompat:1.2.0' implementation 'androidx.constraintlayout:constraintlayout:1.1.3' implementation 'com.huawei.hms:push:4.0.3.301' } apply plugin: 'com.huawei.agconnect'
Do aktivity přidat HMS knihovny:
import com.huawei.agconnect.config.AGConnectServicesConfig; import com.huawei.agconnect.config.LazyInputStream; import com.huawei.hms.aaid.HmsInstanceId; import com.huawei.hms.common.ApiException;
Do app/src/main/assets vložit soubor agconnect-services.json , který obsahuje ID aplikace:
{ "client":{ "cp_id":"519042000*****1224430", "product_id":"736430******123209181", "client_id":"43485382*****12388016", "client_secret":"272CC3*************123E3A5D85BB9B649BADF98D781E2453", "app_id":"10*****27123", "package_name":"cz.inited.test.huawei.push", "api_key":"CgB6e3x*************9lVnzBnCnPhoW1j6CLaGrRIJzihva6VJcj3eTd/zZotgflrQC1aA212312312" }, "configuration_version":"1.0" }
Načíst soubor v hlavní aktivitě:
@Override protected void attachBaseContext(Context context) { super.attachBaseContext(context); AGConnectServicesConfig config = AGConnectServicesConfig.fromContext(context); config.overlayWith(new LazyInputStream(context) { public InputStream get(Context context) { try { return context.getAssets().open("agconnect-services.json"); } catch (IOException e) { Log.e(TAG, "Cannot open agconnect-services.json", e); return null; } } }); }
Získat token pro odesílání push notifikací:
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); final Context ctx = this; new Thread() { @Override public void run() { try { // read from agconnect-services.json String appId = AGConnectServicesConfig.fromContext(ctx).getString("client/app_id"); Log.i(TAG, "GET appId:" + appId); String token = HmsInstanceId.getInstance(ctx).getToken(appId, "HCM"); Log.i(TAG, "GET token:" + token); } catch (ApiException e) { Log.e(TAG, "GET token failed, " + e); } } }.start(); }