How to get power life of cell phone using Nativescript? - nativescript

I tried using nativescript like this but it doesnt work:
battery = navigator.battery || navigator.webkitBattery || navigator.mozBattery || navigator.msBattery;
console.log("battery level: ", Math.floor(this.battery.level * 100) + "%");

you have to write respective native codes for getting Battery info.
for android you can register broadcastreciever for ACTION_BATTERY_CHANGED. and for ios you can use UIDevice.currentDevice.batteryLevel
example:
import { android as androidApp, ios as iosApp } from "application";
import { ios as iosUtils } from "utils/utils";
if (iosApp){
iosUtils.getter(UIDevice, UIDevice.currentDevice).batteryMonitoringEnabled = true;
let battery = +(iosUtils.getter(UIDevice, UIDevice.currentDevice).batteryLevel * 100);
}else{
androidApp.registerBroadcastReceiver(android.content.Intent.ACTION_BATTERY_CHANGED,(context: android.content.Context, intent: android.content.Intent) =>{
let level = intent.getIntExtra(android.os.BatteryManager.EXTRA_LEVEL, -1);
let scale = intent.getIntExtra(android.os.BatteryManager.EXTRA_SCALE, -1);
let percent = (level / scale) * 100.0;
});
}

Related

Triggering a Lottie animation onScroll

