Xamarin: how to Start an Application at Device Bootup in Android

This tutorial will explain to stat an application while the Android device boot-up. For this, we need to  listen to the BOOT_COMPLETED action and react to it.

BOOT_COMPLETED is a Broadcast Action that is broadcast once, after the system has finished booting. You can listen to this action by creating a BroadcastReceiver that then starts your launch Activity when it receives an intent with the BOOT_COMPLETED action.

Add this permission to your manifest

In your Android.Manifest you must add thi permission:

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

 

BackgroundTest-AndroidManifest

Then open this file and add the following rows under Application:

    <receiver android:name=".BootReceiver" android:enabled="true" 
              android:permission="android.permission.RECEIVE_BOOT_COMPLETED" >
      <intent-filter>
        <action android:name="android.intent.action.BOOT_COMPLETED" />
        <category android:name="android.intent.category.DEFAULT" />
      </intent-filter>
    </receiver>

In this example, we will create a new BroadcastReceiver called BootReceiver.

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using Android.App;
using Android.Content;
using Android.OS;
using Android.Runtime;
using Android.Views;
using Android.Widget;

namespace BackgroundTest.Droid.BackgroundServices
{
    public class BootReceiver : BroadcastReceiver
    {
        public override void OnReceive(Context context, Intent intent)
        {
            Intent i = new Intent(context, typeof(MainActivity));
            i.AddFlags(ActivityFlags.NewTask);
            context.StartActivity(i);
        }
    }
}

Install the application, and then restart the device. You can see the application will start after the device restarts. An implementation of background services starting with Activity, it explains here.

Source code on GitHub.

Happy coding!

Microsoft warns iOS isn't as secure as you think

Microsoft_Cybercrime_Center

Microsoft has warned customers that iOS is no more secure than Android, contradicting commonly held beliefs about the relative security of the two platforms. The company said that recent attacks targeting iOS prove it's as vulnerable as Android.

Brad Anderson, Microsoft's corporate vice president for enterprise and client mobility, set out his views in a company blog post last week. He used the Pegasus iOS spyware, revealed last month, as an example of severe vulnerabilities present in iOS. Pegasus is capable of monitoring everything a user does on their device, leaving them vulnerable to further attack.

The malware was analysed by Lookout Security, a Microsoft partner. In its report, Lookout described Pegasus as "the most sophisticated attack we've seen on any endpoint." Since it originates from a leading iOS security firm, Anderson said the statement reveals a lot about the state of security on Apple's platform.

Anderson is attempting to challenge the trust that consumers typically place in Apple. Android threats are far more numerous and gain more widespread attention than attacks on iOS. iOS is not immune to potentially devastating malware though, in contradiction of the views of some customers. Anderson said Pegasus should be a "pretty startling wake-up call" that everyone is "under constant persistent attack" on every platform.

Microsoft executives have reportedly indicated "unwavering implicit trust" in Apple's iOS "countless times," revealing how strong the association between Apple and security has become. The belief that Apple's platform is stronger than Android appears to derive from iOS' closed nature. Because it's a more controlled ecosystem, the attack surface is lower than for Android malware.

This view is dangerous, according to Anderson. Every mobile device is at constant risk of attack, regardless of the platform it runs. "I know for a fact that all the providers of mobile operating systems go to superhuman lengths to harden their platforms and do everything they can to deliver the most secure operating system possible," said Anderson.

However, iOS, Android and Windows all have vulnerabilities that expose them to potentially devastating attacks. Some platforms are targeted more frequently than others but this shouldn't influence people to make assumptions about a platform's security. Pegasus demonstrates that even a closed ecosystem can be infiltrated by some of the most complex mobile malware ever observed.

Coming from Microsoft, Anderson's argument represents a powerful message to businesses and consumers that iOS may not be all it seems. Pegasus has proven iOS presents a viable attack vector to cybercriminals. It has also demonstrated that malware has been commercialised to the point that it's an off-the-shelf product, available for purchase from the secretive NSO Group. According to Microsoft, the idea of a single platform being more secure than others is an urban myth. In real-world terms, any device can be hacked and every user is a target.

Preserve data when deploying Xamarin.Android app

