i have 2 issues:
the major issue is that if the app is not installed on my phone (android), then the branch link sents me to install it via play store, but then after i install and open it from there i dont have the deep link data.
if the app is already installed and i click the branch link, i need to choose between to open it via chrome or via app,
if i choose chrome -> again no deep link data.
this is the source code:
MainApp.java
public class MainApp extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
#Override public void onStart() {
super.onStart();
try {
Branch.sessionBuilder(this).withCallback(new Branch.BranchReferralInitListener() {
#Override
public void onInitFinished(JSONObject referringParams, BranchError error) {
if (error == null) {
// option 3: navigate to page
Intent intent = new Intent(MainApp.this, Main2Activity.class);
startActivity(intent);
} else {
Log.i("BRANCH SDK", error.getMessage());
}
}
}).withData(this.getIntent().getData()).init();
}
catch (Exception e) {
e.printStackTrace();
}
}
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
try {
setIntent(intent);
// if activity is in foreground (or in backstack but partially visible) launching the same
// activity will skip onStart, handle this case with reInitSession
Branch.sessionBuilder(this).withCallback(branchReferralInitListener).reInit();
}
catch (Exception ignored) { }
}
private Branch.BranchReferralInitListener branchReferralInitListener = new Branch.BranchReferralInitListener() {
#Override
public void onInitFinished(JSONObject linkProperties, BranchError error) {
// do stuff with deep link data (nav to page, display content, etc)
}
};
}
Main2Activity.java
public class Main2Activity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
}
#Override public void onStart() {
super.onStart();
try{
// Branch logging for debugging
Branch.enableLogging();
// Branch object initialization
Branch.getAutoInstance(this);
}
catch (Exception e) {
e.printStackTrace();
}
}
}
AndroidManifest.xml
<?xml version="1.0" encoding="utf-8"?>
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/AppTheme"
android:usesCleartextTraffic="true">
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id" />
<activity
android:name=".MainApp">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- Branch URI Scheme -->
<intent-filter>
<data android:scheme="hello" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
</intent-filter>
</activity>
<!-- Branch init -->
<meta-data android:name="io.branch.sdk.BranchKey" android:value="key_live_jeVWU2AYfrIjpJmslgNxZgjeAwcUzcqK" />
<meta-data android:name="io.branch.sdk.BranchKey.test" android:value="key_test_hlxrWC5Zx16DkYmWu4AHiimdqugRYMr" />
<meta-data android:name="io.branch.sdk.TestMode" android:value="false" /> <!-- Set to true to use Branch_Test_Key (useful when simulating installs and/or switching between debug and production flavors) -->
<activity android:name=".MainActivity" />
<activity android:name=".Main2Activity" >
<!-- Branch App Links (optional) -->
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https" android:host="2rerz.app.link" />
<!-- example-alternate domain is required for App Links when the Journeys/Web SDK and Deepviews are used inside your website. -->
<data android:scheme="https" android:host="2rerz-alternate.app.link" />
</intent-filter>
</activity>
</application>
CustomApplication.java
import android.app.Application;
import io.branch.referral.Branch;
public class CustomApplication extends Application {
#Override
public void onCreate() {
super.onCreate();
// Branch logging for debugging
//Branch.enableLogging();
// Branch object initialization
Branch.getAutoInstance(this);
}
}
The correct Manifest.xml file should be like this -
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id" />
<activity
android:name=".MainApp">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<!-- Branch URI Scheme -->
<intent-filter>
<data android:scheme="hello" />
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
</intent-filter>
<!-- Branch App Links (optional) -->
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https" android:host="2rerz.app.link" />
<!-- example-alternate domain is required for App Links when the Journeys/Web SDK and Deepviews are used inside your website. -->
<data android:scheme="https" android:host="2rerz-alternate.app.link" />
</intent-filter>
</activity>
<!-- Branch init -->
<meta-data android:name="io.branch.sdk.BranchKey" android:value="key_live_jeVWU2AYfrIjpJmslgNxZgjeAwcUzcqK" />
<meta-data android:name="io.branch.sdk.BranchKey.test" android:value="key_test_hlxrWC5Zx16DkYmWu4AHiimdqugRYMr" />
<meta-data android:name="io.branch.sdk.TestMode" android:value="false" /> <!-- Set to true to use Branch_Test_Key (useful when simulating installs and/or switching between debug and production flavors) -->
<activity android:name=".MainActivity" />
<activity android:name=".Main2Activity" >
</activity>
Also, ensure that you are using the correct API Key with the links you are using. If it's a Live Link, then use the Live API key and vice versa.
Related
I am starter at Android, I found this library for deep links, and it's just not working.
After the example beneath, I didn't receive the deep link.
I annotate my activity as in the GitHub example
#DeepLink("http://example.com/{id}")
public class SplashActivity extends AppCompatActivity {
I setup manifest.xml
<activity
android:name="com.example.SplashActivity"
android:exported="true"
android:label="#string/app_name"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="https" android:host="example.com" />
<data android:scheme="http"/>
</intent-filter>
</activity>
And I setup the rest on onCreate method:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.splash_screen);
if (getIntent().getBooleanExtra(DeepLink.IS_DEEP_LINK, false)) {
Bundle parameters = getIntent().getExtras();
Log.d("TAG", "Deeplink params: " + parameters);
String idString = parameters.getString("id");
Log.d("id", idString);
link = idString;
}
I trigger the deep link via adb
adb shell am start -W -a android.intent.action.VIEW -d "http://example.com/123"
I am trying to add snap-kit in my application and I have integrated everything as their documentation. App successfully launched Snapchat app but it's not login it shows an error Something is wrong Here is my complete code and other implementation. This is the official documentation that I have followed https://kit.snapchat.com/docs/login-kit-android
MainActivity
public class MainActivity extends AppCompatActivity {
private ActivityMainBinding binding;
private static final String TAG = "MAIN_ACTIVITY";
String query = "{me{bitmoji{avatar},displayName}}";
String variables = null;
boolean isUserLoggedIn;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
isUserLoggedIn = SnapLogin.isUserLoggedIn(this);
if (isUserLoggedIn)
binding.btnLogin.setText("Logout");
else
binding.btnLogin.setText("Logout");
binding.btnLogin.setOnClickListener(v -> {
SnapLogin.getAuthTokenManager(this).startTokenGrant();
binding.progress.setVisibility(View.VISIBLE);
});
SnapLogin.getLoginStateController(this).addOnLoginStateChangedListener(mLoginStateChangedListener);
SnapLogin.fetchUserData(this, query, null, new FetchUserDataCallback() {
#Override
public void onSuccess(#Nullable UserDataResponse userDataResponse) {
if (userDataResponse == null || userDataResponse.getData() == null) {
return;
}
MeData meData = userDataResponse.getData().getMe();
if (meData == null) {
return;
}
binding.txtName.setText(userDataResponse.getData().getMe().getDisplayName());
if (meData.getBitmojiData() != null) {
Glide.with(MainActivity.this)
.load(meData.getBitmojiData().getAvatar())
.into(binding.imgProfile);
}
}
#Override
public void onFailure(boolean isNetworkError, int statusCode) {
}
});
}
final LoginStateController.OnLoginStateChangedListener mLoginStateChangedListener =
new LoginStateController.OnLoginStateChangedListener() {
#Override
public void onLoginSucceeded() {
// Here you could update UI to show login success
binding.progress.setVisibility(View.VISIBLE);
Log.d(TAG, "onLoginSucceeded: ");
binding.btnLogin.setText("Logout");
}
#Override
public void onLoginFailed() {
// Here you could update UI to show login failure
binding.progress.setVisibility(View.VISIBLE);
Log.d(TAG, "onLoginFailed: ");
}
#Override
public void onLogout() {
// Here you could update UI to reflect logged out state
binding.progress.setVisibility(View.VISIBLE);
Log.d(TAG, "onLogout: ");
}
};
}
Manifests
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.iotait.snapchatandroid">
<uses-permission android:name="android.permission.INTERNET" />
<queries>
<package android:name="com.snapchat.android" />
</queries>
<application
android:name=".application.AppController"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.SnapchatAndroidDemo">
<meta-data
android:name="com.snapchat.kit.sdk.clientId"
android:value="**********************" />
<meta-data
android:name="com.snapchat.kit.sdk.redirectUrl"
android:value="*********************" />
<meta-data
android:name="com.snapchat.kit.sdk.scopes"
android:resource="#array/snap_connect_scopes" />
<activity android:name=".ui.sign.SigninActivity"
android:screenOrientation="nosensor"/>
<activity android:name=".ui.intro.IntroActivity"
android:screenOrientation="nosensor"/>
<activity android:name=".ui.login.LoginActivity"
android:screenOrientation="nosensor"/>
<activity
android:name=".ui.splash.SplashActivity"
android:screenOrientation="nosensor"
android:theme="#style/Theme.splash">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".ui.MainActivity"
android:screenOrientation="nosensor" />
<activity
android:name="com.snapchat.kit.sdk.SnapKitActivity"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="lmk"
android:path="/oauth2"
android:scheme="lmk" />
</intent-filter>
</activity>
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
</application>
</manifest>
Dependencies
implementation([
'com.snapchat.kit.sdk:login:1.1.4',
'com.snapchat.kit.sdk:core:1.1.4'
])
You need to add these line in the application tag
<meta-data android:name="com.snapchat.kit.sdk.clientId" android:value="1aab4ace-3f06-487d-bc85************"/>
<meta-data android:name="com.snapchat.kit.sdk.redirectUrl" android:value="https:********"/>
<meta-data android:name="com.snapchat.kit.sdk.scopes" android:resource="#array/snap_connect_scopes"/>
Use like this
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.iotait.snapchatandroid">
<uses-permission android:name="android.permission.INTERNET" />
<queries>
<package android:name="com.snapchat.android" />
</queries>
<application
android:name=".application.AppController"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:supportsRtl="true"
android:theme="#style/Theme.SnapchatAndroidDemo">
<meta-data android:name="com.snapchat.kit.sdk.clientId" android:value="1aab4ace-3f06-487d-bc85************"/>
<meta-data android:name="com.snapchat.kit.sdk.redirectUrl" android:value="https:********"/>
<meta-data android:name="com.snapchat.kit.sdk.scopes" android:resource="#array/snap_connect_scopes"/>
<activity android:name=".intro.IntroActivity"/>
<activity android:name=".login.LoginActivity"/>
<activity
android:name=".splash.SplashActivity"
android:theme="#style/Theme.splash">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity android:name=".MainActivity" />
<activity
android:name="com.snapchat.kit.sdk.SnapKitActivity"
android:launchMode="singleTask">
<intent-filter>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
<data android:scheme="lmk" android:host="lmk" android:path="/oauth2"/>
</intent-filter>
</activity>
<meta-data
android:name="preloaded_fonts"
android:resource="#array/preloaded_fonts" />
</application>
</manifest>
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 2 years ago.
Build version: 2.9
Build date: 1979-11-30 00:00:00
Current date: 2020-12-12 17:01:30
Device: Samsung SM-N970U
OS version: Android 10 (SDK 29)
Stack trace:
java.lang.RuntimeException: Unable to destroy activity {com.jmctstudios.vibe/com.jmctstudios.vibe.ActivitiesFragment.Splash_A}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.CountDownTimer.cancel()' on a null object reference
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:5456)
at android.app.ActivityThread.handleDestroyActivity(ActivityThread.java:5493)
at android.app.servertransaction.DestroyActivityItem.execute(DestroyActivityItem.java:44)
at android.app.servertransaction.TransactionExecutor.executeLifecycleState(TransactionExecutor.java:176)
at android.app.servertransaction.TransactionExecutor.execute(TransactionExecutor.java:97)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:2267)
at android.os.Handler.dispatchMessage(Handler.java:107)
at android.os.Looper.loop(Looper.java:237)
at android.app.ActivityThread.main(ActivityThread.java:8167)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:496)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:1100)
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.os.CountDownTimer.cancel()' on a null object reference
at com.jmctstudios.vibe.ActivitiesFragment.Splash_A.onDestroy(Splash_A.java:83)
at android.app.Activity.performDestroy(Activity.java:8225)
at android.app.Instrumentation.callActivityOnDestroy(Instrumentation.java:1342)
at android.app.ActivityThread.performDestroyActivity(ActivityThread.java:5441)
... 11 more
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
package="com.jmctstudios.vibe">
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-feature
android:name="android.hardware.camera2.full"
android:required="false" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission
android:name="android.permission.MANAGE_DOCUMENTS"
tools:ignore="ProtectedPermissions" />
<uses-permission android:name="android.permission.RECORD_VIDEO" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.FLASHLIGHT" />
<uses-permission android:name="android.permission.FOREGROUND_SERVICE" />
<uses-permission android:name="android.permission.READ_PHONE_NUMBERS" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<application
android:name=".SimpleClasses.VIBE"
android:allowBackup="false"
android:hardwareAccelerated="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:largeHeap="true"
android:networkSecurityConfig="#xml/network_security_config"
android:requestLegacyExternalStorage="true"
android:roundIcon="#mipmap/ic_launcher"
android:screenOrientation="portrait"
android:supportsRtl="false"
android:theme="#style/AppTheme"
tools:replace="allowBackup,supportsRtl">
<activity android:name=".ActivitiesFragment.Accounts.Forgot_Pass_A"
android:theme="#style/transparent_status"/>
<activity
android:name=".ActivitiesFragment.Video_Recording.Trim_video_A"
android:theme="#style/black_status" />
<activity
android:name=".ActivitiesFragment.Video_Recording.Video_Recoder_Duet_A"
android:theme="#style/black_status" />
<activity
android:name="cat.ereza.customactivityoncrash.activity.DefaultErrorActivity"
android:process=":error_activity"
android:theme="#style/error_activity_theme" />
<activity
android:name="com.theartofdev.edmodo.cropper.CropImageActivity"
android:screenOrientation="portrait"
android:theme="#style/Base.Theme.AppCompat"
tools:ignore="LockedOrientationActivity" />
<activity android:name=".ActivitiesFragment.SoundLists.VideoSound_A" />
<activity
android:name=".ActivitiesFragment.Video_Recording.DraftVideos_A"
android:screenOrientation="portrait"
android:theme="#style/white_status"
tools:ignore="LockedOrientationActivity" />
<activity
android:name=".ActivitiesFragment.Video_Recording.GallerySelectedVideo_A"
android:screenOrientation="portrait"
tools:ignore="LockedOrientationActivity" />
<activity
android:name=".ActivitiesFragment.Accounts.Login_A"
android:screenOrientation="portrait"
android:theme="#style/Transparent"
tools:ignore="LockedOrientationActivity" />
<activity
android:name=".ActivitiesFragment.Splash_A"
android:screenOrientation="portrait"
tools:ignore="LockedOrientationActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<activity
android:name=".Main_Menu.MainMenuActivity"
android:launchMode="singleTask"
android:screenOrientation="portrait"
android:theme="#style/transparent_status"
android:windowSoftInputMode="stateAlwaysHidden|adjustNothing"
tools:ignore="LockedOrientationActivity"/>
<activity
android:name=".ActivitiesFragment.WatchVideos_F"
android:parentActivityName=".Main_Menu.MainMenuActivity"
android:screenOrientation="portrait"
android:theme="#style/transparent_status"
android:windowSoftInputMode="stateAlwaysHidden|adjustNothing"
tools:ignore="LockedOrientationActivity">
<intent-filter android:autoVerify="true">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data
android:host="bringthings.com"
android:scheme="http" />
</intent-filter>
<meta-data
android:name="android.support.PARENT_ACTIVITY"
android:value="com.jmctstudios.vibe.Main_Menu.MainMenuActivity" />
</activity>
<activity
android:name="com.facebook.FacebookActivity"
android:configChanges="keyboard|keyboardHidden|screenLayout|screenSize|orientation"
android:label="#string/app_name" />
<activity
android:name="com.facebook.CustomTabActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="#string/fb_login_protocol_scheme" />
</intent-filter>
</activity>
<activity
android:name=".ActivitiesFragment.Video_Recording.Video_Recoder_A"
android:screenOrientation="portrait"
android:theme="#style/black_status"
tools:ignore="LockedOrientationActivity" />
<activity
android:name=".ActivitiesFragment.Video_Recording.Preview_Video_A"
android:screenOrientation="portrait"
android:theme="#style/black_status"
tools:ignore="LockedOrientationActivity" />
<activity
android:name=".ActivitiesFragment.Video_Recording.Post_Video_A"
android:screenOrientation="portrait"
android:windowSoftInputMode="adjustNothing"
tools:ignore="LockedOrientationActivity" />
<activity
android:name=".ActivitiesFragment.SoundLists.SoundList_Main_A"
android:screenOrientation="portrait"
tools:ignore="LockedOrientationActivity" />
<meta-data
android:name="com.google.android.gms.ads.APPLICATION_ID"
android:value="#string/ad_app_id"/>
<meta-data
android:name="com.facebook.sdk.ApplicationId"
android:value="#string/facebook_app_id" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_icon"
android:resource="#drawable/ic_tic" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_color"
android:resource="#color/redcolor" />
<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.fileprovider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
android:name="android.support.FILE_PROVIDER_PATHS"
android:resource="#xml/file_paths" />
</provider>
<service
android:name=".Services.Upload_Service"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="startservice" />
</intent-filter>
</service>
<service android:name=".Firebase_Notification.Notification_Receive">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<uses-library
android:name="org.apache.http.legacy"
android:required="false" />
</application>
</manifest>
package com.jmctstudios.vibe.ActivitiesFragment;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.os.CountDownTimer;
import androidx.appcompat.app.AppCompatActivity;
import android.provider.Settings;
import android.view.Window;
import android.view.WindowManager;
import com.jmctstudios.vibe.Main_Menu.MainMenuActivity;
import com.jmctstudios.vibe.R;
import com.jmctstudios.vibe.ApiClasses.ApiLinks;
import com.jmctstudios.vibe.ApiClasses.ApiRequest;
import com.jmctstudios.vibe.Interfaces.Callback;
import com.jmctstudios.vibe.SimpleClasses.Variables;
import org.json.JSONException;
import org.json.JSONObject;
public class Splash_A extends AppCompatActivity {
CountDownTimer countDownTimer;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.activity_splash);
Variables.sharedPreferences = getSharedPreferences(Variables.pref_name, MODE_PRIVATE);
if(Variables.sharedPreferences.getString(Variables.device_id,"0").equals("0")) {
Call_api_register_device();
}
else
Set_Timer();
}
public void Set_Timer(){
countDownTimer = new CountDownTimer(2500, 500) {
public void onTick(long millisUntilFinished) {
// this will call on every 500 ms
}
public void onFinish() {
Intent intent=new Intent(Splash_A.this, MainMenuActivity.class);
if(getIntent().getExtras()!=null) {
intent.putExtras(getIntent().getExtras());
setIntent(null);
}
startActivity(intent);
overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
finish();
}
}.start();
}
#Override
protected void onDestroy() {
countDownTimer.cancel();
super.onDestroy();
}
public void Call_api_register_device(){
String androidId = Settings.Secure.getString(getContentResolver(),
Settings.Secure.ANDROID_ID);
JSONObject param=new JSONObject();
try {
param.put("key",androidId);
} catch (JSONException e) {
e.printStackTrace();
}
ApiRequest.Call_Api(this, ApiLinks.registerDevice, param, new Callback() {
#Override
public void Responce(String resp) {
try {
JSONObject jsonObject=new JSONObject(resp);
String code=jsonObject.optString("code");
if(code.equals("200")){
Set_Timer();
JSONObject msg=jsonObject.optJSONObject("msg");
JSONObject Device=msg.optJSONObject("Device");
SharedPreferences.Editor editor2 = Variables.sharedPreferences.edit();
editor2.putString(Variables.device_id, Device.optString("id")).commit();
}else {
Call_api_show_register_device();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
public void Call_api_show_register_device(){
String androidId = Settings.Secure.getString(getContentResolver(),
Settings.Secure.ANDROID_ID);
JSONObject param=new JSONObject();
try {
param.put("key",androidId);
} catch (JSONException e) {
e.printStackTrace();
}
ApiRequest.Call_Api(this, ApiLinks.showDeviceDetail, param, new Callback() {
#Override
public void Responce(String resp) {
try {
JSONObject jsonObject=new JSONObject(resp);
String code=jsonObject.optString("code");
if(code.equals("200")){
Set_Timer();
JSONObject msg=jsonObject.optJSONObject("msg");
JSONObject Device=msg.optJSONObject("Device");
SharedPreferences.Editor editor2 = Variables.sharedPreferences.edit();
editor2.putString(Variables.device_id, Device.optString("id")).commit();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
});
}
}
Your object is null during onDestroy, maybe wrap it around a check like
#Override
protected void onDestroy() {
super.onDestroy();
if (countDownTimer!=null) {
countDownTimer.cancel();
}
}
This question already has answers here:
How to get application object into fragment class
(6 answers)
Closed 5 years ago.
I am trying to access the global variable declared in AndroidManifest.xml in UARTlogfragment.java but there is an error in the use of getApplication() i.e. "cannot resolve".
I am posting my Androidmanifest.xml and the UARTlogfragment.java here.
The AndroidManifest.xml is:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.BLUETOOTH" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.NFC" />
<uses-permission android:name="no.nordicsemi.android.LOG" />
<uses-feature
android:name="android.hardware.bluetooth_le"
android:required="true" />
<!-- To auto-complete the email text field in the login form with the user's emails -->
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.READ_PROFILE" />
<uses-permission android:name="android.permission.READ_CONTACTS" />
<application
android:name=".ToolboxApplication"
android:allowBackup="true"
android:fullBackupContent="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:roundIcon="#mipmap/ic_launcher_round"
android:theme="#style/AppTheme"
tools:ignore="GoogleAppIndexingWarning">
<meta-data
android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity
android:name=".SplashscreenActivity"
android:label="#string/app_name"
android:theme="#style/AppTheme.Fullscreen">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<meta-data
android:name="android.app.shortcuts"
android:resource="#xml/shortcuts" />
<intent-filter>
<action android:name="android.nfc.action.NDEF_DISCOVERED" />
<category android:name="android.intent.category.DEFAULT" />
<data android:mimeType="application/vnd.no.nordicsemi.type.app" />
<data android:mimeType="application/vnd.no.nordicsemi.type.address" />
</intent-filter>
</activity>
<!-- Template plugin activities -->
<!-- Remember to add your plug-in Activities to the Android Manifest file. -->
<!-- Plug-in activities -->
<activity
android:name=".FeaturesActivity"
android:label="#string/app_name"
android:launchMode="singleTask"
android:theme="#style/AppTheme.TranslucentStatusBar" />
<activity
android:name=".uart.UARTActivity"
android:icon="#drawable/ic_uart_feature"
android:label="#string/uart_feature_title"
android:launchMode="singleTask"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="no.nordicsemi.android.nrftoolbox.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".proximity.ProximityService"
android:label="#string/proximity_feature_title" />
<service
android:name=".dfu.DfuService"
android:exported="true"
android:label="#string/dfu_service_title">
<intent-filter>
<action android:name="no.nordicsemi.android.action.DFU_UPLOAD" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</service>
<activity
android:name=".dfu.DfuInitiatorActivity"
android:label="#string/dfu_service_title"
android:noHistory="true"
android:theme="#style/AppTheme.Translucent">
<intent-filter>
<action android:name="no.nordicsemi.android.action.DFU_UPLOAD" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<service
android:name=".cgms.CGMService"
android:label="#string/cgms_feature_title" />
<service
android:name=".rsc.RSCService"
android:label="#string/rsc_feature_title" />
<service
android:name=".csc.CSCService"
android:label="#string/csc_feature_title" />
<service
android:name=".hts.HTSService"
android:label="#string/hts_feature_title" />
<service
android:name=".uart.UARTService"
android:label="#string/uart_feature_title" />
<service android:name=".wearable.MainWearableListenerService">
<intent-filter>
<action android:name="com.google.android.gms.wearable.DATA_CHANGED" />
<action android:name="com.google.android.gms.wearable.MESSAGE_RECEIVED" />
<data
android:host="*"
android:pathPrefix="/nrftoolbox"
android:scheme="wear" />
</intent-filter>
</service>
<provider
android:name=".uart.UARTLocalLogContentProvider"
android:authorities="no.nordicsemi.android.nrftoolbox.uart.log"
android:exported="true" />
<activity
android:name=".Register_Page"
android:label="#string/title_activity_register__page" />
<activity android:name=".View_Profile" />
<activity android:name=".Profile" />
<activity android:name=".Wallet_Page" />
<activity android:name=".confirm_booking" />
<activity android:name=".LoginActivity" />
<activity android:name=".Add_Amount" />
<activity android:name=".last_step_book"></activity>
</application>
The UARTlogfragment.java(where I am trying to access the global variable) is :
public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) {
final View view = inflater.inflate(R.layout.fragment_feature_uart_log, container, false);
mydb = new no.nordicsemi.android.nrftoolbox.myDbAdapter(getContext());
String s = ((ToolboxApplication) this.getApplication()).getSomeVariable();
Cursor rs = mydb.getData(1);
rs.moveToFirst();
String nam = rs.getString(rs.getColumnIndex(no.nordicsemi.android.nrftoolbox.myDbAdapter.CONTACTS_COLUMN_NAME));
String phon = rs.getString(rs.getColumnIndex(no.nordicsemi.android.nrftoolbox.myDbAdapter.CONTACTS_COLUMN_PHONE));
String emai = rs.getString(rs.getColumnIndex(no.nordicsemi.android.nrftoolbox.myDbAdapter.CONTACTS_COLUMN_EMAIL));
String cit = rs.getString(rs.getColumnIndex(no.nordicsemi.android.nrftoolbox.myDbAdapter.CONTACTS_COLUMN_CITY));
String gend = rs.getString(rs.getColumnIndex(no.nordicsemi.android.nrftoolbox.myDbAdapter.CONTACTS_COLUMN_GENDER));
String pas = rs.getString(rs.getColumnIndex(no.nordicsemi.android.nrftoolbox.myDbAdapter.CONTACTS_COLUMN_PASS));
String dobb = rs.getString(rs.getColumnIndex(no.nordicsemi.android.nrftoolbox.myDbAdapter.CONTACTS_COLUMN_DOB));
if (!rs.isClosed()) {
rs.close();
}
final EditText field = mField = view.findViewById(R.id.field);
mField.setText(nam+" "+emai+" "+phon+" "+gend+" "+cit);
field.setOnEditorActionListener((v, actionId, event) -> {
if (actionId == EditorInfo.IME_ACTION_SEND) {
onSendClicked();
return true;
}
return false;
});
final Button sendButton = mSendButton = view.findViewById(R.id.action_send);
sendButton.setOnClickListener(v -> onSendClicked());
return view;
}
What is the error ?? And why cannot it resolve getApplication()??
Change
String s = ((ToolboxApplication) this.getApplication()).getSomeVariable();
to
String s = ((ToolboxApplication) getActivity().getApplication()).getSomeVariable();
As you are trying yo use application context from fragment you can not use getApplication() because isn't method of Fragment class
So you first have to use the getActivity() which will return a Fragment Activity to which the fragment is currently associated with.
to sumup in your code,
instead of this.getApplication() you have to use getActivity.getApplication()
I have a Parse notification in my app. If I open my app. then it will receive the notification.
If I restart my phone. No notification will be received, until I open my app.
My question is:
How Can I initiate / run, my ParsePushBroadcastReceiver whenever the phone has been restarted. or how can I make this Receiver to be always running even if user close the app / kill the app ?
I though by adding android.intent.action.BOOT_COMPLETED would work. but it don't
Here is my manifest:
<activity
android:name=".SplashActivity"
android:label="#string/app_name"
android:screenOrientation="portrait" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.parse.PushService" />
<receiver android:name="com.parse.ParseBroadcastReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.RECEIVE_BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
</intent-filter>
</receiver>
<receiver
android:name="com.my.app.core.MyParseReceiver"
android:exported="false" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.USER_PRESENT" />
<action android:name="com.parse.push.intent.RECEIVE" />
<action android:name="com.parse.push.intent.DELETE" />
<action android:name="com.parse.push.intent.OPEN" />
</intent-filter>
</receiver>
<receiver
android:name="com.parse.GcmBroadcastReceiver"
android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
<action android:name="android.intent.action.RECEIVE_BOOT_COMPLETED" />
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<action android:name="com.google.android.c2dm.intent.REGISTRATION" />
<category android:name="com.my.app" />
</intent-filter>
</receiver>
<meta-data
android:name="com.parse.push.notification_icon"
android:resource="#drawable/ic_launcher" />
My Class
....
public class MyParseReceiver extends ParsePushBroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
super.onReceive(context, intent);
Log.i(TAG, "onReceive Called");
if (intent == null) {
Log.e(TAG, "Receiver intent null");
}
else {
// Parse push message and handle accordingly
Log.d(TAG, "Receiver intent data => " + intent.toString());
}
}//end onReceive
#Override
public void onPushOpen(Context context, Intent intent) {
...
I wouldn't recommend it but you could make an onBacKeyPressed() method and just make it look like the app has been killed.