phonegap parsing incoming data to application - android

Using PhoneGap I am opening an application on Android from a link in an email using an intent specified in the Manifest file. This is working fine.
What I need to do now is parse in some data to the application that is opened, the data I am retrieving from the URL query params, this is working fine I am reading the URL that is clicked in the email within the onCreate(Bundle savedInstanceState) method thus:
super.loadUrl("file:///android_asset/www/index.html");
System.out.println("- start intent -");
final Intent intent = getIntent();
if(intent != null && intent.getDataString() != null){
System.out.println("- data string:"+intent.getDataString());
String url = intent.getDataString();
this.sendJavascript("testMethod('"+url+"');");
System.out.println("- finished method call");
}
If you look at the code above the system outs are all output as expected and the data string is exactly as expected but the testMethod(url), which is in my index.js file, never gets called.
Even when I do a simple method thus
function testMethod(url){
alert("************************ alert");
console.log("******************** log")
console.warn("******************** warn")
console.info("******************** info")
console.error("******************** error")
}
None of the console calls or the alert are made.
So to me it seems that the sendJavascript method is not being executed or called.
Am I missing something?

In the end I could not get this to function at all. What I am trying to acheive is pass a value in when the application is loaded from a URL. I acheived this by changing the URL if there is an intent and adding query parameters to the loadUrl. Then in the index.js I have checked for window.location.search and then called an extra function if a specific query param is found like this.
if(intent != null && intent.getDataString() != null){
super.loadUrl("file:///android_asset/www/index.html?register=true");
}
else{
super.loadUrl("file:///android_asset/www/index.html");
}
Then in the Javascript
if(window.location.search === "?register=true"){
handleOpenURL("my/url");
}

Related

unable to retrieve link params when opening branch link inside app