By default all your data from your previous runs is deleted when you’re deploying an Xamarin.Android app. In many cases you don’t want the data to be deleted.

Visual Studio


To preserve data go to Tools -> Options -> Xamarin -> Android Settings and check “Preserve application data/cache on device between deploys”.

Preserve_data_visualstudio

Xamarin Studio


To preserve data go to Tools -> Options -> Android and check “Preserve data/cache between application deploys”.

Preserve_data_xamarinstudio

Happy coding!

Xamarin Forms and Google Mobile Ads for iOS

If you have a new Xamarin Project and you want to add an advertising, the simple way it is to use Google Admob. This implementation is only for Android and iOS.

One of the first things people think about when developing for a new platform / using a new technology is monetization; and in my case the question is: how easy is it to integrate AdMob? For Xamarin Forms the answer would be: “It depends” – it depends on luck & on the complexity of what you want to achieve; but I will detail this as we move along.

The first thing you need to do is add the required components to your projects. For this walktrough I will be using Visual Studio but it should be relatively the same when using Xamarin Studio. Here, things go separate ways for each of the platforms:

  • for Android – add the Google Play Services component
  • for iOS – add the AdMob component
  • for Windows Phone – download the SDK from here and add it as a reference

By now, you Android project should no longer be building & you should be receiving a COMPILETODALVIK : UNEXPECTED TOP-LEVEL error. To fix that, go into your Droid project properties, select the Android Options tab and then under Advanced modify the value for the Java Max Heap Size to 1G. Your project should now build without any errors.

Next, inside your shared / PCL project add a new Content View and call it AdMobView. Remove the code generated inside it’s constructor & it should look like this:

public class AdMobView : ContentView
{
    public AdMobView() { }
}

Add this new view to your page. In XAML you can do it like this:

<controls:AdMobView WidthRequest="320" HeightRequest="50" />

Make sure NOTHING interferes with the control. By nothing I mean – overlapping controls, page padding, control margins / spacing, etc. If you have something overlapping the ad control, ads will not display & you won’t receive an error, so be careful.

Android

Add a new class called AdMobRenderer with the code below. Make sure to keep the ExportRenderer attribute above the namespace, otherwise the magic won’t happen.

using WordBankEasy.Droid.Renderers;
using WordBankEasy.Views.AdMob;
using Xamarin.Forms;
using Xamarin.Forms.Platform.Android;

[assembly: ExportRenderer(typeof(AdMobView), typeof(AdMobRenderer))]

namespace WordBankEasy.Droid.Renderers {
    public class AdMobRenderer : ViewRenderer<AdMobView, Android.Gms.Ads.AdView> {
        protected override void OnElementChanged(ElementChangedEventArgs<AdMobView> e) {
            base.OnElementChanged(e);

            if (Control == null) {
                var ad = new Android.Gms.Ads.AdView(Forms.Context);
                ad.AdSize = Android.Gms.Ads.AdSize.Banner;
                ad.AdUnitId = "ca-app-pub-4381168884554284/2250461656";

                var requestbuilder = new Android.Gms.Ads.AdRequest.Builder();
                ad.LoadAd(requestbuilder.Build());

                SetNativeControl(ad);
            }
        }
    }
}

