Shaik MD Ashiq Shaik MD Ashiq - 2 months ago 16
Android Question

Call activity from Application

I am trying to use Digits from Twitter.
The AuthCallBack is not fired when used from activity and the recent document saying to use the AuthCallBack from the Application class.

Now I have the AuthCallBack working correctly and onSuccess I need to call a method from my MainActivity. How do I achieve it from the Application class. Kindly help. I have given the code below.

public class MyApplication extends Application {

private AuthCallback authCallback;

@Override
public void onCreate() {
super.onCreate();

authCallback = new AuthCallback() {
@Override
public void success(DigitsSession session, String phoneNumber) {

//call myFunction() from MainActivity here

}

@Override
public void failure(DigitsException exception) {

}
};
}

public AuthCallback getAuthCallback(){
return authCallback;
}
}

Answer

You can use BroadcastManager to archive the same. Below is sample code you can use

From Application:

    @Override
    public void success(DigitsSession session, String phoneNumber) {
    Intent intent = new Intent(Constants.FILTER_LOGIN_SUCCESS);
    intent.putExtra(Constants.EXTRA_PHONE_NUMBER, phoneNumber);
    LocalBroadcastManager.getInstance(mInstance).sendBroadcast(intent);
}

Activity Class :

@Override
    protected void onResume() {
        super.onResume();
        LocalBroadcastManager.getInstance(SignUpActivity.this).registerReceiver(broadcastReceiver,
                new IntentFilter(Constants.FILTER_LOGIN_SUCCESS));
    }

@Override
protected void onDestroy() {
    super.onDestroy();
    LocalBroadcastManager.getInstance(SignUpActivity.this).unregisterReceiver(broadcastReceiver);
}

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String phoneNumber = intent.getStringExtra(Constants.EXTRA_PHONE_NUMBER);
            navigateToAnotherActivty();
        }
    };