Uses native code in cordova application - android

I have a following code in native android
List<PackageInfo> PackList = getPackageManager().getInstalledPackages(0);
for (int i=0; i < PackList.size(); i++)
{
PackageInfo PackInfo = PackList.get(i);
if ( ( (PackInfo.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) != true)
{
String AppName = PackInfo.applicationInfo.loadLabel(getPackageManager()).toString();
Log.e("App" + Integer.toString(i), AppName);
}
}
for getting information about installed application in mobile. I want to use in cordova/phonegap application.
How I use that?
What steps do I need?
Or is there anyway that same code use in different platforms
(android,windows)?
I also checked this link but didn't understand
Thanks In Advance

To use native code in a phonegap app you have to create a phonegap plugin. This is actually pretty simple:
1) Create you phonegap plugin class, in this case the plugin only responds to the action "toast" to create a native Android toast:
public class ExamplePlugin extends CordovaPlugin {
#Override
public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
if("toast".equals(action)) {
// The first String in the arguments array is the text for the toast
String text = args.getString(0);
Toast toast = Toast.makeText(this.cordova.getActivity(), text, Toast.LENGTH_SHORT);
toast.show();
// With PluginResult you can send results back to the js layer.
PluginResult result = new PluginResult(PluginResult.Status.OK, "--toast displayed.");
result.setKeepCallback(true);
callbackContext.sendPluginResult(result);
}
// Return true if everything worked as it should. If an error occurs return false.
// Depending on this return value either the success or error callback is invoked.
return true;
}
#Override
public void initialize(CordovaInterface cordova, CordovaWebView webView) {
super.initialize(cordova, webView);
// Here you can perform some initialisations for your plugin.
}
}
Then in the config.xml of your phonegap app you add this line:
<plugin name="ExamplePlugin" value="com.phonegap.example.ExamplePlugin" />
Name being the name by which you can call the plugin from javascript and value being the complete class name of your plugin.
Now you can call the plugin from javascript:
cordova.exec(successCallback, errorCallback, "ExamplePlugin", "toast", ["Hello Cordova!!1"]);
You supply two callbacks, the name of the plugin you want to call, the action you want to execute and an array of arguments, in our case the plugin is named "ExamplePlugin" the action is "toast" and we only have on string argument as text for our toast.
Of course this just works for Android. If you want the same functionality for different platforms e.g. iOS, Windows Phone etc. You are gonna have to create a plugin for each of them too.

You will need to create a PhoneGap/Cordova plugin.
In the return data (the result) in the plugin you need to return the String.
For recent an example, check out this blog post. It works with AndroidPreferences feature and it uses both sending data and retrieving data.

Related

Create template page for printing - ionic 2

Ionic printer plugin use Printer.print([html string], [printer options]) function to get print out using mobile app.
I need to create html template and update some values dynamically and use template as input for the print function.
Can anyone have any idea how to do this?
I am using ionic 2 and android platform.
It depends on what exactly want to print.
I would probably just create an HTML template inside your code and then replace the values before printing.
Example:
class Page {
template: string = `<h1>{title}</h1>
<p>This is a paragraph</p>
<p>{content}</p>`;
getHTML(title, content) {
let str = template;
str = str.replace('{title}', title);
str = str.replace('{content}', content);
return str;
}
printPage(title, content) {
let options = {};
this.p.print(getHTML(title, content), options).then(onSuccess, onError);
}
}

Appium Android Automation