Next, you need to modify your AndroidManifest.xml file to add the AdActivity & required permissions for displaying ads: ACCESS_NETWORK_STATE, INTERNET; just like in the example below (see also http://puresourcecode.com/dotnet/post/Android-required-permissions).

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android">
    <uses-sdk android:minSdkVersion="15" />
    <application>
    <activity android:name="com.google.android.gms.ads.AdActivity" 
            android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize" android:theme="@android:style/Theme.Translucent" />
    </application>
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.INTERNET" />
</manifest>

That’s it. Your Android build should now display ads inside the AdMobView content view.

iOS

This, I haven’t got the chance to test yet as I don’t have a Mac around but people say it works, so I’ve added it for reference. Same as before, just add a new class called AdMobRenderer and copy-paste the code below but before you have to add a component.

In your iOS project click on “Components” (as in the picture)

Components

and click on “Get More Components…”. Then search admob and install it.

Google-Admob-Xamarin

using Xamarin.Forms;
using CoreGraphics;
using Xamarin.Forms.Platform.iOS;
using UIKit;
using WordBankEasy.Views.AdMob;
using WordBankEasy.iOS.Renderers;
using Google.MobileAds;

[assembly: ExportRenderer(typeof(AdMobView), typeof(AdMobRenderer))]
namespace WordBankEasy.iOS.Renderers {
    public class AdMobRenderer : ViewRenderer {
        const string AdmobID = "ca-app-pub-4381168884554284/5843056458";

        BannerView adView;
        bool viewOnScreen;

        protected override void OnElementChanged(ElementChangedEventArgs<Xamarin.Forms.View> e) {
            base.OnElementChanged(e);

            if (e.NewElement == null)
                return;

            if (e.OldElement == null) {
                adView = new BannerView(size: AdSizeCons.Banner, origin: new CGPoint(-10, 0)) {
                    AdUnitID = AdmobID,
                    RootViewController = UIApplication.SharedApplication.Windows[0].RootViewController
                };

                adView.AdReceived += (sender, args) => {
                    if (!viewOnScreen) this.AddSubview(adView);
                    viewOnScreen = true;
                };

                adView.LoadRequest(Request.GetDefaultRequest());
                base.SetNativeControl(adView);
            }
        }
    }
}

Here you can receive an strange error like:

Foundation.MonoTouchException: Objective-C exception thrown. Name: NSInvalidArgumentException Reason: -[AppDelegate window]: unrecognized selector sent to instance 0x7ffee9cdd4d0

Native stack trace:

0 CoreFoundation 0x000000010a12ed85 __exceptionPreprocess + 165

1 libobjc.A.dylib 0x000000010a5e3deb objc_exception_throw + 48

2 CoreFoundation 0x000000010a137d3d -[NSObject(NSObject) doesNotRecognizeSelector:] + 205

3 CoreFoundation 0x000000010a07db17 forwarding + 487

4 CoreFoundation 0x000000010a07d8a8 _CF_forwarding_prep_0 + 120

5 WordBankEasyiOS 0x0000000100bc65e4 GADiTunesMetadataForFileAtPath + 4181

6 WordBankEasyiOS 0x0000000100c2d484 hasRequiredParams + 10260

7 WordBankEasyiOS 0x0000000100bc5f06 GADiTunesMetadataForFileAtPath + 2423

8 WordBankEasyiOS 0x0000000100bc1c35 GADCategories_NSURL_GADNSURLUtilities + 4438

9 WordBankEasyiOS 0x0000000100c00fde GADDispatchAsyncSafeMainQueue + 45

10 libobjc.A.dylib 0x000000010a5e4bff _class_initialize + 679

11 libobjc.A.dylib 0x000000010a5eacc5 lookUpImpOrForward + 176

12 libobjc.A.dylib 0x000000010a5f98bb objc_msgSend + 187

13 WordBankEasyiOS 0x0000000100bbe0ff GADCategories_DFPBannerView_CustomRenderedAd + 18074

14 WordBankEasyiOS 0x0000000100bbe382 GADCategories_DFPBannerView_CustomRenderedAd + 18717

15 WordBankEasyiOS 0x0000000100bbe527 GADCategories_DFPBannerView_CustomRenderedAd + 19138

16 ??? 0x000000011d368a0e 0x0 + 4785080846

17 ??? 0x000000011d36843b 0x0 + 4785079355

18 ??? 0x000000011d364d88 0x0 + 4785065352

19 ??? 0x000000011c51bbd6 0x0 + 4770085846

20 ??? 0x000000011c51b138 0x0 + 4770083128

21 ??? 0x000000011c51b138 0x0 + 4770083128

22 ??? 0x000000011c51b138 0x0 + 4770083128

Don't worry! I received the same error and I spend a lot of time to understand and fix it. There is a workaround that seems working fine.

In your iOS project, open AppDelegate.cs and add this code:

/// <summary>
/// Gets the window.
/// </summary>
/// <returns>UIWindow.</returns>
[Export("window")]
public UIWindow GetWindow() {
   return UIApplication.SharedApplication.Windows[0];
}

A complete example of this class is:

using System;
using System.Collections.Generic;
using System.Linq;

using Foundation;
using ImageCircle.Forms.Plugin.iOS;
using UIKit;

namespace WordBankEasy.iOS {
    // The UIApplicationDelegate for the application. This class is responsible for launching the 
    // User Interface of the application, as well as listening (and optionally responding) to 
    // application events from iOS.
    [Register("AppDelegate")]
    public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate {
        //
        // This method is invoked when the application has loaded and is ready to run. In this 
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary options) {
            global::Xamarin.Forms.Forms.Init();

            ImageCircleRenderer.Init();

            LoadApplication(new App());

            return base.FinishedLaunching(app, options);
        }

        /// <summary>
        /// Gets the window.
        /// </summary>
        /// <returns>UIWindow.</returns>
        [Export("window")]
        public UIWindow GetWindow() {
            return UIApplication.SharedApplication.Windows[0];
        }
    }
}