im currently building a website using fullpage js and lottie animations. Now im trying to trigger an animation when the user scrolls to the section with the animation. Here is what i tried:
(please note that im very new to js)
$(document).ready(function($) {'use strict';
$('#fullpage').fullpage({
sectionsColor: ['white', '#004E8A', 'white','#004E8A', 'white', '#004E8A',
'white','#004E8A', 'white'],
anchors:['startseite','pers_vermittler','team','konzept','rechner','mod_portfolio','sicherheit','absatz'],
onLeave: function(index, nextIndex, direction) {
if( index == 3 && direction == 'down' ) {
lottie.play('k2an');
}
(at the end of the body section ->)
<script>
var params = {
container: document.getElementById('k2an'),
renderer: 'svg',
loop: true,
autoplay: false,
path: 'k2an.json',
};
anim = lottie.loadAnimation(params);
You should be using fullPage.js callbacks to fire your JS animations.
See the example:
$('#fullpage').fullpage({
anchors: ['firstPage', 'secondPage', 'thirdPage', 'fourthPage', 'lastPage'],
afterLoad: function(anchorLink, index){
var loadedSection = $(this);
//using index
if(index == 3){
alert("Section 3 ended loading");
}
//using anchorLink
if(anchorLink == 'secondSlide'){
alert("Section 2 ended loading");
}
}
});
Feel free to also check my video tutorial on how to create animations using fullPage.js state classes.
Right now im using this approach on a couple production sites. It plays the animation as the user scrolls.
I basically check how much of the animation objects box is visible in the viewport, calculate the total length of the animation (in frames) and then project the percentage to a frame where i gotoAndStop().
var anim = <YOUR LOTTIE ANIMATION OBJECT>
// play around with these
var speed = 1; // speed of animation
var scrollOffset = 0; // start animation sooner / later
function scrollHandler() {
if (!anim.isLoaded) return;
p = percentageSeen(e) / 100 - (scrollOffset || 0);
if (p <= 0 || p >= 1) return
var length = anim.totalFrames / anim.frameModifier;
var pos = length * p * (speed || 1);
anim.goToAndStop(pos);
}
$(window).on('scroll', scrollHandler);
/**
* returns percentage of scrolling element through viewport
* 0% until element-middle is at bottom of viewport
* 100% if element-middle is at top of viewport
*
* #param id
* #returns {number}
*/
function percentageSeen(idOrElement) {
var $element;
if (typeof idOrElement === 'object') {
$element = idOrElement;
} else {
$element = $('#' + id);
if (!$element[0]) return 0;
}
var $win = $(window), viewportHeight = $(window).height(),
scrollTop = $win.scrollTop(),
elementOffsetTop = $element.offset().top,
elementHeight = $element.height();
if (elementOffsetTop > (scrollTop + viewportHeight)) {
return 0;
} else if ((elementOffsetTop + elementHeight) < scrollTop) {
return 100;
} else {
var distance = (scrollTop + viewportHeight) - elementOffsetTop - (elementHeight / 2);
if (distance < 0) return 0;
var percentage = distance / (viewportHeight / 100);
if (percentage > 100) return 100;
return percentage;
}
}
If you want to only start the animation and let it run (independently of further user-scrolling-behaviour), just use the jquery inview plugin, disable autoplay on your animation and trigger the play() once like this:
$(".animation-container").one("inview", function() {
anim.play()
});

Detect iPhone X with Appcelerator

I am using custom navbar for my project and I am using codes for ios 7 top margin as below;
var _IsIos7Plus = false;
if (Titanium.Platform.name == 'iPhone OS') {
var _Version = Titanium.Platform.version.split(".");
var _Major = parseInt(_Version[0], 10);
if (_Major >= 7) {
_IsIos7Plus = true;
}
}
Alloy.Globals.Ios7TopMargin = _IsIos7Plus == true ? 20 : 0;
But iPhone X simulator shows 20 blank. Is there any way to detect iPhone X?
If you upgrade your project firstly you should check
Default-Portrait-2436h#3x.png
Default-Landscape-2436h#3x.png
splash screens are exists
Than you can detect iPhoneX code as below;
var IsIphoneX = (Ti.Platform.displayCaps.platformWidth === 375 && Ti.Platform.displayCaps.platformHeight === 812 && Ti.Platform.displayCaps.logicalDensityFactor === 3);

Unable to port Lumia imaging SDK2.0 to SDK 3.0(UWP)

I am having a tough time converting lumia imaging SDK 2.0 code to SDK3.0 in below specific case. I used to increase/decrease the image quality of JPG file using below code in Windows phone 8.1 RT apps:
using (StreamImageSource source = new StreamImageSource(fileStream.AsStreamForRead()))
{
IFilterEffect effect = new FilterEffect(source);
using (JpegRenderer renderer = new JpegRenderer(effect))
{
renderer.Quality = App.COMPRESSION_RATIO / 100.0; // higher value means better quality
compressedImageBytes = await renderer.RenderAsync();
}
}
Now since FilterEffect class has been replaced in SDK 3.0 with EffectList(), I changed code to
using (BufferProviderImageSource source = new BufferProviderImageSource(fileStream.AsBufferProvider()))
{
using (JpegRenderer renderer = new JpegRenderer())
{
IImageProvider2 source1 = new EffectList() { Source = source };
renderer.Source = source1;
renderer.Quality = App.COMPRESSION_RATIO / 100.0;
try
{
var img = await renderer.RenderAsync();
}
catch (Exception ex)
{
;
}
}
}
I am getting InvalidCastException exception. I have tried several combinations but no luck.
I don't really know what is going on with the InvalidCastException, we can continue that discussion in the comments as it will most likely need some back-and-forth.
That said, you could continue without the effect list, and chain effects in the normal way. So to rewrite your scenario:
using (var soruce = new StreamImageSource(...))
using (var renderer = new JpegRenderer(source))
{
renderer.Quality = App.COMPRESSION_RATIO / 100.0;
var img = await renderer.RenderAsync();
}
If you wanted to add an effect (for example a CarttonEffect), just do:
using (var soruce = new StreamImageSource(...))
using (var caroonEffect = new CartoonEffect(source))
using (var renderer = new JpegRenderer(caroonEffect))
{
renderer.Quality = App.COMPRESSION_RATIO / 100.0;
var img = await renderer.RenderAsync();
}
and so on. If you had effects A, B, C and D just make a chain Source -> A -> B -> C -> D -> JpegRenderer.
I am on VS 2015 community version. While digging around this, I got below code working which works exactly same as SDK 2.0. All I did was specified the Size of JpegRenderer. It works for all landscape images but fails to transform the portrait images to correct orientation. There is no exception but result of portrait image is widely stretched landscape image.
I initialized the Size for portrait images to Size(765, 1024) but no impact.
using (JpegRenderer renderer = new JpegRenderer(source))
{
renderer.Quality = App.COMPRESSION_RATIO / 100.0;
try
{
var info = await source.GetInfoAsync();
renderer.Size = new Size(1024, 765);
compressedImageBytes = await renderer.RenderAsync();
}
catch (Exception ex)
{
new MessageDialog("Error while compressing.").ShowAsync();
}
}
I am sorry the working code was using BufferProviderImageSource instead StreamImageSource. Below is the snippet. Few points here:
1) If I don't use Size property I get "The component cannot be found exception".
2) GetInfoAsync(): Yes it was useless for above code but I need to use it to know if image is Landscape or Portrait so that I can initialize Size property of resultant image.
3) If Size property goes beyond 1024x1024 for portrait images I get the exception "Value does not fall within the expected range"
Why lumia made this version so tricky. :(
var stream = FileIO.ReadBufferAsync(file);
using (var source = new BufferProviderImageSource(stream.AsBufferProvider()))
{
EffectList list = new EffectList() { Source = source };
using (JpegRenderer renderer = new JpegRenderer(list))
{
renderer.Quality = App.COMPRESSION_RATIO / 100.0;
renderer.OutputOption = OutputOption.PreserveAspectRatio;
try
{
var info = await source.GetInfoAsync();
double width = 0;
double height = 0;
if (info.ImageSize.Width > info.ImageSize.Height) //landscape
{
width = 1024;
height = 765;
if (info.ImageSize.Width < 1024)
width = info.ImageSize.Width;
if (info.ImageSize.Height < 765)
height = info.ImageSize.Height;
}
else //portrait..
{
width = 765;
height = 1024;
if (info.ImageSize.Width < 765)
width = info.ImageSize.Width;
if (info.ImageSize.Height < 1024)
height = info.ImageSize.Height;
}
renderer.Size = new Size(width, height);
compressedImageBytes = await renderer.RenderAsync();
}
catch (Exception ex)
{
new MessageDialog(ex.Message).ShowAsync();
}
}
}

CSS3 Animations support?

Anybody know where I can find a table of browsers and whether or not they support CSS3 animations and keyframes? Thanks
Can I Use is the place for all of this sort of thing, regularly updated, and always accurate!
http://caniuse.com/css-animation
They were implemented on these dates:
Safari 4.0: 11/06/2008
Chrome 1.0: 02/09/2008
Firefox 5: 20/04/2011
IE 10: 09/2011
They became part of the spec in 2009: http://www.w3.org/TR/css3-animations/
For more info, checkout http://css3.bradshawenterprises.com/support/ and http://css3.bradshawenterprises.com/animations/
I'm going this way. Instead of looking for the browser, I'm looking at feature detection. This nifty write-up will save me some work. So, I'm copying the code, you figure out what it all means :-).
/* Check if the Animation feature exists */
if(hasAnimation())
{
alert("Has!");
return;
}
function hasAnimation()
{
var elm = document.getElementById( 'imgDiv' )
animationstring = 'animation',
keyframeprefix = '',
domPrefixes = 'Webkit Moz O ms Khtml'.split(' '),
pfx = '';
if( elm.style.animationName === undefined )
{
var animation = false;
for( var i = 0; i < domPrefixes.length; i++ )
{
if( elm.style[ domPrefixes[i] + 'AnimationName' ] !== undefined )
{
pfx = domPrefixes[ i ];
animationstring = pfx + 'Animation';
keyframeprefix = '-' + pfx.toLowerCase() + '-';
animation = true;
break;
}
}
if( animation === false ) // animate in JavaScript fallback
return false;
}
/* Create animationstring */
elm.style[ animationstring ] = 'rotate 1s linear infinite';
var keyframes = '#' + keyframeprefix + 'keyframes rotate { '+
'from {' + keyframeprefix + 'transform:rotate( 0deg ) }'+
'to {' + keyframeprefix + 'transform:rotate( 360deg ) }'+
'}';
/* Add rule to stylesheet */
if( document.styleSheets && document.styleSheets.length )
{
document.styleSheets[0].insertRule( keyframes, 0 );
return true;
}
/* If there is no stylesheet, add rule to header */
var s = document.createElement( 'style' );
s.innerHTML = keyframes;
document.getElementsByTagName( 'head' )[ 0 ].appendChild( s );
return true;
}
Update: I've rewritten the code for clarity. Also the 'elm' element wasn't defined. The original demo code is here.
EDIT: I apologize to everyone for recommending a W3Schools link, I will NEVER do it again.
W3Schools usually has these types of table and information, check out this link.
It looks like as of now, the following browsers support CSS animations:
Firefox
Chrome
Safari
And, the ones left, which don't currently support it are:
IE
Opera

Get scaled image dimensions for spark image

Is there an equivalent to contentWidth and contentHeight for spark images?
I can get the size of the image component itself, as well as the sourceWidth and sourceHeight properties to get the unscaled size of the image.
But I can't work out the scaled image width and height of the source as displayed in the image component.
Any help greatly appreciated.
Was just trying to solve this exact issue. An adequate solution I found was to use IMAGE_ID.transform.pixelBounds.height (or width). Note that this won't be set until after the updateComplete event fires for the image. No idea why FLEX doesn't have a simple scaledWidth property.
Try extending the Spark Image component to include 2 new read-only properties to provide the scaled width and height as an equivalent to contentWidth and contentHeight.
The following will create 2 new bindable properties to return the actual scaled width and height of the image displayed inside the Spark Image component.
/**
* Returns the width of the image display taking into account the actual
* constraints of the container. If no scaling has occurred the actual
* width of the control is returned.
*/
[Bindable(event="scaledWidthChanged")]
public function get scaledWidth():Number
{
var num:Number = this.width;
if (scaleMode == "letterbox")
{
try
{
if ( (width > 0) && (sourceWidth < sourceHeight) )
{
num = (sourceWidth/sourceHeight) * width;
}
}
catch(e:Error)
{
num = this.width;
}
}
return num;
}
/**
* Returns the height of the image display taking into account the actual
* constraints of the container. If no scaling has occurred the actual
* height of the control is returned.
*/
[Bindable(event="scaledHeightChanged")]
public function get scaledHeight():Number
{
var num:Number = this.width;
if (scaleMode == "letterbox")
{
try
{
if ((height > 0) && (sourceHeight < sourceWidth))
{
num = (sourceHeight/sourceWidth) * height;
}
}
catch(e:Error)
{
num = this.height;
}
}
return num;
}

Resources