Our android app is a chat app. Users can paste a branch link in a chat message. When another user taps on it, we want to retrieve the link parameters to take the user to another screen.
Unfortunately, we are unable to retrieve the link parameters when we tap on such link inside the app (note that we are not using a webview), we are getting the error "Warning. Session initialisation already happened.
To force a new session, set intent extra, branch_force_new_session, to true in the onInitFinished(#Nullable JSONObject referringParams, #Nullable BranchError error) method.
How can we solve this? It's not obvious to me how I could pass a new intent param in that use case.
Notes:
Our launcher activity is singleTask
We are on branch.io sdk 4.3.2
onNewIntent() does not seem to be called (in the code below), maybe that is the root cause for our issue.
sample code:
private Branch.BranchReferralInitListener branchReferralInitListener =
new Branch.BranchReferralInitListener() {
#Override
public void onInitFinished(#Nullable JSONObject referringParams, #Nullable BranchError error) {
...
}
#Override
protected void onStart() {
super.onStart();
Branch.getInstance().initSession(branchReferralInitListener, getIntent() != null ?
getIntent().getData() : null, this);
}
#Override
public void onNewIntent(Intent intent) {
super.onNewIntent(intent);
this.setIntent(intent);
// activity will skip onStart, handle this case with reInitSession
Branch.getInstance().reInitSession(this, branchReferralInitListener);
}
This is a known issue with the Android SDK v4.3.2 and we are working on a resolution.
Would suggest you to try the following in the meanwhile:
When the user tries to open an app that is running in the background, we get an error for set branch_force_new_session to true.
Branch SDK gets initialised on onStart for the Launcher Activity and when the app comes foreground from the background, its on onResume.
In this scenario, we could need to re-initialise the SDK here.
Would request you to implement the below snippet as per Branch docs (https://docs.branch.io/apps/android/#initialize-branch)
// activity will skip onStart, handle this case with reInitSession
Branch.getInstance().reInitSession(this, branchReferralInitListener);
Alternatively, would suggest you to install Branch SDK v4.3.1.
Initialized, you branch IO in application class so that it will initialize once and will not be require again
// Branch logging for debugging
Branch.enableLogging();
//Disable Device ID #2966
Branch.disableDeviceIDFetch(true);
// Initialize the Branch object
BranchIOManager.setupBranchInstance(this);
// It tells the Branch initialization to wait for the Google Play Referrer before proceeding.
Branch.enablePlayStoreReferrer(1000L);
Then inside initSession() branch method use. Pass them as JSON Object to method where you can retrieve the value based on key names.
if (branch != null && uri != null) {
branch.initSession(new Branch.BranchUniversalReferralInitListener() {
#Override
public void onInitFinished(BranchUniversalObject branchUniversalObject, LinkProperties linkProperties, BranchError error) {
// Log.d("onInitFinished", error + "");
if (error == null && branchUniversalObject != null) {
JSONObject jBranch = branchUniversalObject.getContentMetadata().convertToJson();
if (!branchJSONString.equals(jBranch.toString())) {
//This check is applied as if we launch another mLandingScreenPhoneActivity from Branch link then app will become in loop
branchJSONString = jBranch.toString();
loadScreenFromBranchIODynamicLink(jBranch, 0);
}
}
if (error != null) {
// //Toast.makeText(LandingScreenPhoneActivity.this, error + "", Toast.LENGTH_SHORT).show();
}
}
}, uri, this);
}
Here you can get screen values
String screenName = referringParams.optString("screen_key");
//Screen in app where needs to navigate
int screenIndex = referringParams.optInt("screen_index");

How to get Updated Context in Unity3D Android when app is open from Background?

I am trying to get URL data when Unity3D android app is open from URL scheme. To get data which is come in URL I have written below in Unity3D :
using (AndroidJavaClass unityPlayerClass = new AndroidJavaClass("com.unity3d.player.UnityPlayer")) {
AndroidJavaObject context = unityPlayerClass.GetStatic<AndroidJavaObject>("currentActivity");
String dataString = context.Call<AndroidJavaObject>("getIntent").Call<String>("getDataString");
Debug.LogError ("URL Data " +dataString );
I am able to get URL data but it always remain same if I am opening app from URL scheme or without URL scheme. So I guess the context is not updating when I am opening the app from background state.
Please provide me some suggestion to come out from this problem.
Add this code to Main Activity class
#Override
protected void onNewIntent(Intent intent) {
super.onNewIntent(intent);
setIntent(intent);
}

Accepting incoming call twilio(Obtain the name to client who made the call)

I am developing a simple voice chat android application using twilio. I am being able to make outgoing calls and also accept incoming calls using client names. This is my twilio voice url php script :
<?php
header('Content-type: text/xml');
$client= $_REQUEST["userName"];
?>
<Response>
<Dial callerId="<?php echo $client ?>">
<Client><?php echo $number;?></Client>
</Dial>
</Response>
What I need to do is I need to display the name of the calling client to the user receiving the incoming call but I am unable to figure out how to obtain the name of calling client. I even tried doing this,
#Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
Device device = intent.getParcelableExtra(Device.EXTRA_DEVICE);
Connection incoming = intent
.getParcelableExtra(Device.EXTRA_CONNECTION);
incoming.setConnectionListener(this);
String clientName = Connection.getParameters().get(incoming.IncomingParameterFromKey);
Log.i(TAG, "Call from : " + clientName);
}
but I got following logcat output:
12-13 16:17:25.531: E/Voice chat sample app log(16157): Call from : 873797
I am getting a number 873797 instead of client name.
There might be some way to obtain the name of the client. I also went through twilio documentation with no success. Any help would be greatly appreciated.
All you need to do is just go to this link
https://www.twilio.com/user/account/phone-numbers/incoming
1. Click on your twilio number.
2. Enter into the Configure Tab
3. Go into Voice . Check the Url in Configure with:
4. Over there you have a drop down of Caller Name Lookup that is set to disabled. Enable it .
Hope this works for you ! :)
I have solved the problem with this,
Hope it helps
#Override
public void onResume() {
super.onResume();
Intent intent = getIntent();
if (intent != null) {
/*
* Determine if the receiving Intent has an extra for the incoming connection. If so,
* remove it from the Intent to prevent handling it again next time the Activity is resumed
*/
Device device = intent.getParcelableExtra(Device.EXTRA_DEVICE);
Connection incomingConnection = intent.getParcelableExtra(Device.EXTRA_CONNECTION);
if (incomingConnection == null && device == null) {
return;
}
intent.removeExtra(Device.EXTRA_DEVICE);
intent.removeExtra(Device.EXTRA_CONNECTION);
pendingConnection = incomingConnection;
pendingConnection.setConnectionListener(this);
String incomingRecipientCallNumber = pendingConnection.getParameters().get(incomingConnection.IncomingParameterFromKey);
showRecipientNumber.setText(incomingRecipientCallNumber);
showIncomingDialog();
}
}

Android - some code executes after the phone went to a different Activity

I have a strange scenario here.
I have this code:
// For checking if the person is logged in.
first_time_check();
setContentView(R.layout.main);
// ...next lines of code
and the first_time_check() function checks if the user is logged in for the first time. If their user_id is not in the SharedPreferences, I redirect them to log in:
public void first_time_check()
{
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences( ProblemioActivity.this);
String user_id = prefs.getString( "user_id", null ); // First arg is name and second is if not found.
String first_time_cookie = prefs.getString( "first_time_cookie" , null );
// About setting cookie. Check for first time cookie
if ( first_time_cookie == null )
{
// This user is a first-time visitor, 1) Create a cookie for them
first_time_cookie = "1";
// 2) Set it in the application session.
prefs.edit().putString("first_time_cookie", first_time_cookie ).commit();
// Make a remote call to the database to increment downloads number
// AND send me an email that it was a new user.
}
else
{
// If not first time, get their id.
// If user_id is empty, make them an account.
// If id not empty, call the update login date and be done.
if ( user_id == null )
{
// User id is null so they must have logged out.
Intent myIntent = new Intent(ProblemioActivity.this, LoginActivity.class);
ProblemioActivity.this.startActivity(myIntent);
}
else
{
// Make a remote call to the database to increment downloads number
}
}
return;
}
So after the code executes the
Intent myIntent = new Intent(ProblemioActivity.this, LoginActivity.class);
ProblemioActivity.this.startActivity(myIntent);
it still executes below the original code that calls this functions.
Any idea how that can happen?
Thanks!!
This is excerpted from the Dev Guide
Shutting Down an Activity
You can shut down an activity by calling its finish() method.
You can also shut down a separate activity that you previously
started by calling finishActivity().
Note: In most cases, you should not explicitly finish an activity
using these methods. As discussed in the following section about the
activity lifecycle, the Android system manages the life of an
activity for you, so you do not need to finish your own activities.
Calling these methods could adversely affect the expected user
experience and should only be used when you absolutely do not want
the user to return to this instance of the activity.
Calling finish() on the activity seems appropriate here as you do not want the user to return to this activity.

Android Jtwitter, authentication issues

Hello I am having difficulty using the JTwitter functions to authenticate with my twitter application. I always get a "TwitterException"
Here is my method
OAuthSignpostClient oauthClient = new OAuthSignpostClient(consumerKey,
privateKey, "oob");
a) I don't know what the "oob" value SHOULD be, it is the "callbackURL" and in my application on twitter it says "callBack URL: none" so I have tried putting "none", "None", and null where "oob" with no differing results.
then the rest is boilerplate
Intent i = new Intent(Intent.ACTION_VIEW,
Uri.parse(oauthClient.authorizeUrl().toString()));
startActivity(i);
// get the pin
String v = oauthClient.askUser("Please enter the verification PIN from Twitter");
oauthClient.setAuthorizationCode(v);
// Store the authorisation token details for future use
String[] accessToken = oauthClient.getAccessToken();
// Next time we can use new OAuthSignpostClient(OAUTH_KEY, OAUTH_SECRET,
// accessToken[0], accessToken[1]) to avoid authenticating again.
EditText twitterText = (EditText)findViewById(R.id.twitterText);
twitterText.getText();
// Make a Twitter object
Twitter twitter = new Twitter(null, oauthClient);
// Print Daniel Winterstein's status
//System.out.println(twitter.getStatus("winterstein"));
// Set my status
twitter.setStatus(twitterText.getText());
at this point, I'm simply not sure on how to make this work. Wish I could be more verbose about it, but it has something to do with the authentication. Online things I've seen haven't been helpful
Try this as your callback url:
OAuthSignpostClient oauthClient =
new OAuthSignpostClient(consumerKey, privateKey, "callback://twitter");
Remember! After:
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(authUrl)));
Do the following
override onResume() to get the verification code
protected void onResume() {
super.onResume();
if (this.getIntent()!=null && this.getIntent().getData()!=null){
Uri uri = this.getIntent().getData();
if (uri != null && uri.toString().startsWith("callback://twitter")) {
//Do whatever you want
//usually use uri.getQueryParameter(someString);
//test what could be someString using Log.v("",uri.toString());
//you want the Authorization code which is a couple of numbers
//so you could use oauthClient.setAuthorizationCode(v);
//and finally initialise Twitter
}
}
}
You can use uri.getQueryParameterNames() to get the parameter String names.
#BobVork
I'd just like to add that you'll need to have a callback URL set in the Settings tab for your Twitter app (on twitter.com).
It doesn't even matter what you put in the field, but if it's empty, callback urls will not work.
I'm not sure that's the problem, but it seems like you never set the user name for the twitter object.
Well, I don't know how it is with the Jtwitter API and I don't know enough Java at this point to really understand the inner workings of this code, but have you tried, instead of NULL or None, to try ? instead. That is the callback used with the restful API when making calls from Javascript. Try it out.

Categories

Resources