After that you can start you app and see you advertising without problem. For now :)

Happy coding!

Google opens Chromebooks to Android store

Google's Chromebook update will allow the inexpensive laptops to run apps from the Android store opening them up to apps from Microsoft Word to Quicken.

Android.Content.Res.Resources+NotFoundException: Resource ID #0x0

I've just created a simple MasterDetailPage and in the code I inserted an icon for the left page with:

public MainPage() {
    InitializeComponent();

    BackgroundColor = Color.FromHex("#007acc");
    Icon = "settings.png";
}

I tried to deploy my app on an Android emulator but I can't deploy it because Android.Content.Res.Resources+NotFoundException: Resource ID #0x0.

I checked everthing and evething seemed fine. The problem is the icon!

You have to remove Icon from the code and in the XAML page type the following code:

  <ContentPage.Icon>
    <OnPlatform x:TypeArguments="FileImageSource">
      <OnPlatform.iOS>settings.png</OnPlatform.iOS>
    </OnPlatform>
  </ContentPage.Icon>

Happy coding!

Installing Google Play Services in the Microsoft Visual Studio Android Emulator

Installing the Google Play Services in Microsoft’s Visual Studio Android Emulator that comes with Visual Studio 2015 is easy to do. This installs the Google Play store and related services, which makes it possible to install other apps to your Android image.

  1. Download the Google Apps package from the Team Android site. Make sure that you match the version of the apps to the version of Android that your emulator is for. The default emulator is for Kit Kat, but this also works for Lollipop.
  2. Start the Microsoft Visual Studio Android Emulator
  3. Start the Android virtual machine that matches the version of the apps that you downloaded for (default would be Kit Kat).
  4. Unlock the Android VM so you get to the home screen
  5. Drag and drop the downloaded Google Apps package in to the Android VM. You will get a prompt to install the apps that looks like this: Install-Goople-Play-Microsoft-Android-Emulator
  6. Select the “Install and Shut Down” option.
  7. Start the VM again
  8. Click the All Apps button in Android and you will see the Google Play store.
  9. When you open the Google Play store, you will need to login with your Google account and make a new one.

Once you have the Google Play store installed, you should be able to install other common applications. I tested this by installing Chrome and it worked well.

275 million Android phones imperiled by new code-execution exploit

metaphor-expoit-demo-640x360

Almost 300 million phones running Google's Android operating system are vulnerable to a newly developed drive-by attack that can install malware and take control of key operations, a security firm has warned.

A proof-of-concept exploit dubbed Metaphor works against Android versions 2.2 through 4.0 and 5.0 and 5.1, which together are estimated to run 275 million phones, researchers from Israeli security firm NorthBit said. It attacks the same Stagefright media library that made an estimated 950 million Android phones susceptible to similar code-execution attacks last year. The following video demonstrates how a malicious attacker might use a Metaphor-style attack to take control of a phone after luring an unsuspecting end user to a booby-trapped website.

The NorthBit-developed attack exploits a Stagefright vulnerability discovered and disclosed last year by Zimperium, the security firm that first demonstrated the severe weaknesses in the code library. For reasons that aren't yet clear, Google didn't fix the vulnerability in some versions, even though the company eventually issued a patch for a different bug that had made the Zimperium exploits possible. While the newer attack is in many ways a rehash of the Zimperium work, it's able to exploit an information leak vulnerability in a novel way that makes code execution much more reliable in newer Android releases. Starting with version 4.1, Android was fortified with an anti-exploitation defense known as address space layout randomization, which loads downloaded code into unpredictable memory regions to make it harder for attackers to execute malicious payloads. The breakthrough of Metaphor is its improved ability to bypass it.