This may be simple question for the experts. I am a beginner in appium and all these days i have been trying to make my test script for printing a page title in my script. Here is the part of My code below: i am unable to print the page title and then do a validation. Can someone help?
driver = new AndroidDriver<WebElement>(new URL("http://127.0.0.1:4723/wd/hub"), capabilities);
System.out.println(driver.getRemoteAddress());
}
public void ApkPushValidation() throws Exception {
Assert.assertEquals("Verify your phone number", driver.findElementByName("Verify your phone number").getText());
driver.wait(5000);
String i = driver.getTitle();
System.out.println(i);
if (driver.getTitle().equals("Verify your phone number") ) {
System.out.println("app installation is passed");
} else {
System.out.println("App installation is failed");
}
//System.out.println(i);---> my expectation is that this will print out Verify your Phone number. However this is not printing the page title.
Use UIAutomatorViewer to find out the xpath of the title.
use the following website for example on how to use the x-path. "http://software-testing-tutorials-automation.blogspot.ca/2015/10/ui-automator-viewer-get-android-app.html"
I think that driver.getTitle() is a method for Web page interaction, not meant for Native apps. I would suggest to use XPath or some other element locator to find the title.
Instead if getTitle(); try to use xPath, name or Id available for the title. Use Appium inspector or UI automator to locate that element and change it like this:
String i = driver.findElementById("Your ID").getText();
if (i.equals("Verify your phone number") ) {
System.out.println("app installation is passed");
} else {
System.out.println("App installation is failed");
}
What you probably what to perform should be done using the following piece of code :
WebElement title = driver.findElementByName("Verify your phone number"); // defining the element only once for multiple use
// different locator strategies could be used for locating the element above
Assert.assertEquals("Verify your phone number", title.getText());
driver.wait(5000);
String i = title.getText();
System.out.println(i);
if (i.equals("Verify your phone number") ) {
System.out.println("app installation is passed");
} else {
System.out.println("App installation is failed");
}
More on driver.getTitle() : It has been inherited from RemoteWebDriver and possibly should return the title of a webpage/webview instead of an native application view which seems to be your case.
Note: would add more to this about getTitle() as I get to know.

google adwords in phonegap

I have added plugin of google adwords in my PhoneGap application. what should i do to see that plugin is working as i am new to the PhoneGap .how and where will i see the changes in my application after adding that plugin to my application.. can i see any logo of adwords or anything .. please help i tried this
this is d code in plugin
public class CordovaGoogleAdWords extends CordovaPlugin {
#Override
public boolean execute(String action, JSONArray inputs, CallbackContext callbackContext) throws JSONException {
//PluginResult result = null;
//callbackContext.sendPluginResult(result);
if(action.equals("track")) {
this.track(inputs, callbackContext);
return true;
}
return false;
}
private void track(JSONArray inputs, CallbackContext callbackContext) {
try {
AdWordsConversionReporter.reportWithConversionId(
this.cordova.getActivity().getApplicationContext(),
inputs.getJSONObject(0).getString("conversionId"),
inputs.getJSONObject(0).getString("label"),
inputs.getJSONObject(0).getString("value"), // The value of your conversion; can be modified to a transaction-specific value.
Boolean.parseBoolean(inputs.getJSONObject(0).getString("repeatable"))
);
callbackContext.success();
} catch (JSONException e) {
Log.d("Cordova Plugin Error", e.getMessage());
e.printStackTrace();
callbackContext.error("Unable to send tracking data");
}
}
}
For mobile ads use AdMob. You can use an existing plugin for phonegap/cordova: https://github.com/appfeel/admob-google-cordova:
For a cordova / phonegap CLI project, use one of this command line instructions:
cordova plugin add com.admob.google
phonegap local plugin add com.admob.google
If you use Phonegap build, place the following tag in your config.xml file:
<gap:plugin name="com.admob.google" source="plugins.cordova.io" />
Then in your javascript code:
function onDeviceReady() {
document.removeEventListener('deviceready', onDeviceReady, false);
// Set AdMobAds options:
admob.setOptions({
publisherId: "ca-app-pub-XXXXXXXXXXXXXXXX/BBBBBBBBBB", // Required
interstitialAdId: "ca-app-pub-XXXXXXXXXXXXXXXX/IIIIIIIIII", // Optional
tappxIdiOs: "/XXXXXXXXX/Pub-XXXX-iOS-IIII", // Optional
tappxIdAndroid: "/XXXXXXXXX/Pub-XXXX-Android-AAAA", // Optional
tappxShare: 0.5 // Optional
});
// Start showing banners (atomatic when autoShowBanner is set to true)
admob.createBannerView();
// Request interstitial (will present automatically when autoShowInterstitial is set to true)
admob.requestInterstitial();
}
document.addEventListener("deviceready", onDeviceReady, false);

What does Device Id mean Azure Push Notifications in Xamarin Android? How to get it?

We are using Azure Mobile Services to Push notifications to a Xamarin Android and a Xamarin iOS and a Windows Universal App. The Windows Universal App has plenty of documentation around what we need, although we haven’t had a chance to implement it yet. However, both Xamarin Android and iOS are missing all documentation around Push Notifications. If you go to http://azure.microsoft.com/en-us/documentation/services/mobile-services/ and select Xamarin Android or Xamarin iOS and .NET Backend there are zero links for documentation around these APIs. After digging around a ton yesterday I found this: http://azure.microsoft.com/en-us/documentation/articles/mobile-services-dotnet-backend-xamarin-android-get-started-push/ and http://azure.microsoft.com/en-us/documentation/articles/mobile-services-dotnet-backend-xamarin-ios-get-started-push/ both which were last updated in September of last year. The documentation was promised to be updated over 5 months ago.
When I use the Xamarin Component from Microsoft for Azure Mobile Services: http://components.xamarin.com/view/azure-mobile-services/ I am able to get the MobileServiceClient up and running, but not the Push notifications.
The API:
Push pushManager = MobileService.GetPush();
string deviceId = "what is this???";
//Option 1:
pushManager.RegisterNativeAsync(deviceId);
//Option 2:
GcmRegistration googleNotificationRegistration = new GcmRegistration(deviceId);
pushManager.RegisterAsync(googleNotificationRegistration);
Documentation I’m using:
Push.RegisterAsync:
https://msdn.microsoft.com/en-us/library/microsoft.windowsazure.mobileservices.push.registerasync.aspx
GcmRegistration: I can’t find any documentation for this class
Registration (Base class for GcmRegistration):
https://msdn.microsoft.com/en-us/library/microsoft.windowsazure.mobileservices.registration.aspx
Note: the parameter for Registration is not named deviceId it is named channelUri
Push.RegisterNativeAsync:
https://msdn.microsoft.com/en-us/library/dn643553.aspx
Note: the parameter of RegisterNativeAsync is not named deviceId it is named channelUri
My question is simple:
What is deviceId supposed to be? And how do I get it?
All the documentation above is for Winodws Universal Apps not for Xamarin Apps on Mono.
In the writing up of this question I have found articles about "Get Started with Notification Hubs":
Xamarin iOS - http://azure.microsoft.com/en-us/documentation/articles/partner-xamarin-notification-hubs-ios-get-started/
Xamarin Android - http://azure.microsoft.com/en-us/documentation/articles/partner-xamarin-notification-hubs-android-get-started/
Are these the example I should be using? They look old and the Android one mentions nothing about Azure Mobile Services. Should I not even be using the Azure Mobile Services Xamarin Component for Android?
tl;dr
deviceId should be just the GCMRegistrationId.
I looked into the source code of the implementations of the component DLLs and also Android SDKs.
Firstly, let's take a look to your option 1 and option 2 behind the scene. Basically both eventually do the same job of creating a GcmRegistration and passing it the internal RegistrationManager.
public Task RegisterAsync (Registration registration)
{
if (registration == null) {
throw new ArgumentNullException ("registration");
}
if (string.IsNullOrWhiteSpace (registration.PushHandle)) {
throw new ArgumentNullException ("registration.deviceId");
}
return this.RegistrationManager.RegisterAsync (registration);
}
public Task RegisterNativeAsync (string deviceId, IEnumerable<string> tags)
{
if (string.IsNullOrWhiteSpace (deviceId)) {
throw new ArgumentNullException ("deviceId");
}
GcmRegistration registration = new GcmRegistration (deviceId, tags);
return this.RegistrationManager.RegisterAsync (registration);
}
Then, one of the API calls that I can find involving the Registration.PushHandle (which is the deviceId you passed) is as below
public async Task<IEnumerable<Registration>> ListRegistrationsAsync (string deviceId)
{
MobileServiceHttpResponse mobileServiceHttpResponse = await this.client.HttpClient.RequestAsync (HttpMethod.Get, string.Format ("/push/registrations?deviceId={0}&platform={1}", new object[] {
Uri.EscapeUriString (deviceId),
Uri.EscapeUriString (Platform.Instance.PushUtility.GetPlatform ())
}), this.client.CurrentUser, null, true, null, MobileServiceFeatures.None);
return JsonConvert.DeserializeObject<IEnumerable<Registration>> (mobileServiceHttpResponse.Content, new JsonConverter[] {
new RegistrationConverter ()
});
}
I have then switched to Android Mobile Services SDK to look for similar code to find some hints. Sadly, it is found called pnsHandle in android but still no hints what it is.
/**
* Registers the client for native notifications with the specified tags
* #param pnsHandle PNS specific identifier
* #param tags Tags to use in the registration
* #return The created registration
* #throws Exception
*/
public Registration register(String pnsHandle, String... tags) throws Exception {
if (isNullOrWhiteSpace(pnsHandle)) {
throw new IllegalArgumentException("pnsHandle");
}
Registration registration = PnsSpecificRegistrationFactory.getInstance().createNativeRegistration(mNotificationHubPath);
registration.setPNSHandle(pnsHandle);
registration.setName(Registration.DEFAULT_REGISTRATION_NAME);
registration.addTags(tags);
return registerInternal(registration);
}
Finally, I guess the below example code from http://azure.microsoft.com/en-us/documentation/articles/mobile-services-dotnet-backend-android-get-started-push/#update-app should be calling the same API which now explain everything, i.e. deviceId is just the GCMRegistrationId.
#Override
public void onRegistered(Context context, final String gcmRegistrationId) {
super.onRegistered(context, gcmRegistrationId);
new AsyncTask<Void, Void, Void>() {
protected Void doInBackground(Void... params) {
try {
ToDoActivity.mClient.getPush().register(gcmRegistrationId, null);
return null;
}
catch(Exception e) {
// handle error
}
return null;
}
}.execute();
}

AxSU3D Android Facebook Plugin - "The parameter app_id is required"

I'm using AxSU3D's Android plugin in a Unity project. When I try to use the Facebook Login method, I get an error that says "The parameter app_id is required"
I have posted my code below. I have REPLACED the string "fbAppID" with the actual ID. This is just the sample script that came with the plugin that I am trying to use.
Any help will be appreciated
using UnityEngine;
using System.Collections;
using AxSAndroidPlugin.Core;
using AxSAndroidPlugin.Social.Facebook;
public class FacebookSample : MonoBehaviour {
public string fbAppID = "YOUR_FACEBOOK_APP_ID_HERE";
public GameObject picture;
//Texture2D tex;
void OnGUI () {
if(GUI.Button(GUIControls.GetButtonRect(1), "Init" ))
Facebook.Init(fbAppID);
if(GUI.Button(GUIControls.GetButtonRect(2), "Login" ))
Facebook.Login();
if(GUI.Button(GUIControls.GetButtonRect(3), "IsLoggedIn"))
Facebook.IsLoggedIn();
if(GUI.Button(GUIControls.GetButtonRect(4), "User Info")) {
Facebook.GetUserInfo();
}
if(GUI.Button(GUIControls.GetButtonRect(5), "Friends")) {
Facebook.GetFriendsList();
}
if (GUI.Button (GUIControls.GetButtonRect (6), "Load Profile Picture")) {
Facebook.LoadProfilePicture();
}
if (GUI.Button (GUIControls.GetButtonRect (7), "Get Profile Picture")) {
Texture2D tex = Facebook.GetProfilePicture();
picture.renderer.material.mainTexture = tex;
}
if(GUI.Button(GUIControls.GetButtonRect(8), "Send Request")) {
Facebook.SendRequest("This Plugin Rocks!");
}
if(GUI.Button(GUIControls.GetButtonRect(9), "Post To Timeline")) {
string name = "AxS Android Plugin";
string caption = "AxS Android Plugin for Unity";
string description = "A complete solution to all your Android native needs!";
string link = "http://www.axsu3d.com/";
string pictureLink = "http://www.axsu3d.com/DLs/axsu3dLogo.png";
Facebook.PostToTimeline(name, caption, description, link, pictureLink);
}
//Get the user's likes
if(GUI.Button(GUIControls.GetButtonRect(10), "User Likes")) {
Facebook.GetUserLikes();
}
//Logout of Facebook
if(GUI.Button(GUIControls.GetButtonRect(11), "Logout" ))
Facebook.Logout();
if(GUI.Button(GUIControls.GetButtonRect(12), "Back"))
Application.LoadLevel("CoreSample");
}
}
Firstly, wow. I didn't realize something I helped make would show up on SO.
The solution is quite simple, really. You probably did not use the "Merge Manifest" option.
You can find this option under "Tools/AxSU3D/Android/Merge Manifest". This will show a window where you can put in your Facebook app ID.
The option will create or merge a new AndroidManifest.xml file, which will also contain your Facebook App ID.
Try it out.

Categories

Resources