"They've proven that it's possible to use an information leak to bypass ASLR," Joshua Drake, Zimperium's vice president for platform research and exploitation, told Ars. "Whereas all my exploits were exploiting it with a brute force, theirs isn't making a blind guess. Theirs actually leaks address info from the media server that will allow them to craft an exploit for whoever is using the device."

The other big advance offered by Metaphor is that it works on a wider base of phones. Previous patches published by Google make anyone with version 5.1 or higher immune, and in some cases those may also protect users of 4.4 or higher, Drake said. Metaphor, by contrast, exposes users of 5.1, which is estimated to run on 19 percent of Android phones. Currently, Metaphor works best on Nexus 5 models with a stock ROM, but it also works on the HTC One, LG G3, and Samsung S5, the company said. Depending on the vendor, a drive-by attack requires anywhere from 20 seconds to two minutes to work.

Microsoft Builds Android App Store For Its Own Android Apps Inside Of The Android App Store

microsoft-android2

Microsoft has a new app out called ‘Microsoft Apps‘ on Android that contains a list of its Android apps that you can download on the Android app store.

There are two parts to this development. The first is that Microsoft’s cross-platform work continues, and that the company has yet to let up an inch on its work to bring its software and services to users on every rival operating system. And, the second point is that Microsoft has created an effective Android app store — catalog? — inside of the actual Android app store.

An early comment noted that fact. From the app’s page on Google Play:

microsoft_android_post

That comment is almost correct. At the same time, it can be difficult to sort through tens, and hundreds of thousands of apps to find the precise one that you are perhaps looking for. Microsoft wants to make sure that if you want to use its stack on Android, you can do so without unnecessary sleuthing.

The app has racked up four review so far, giving it an average score of 4 stars.

The new app might not make sense until you realize just how many apps Microsoft has on Android — you can take a spin through the full list here. It’s extensive. It’s almost odd to recall how big a splash bringing Office to Android and iOS once was.

Microsoft fans have a new toy, and the company has a potential conduit for its apps on the Android platform. Not too bad a turn of events for the Redmond-based software company.

Microsoft's new service makes app developers out of everyday employees

microsoft_powerapps_3

Work is growing increasingly mobile thanks to smartphones, but companies can have a hard time coping with demand for apps that let their workers take corporate data on the go. Mobile developers are expensive, and getting new applications tested and then pushed out to users can be a time-consuming process.

Microsoft just unveiled a new beta service on Monday that's supposed to help ease that tension by allowing anyone to build an app - no software development experience required. PowerApps combines a cloud application backend with easy-to-use tools that make creating a mobile app a drag-and-drop affair.

microsoft_powerapps_1

PowerApps applications can pull in information from a variety of data sources including Office 365, Dynamics, Google Drive, Workday and other services. Developers can also build connections for PowerApps in their own services if there isn’t a connector already available.

Once the data connection is set up, users can then start building an application interface from one of Microsoft’s pre-built templates, or plug key data into PowerApps and let the service suggest the right designs for their purposes. Those people who have a strong idea for what they want their app to look like can create it from scratch.

microsoft_powerapps_2

Once users have built the apps they want, they can then use Microsoft's service to share their newly created tools with coworkers who have the PowerApps application installed on their smartphones.

The system is currently limited to building software that runs inside the PowerApps app on mobile devices, however, so employees won’t be able to push their creations to the iOS App Store or Google Play Store. Microsoft Corporate Vice President Bill Staples said during a press briefing that Microsoft will consider feedback from its customers when determining if the company should make it possible to create standalone applications using PowerApps.

Advertsing

125X125_06

Planet Xamarin

Planet Xamarin

Calendar

<<  September 2017  >>
MonTueWedThuFriSatSun
28293031123
45678910
11121314151617
18192021222324
2526272829301
2345678

View posts in large calendar

Month List