ionic2 Streaming Media is not working - android

I'm using the streaming media plugin in my ionic2 application.
this is my code:
let option:StreamingAudioOptions = {
successCallback: () => { console.log('Audio played') },
errorCallback: (e) => { console.log(JSON.stringify(e,null,2)) }
}
this.streamingMedia.playAudio('http://sounddible.com/grab.php?id=2196&type=mp3',option);
the errorCallback return "Class not found"
Any help for explain the reason of this log
Thanks.

try below code :
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { StreamingMedia, StreamingAudioOptions } from '#ionic-native/streaming-media';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController,private streamingMedia: StreamingMedia) {}
startAudio(){
let options: StreamingAudioOptions = {
successCallback: () => { console.log('Video played') },
errorCallback: (e) => { console.log(JSON.stringify(e,null,2)) },
initFullscreen:false,
};
this.streamingMedia.playAudio('YOUR_URL', options);
}

Related

Ionic 5 Capacitor hardware back button ending the app

I have a problem testing my ionic app on my phone and android studio, when i press the hardware back button the application inmediatly exits, i've tried many solutions, but it simply won't work and won't listen to whatever i code into it.
Here is my attempt
import { Component, Renderer2, ViewChild } from '#angular/core';
import { IonRouterOutlet, Platform } from '#ionic/angular';
import { SplashScreen } from '#ionic-native/splash-screen/ngx';
import { StatusBar } from '#ionic-native/status-bar/ngx';
import { TranslateService } from '#ngx-translate/core';
import { Location } from '#angular/common';
#Component({
selector: 'app-root',
templateUrl: 'app.component.html',
styleUrls: ['app.component.scss']
})
export class AppComponent {
#ViewChild(IonRouterOutlet, {static: true}) routerOutlet: IonRouterOutlet
constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar,
private renderer: Renderer2,
private translate: TranslateService,
private location: Location
) {
this.initializeApp();
}
initializeApp() {
this.translate.setDefaultLang( localStorage.getItem('default-language') ? localStorage.getItem('default-language') : navigator.language.slice(0, 2) )
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
this.backButtonEvent();
if (localStorage.getItem('color-theme')) {
this.renderer.setAttribute(document.body, 'color-theme', localStorage.getItem('color-theme'))
} else {
if(window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches === true)
this.renderer.setAttribute(document.body, 'color-theme', 'light')
else
this.renderer.setAttribute(document.body, 'color-theme', 'dark')
}
});
}
backButtonEvent() {
this.platform.backButton.subscribeWithPriority(0, async () => {
if(!this.routerOutlet.canGoBack())
navigator["app"].exitApp()
else
this.location.back()
});
}
}
Try it this way using the #capacitor/app package:
import { App } from '#capacitor/app';
App.addListener('backButton', ({ canGoBack }) => {
if(canGoBack){
window.history.back();
} else {
App.exitApp();
}
});

Ionic-5 app is closing instead back to previous page on click of hardware back button

I am using angular 7 and ionic 5. When i want to redirect to previous page using hardware back button, ionic app is closing itself. I am using below code but its not working.
this.platform.backButton.subscribeWithPriority(9999, () => {
document.addEventListener('backbutton', function (event) {
event.preventDefault();
event.stopPropagation();
console.log('hello');
}, false);
});
If you are using ionic with Capacitor you need to use this code in the constructor of app.component.ts:
import { App } from '#capacitor/app';
import { Location } from '#angular/common';
constructor(private _location: Location)
{
App.addListener('backButton', () =>
{
if (this._location.isCurrentPathEqualTo('/home'))
{
navigator['app'].exitApp();
}
else
{
this._location.back();
}
});
}
I use the directive for this
import { Directive, HostListener } from '#angular/core';
import { PlatformService } from 'src/app/services/platform';
#Directive({
selector: '[disableBackButton]'
})
export class DisableBackButtonDirective {
constructor(
private platformService: PlatformService
) { }
#HostListener('document:ionBackButton', ['$event'])
overrideHardwareBackAction(event: any) {
if (this.platformService.isPlatform('android')) {
event.detail.register(100, async () => {
event.stopImmediatePropagation();
event.stopPropagation();
event.preventDefault();
});
}
}
}
in page.html
<ion-content disableBackButton>
....
</ion-content>
in page.ts
this.platform.backButton.subscribe(() => {
console.log('hello');
});
Try this,
this.platform.backButton.subscribeWithPriority(10, () => {
this.router.navigate(['']); // route to previous page or component
});

how to launch camera in an ionic app

I have created the basic ionic app which can launch camera. I installed all the required plugins and also i have used the right version of cordova . I am not getting any errors and also able to create apk for that . When using in apk in the android mobile, camera is not getting launched.
this is the home.html code adding camera module
<button ion-button (click)="takePhoto()">camera</button>
<p align="center"><img src="{{ myphoto }}"></p>
this is the home.ts file
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Camera, CameraOptions } from '#ionic-native/camera';
import { Database } from '../../providers/database/database';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
tabBarElement: any;
splash = true;
myphoto:any;
public hasTrees : boolean = false;
public trees : any;
constructor(public navCtrl: NavController, private camera:Camera,
public DB : Database) {
this.tabBarElement = document.querySelector('.tabbar');
}
takePhoto(){
const options: CameraOptions = {
quality: 70,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64:
this.myphoto = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
// Handle error
});
}
ionViewDidLoad() {
this.tabBarElement.style.display = 'none';
setTimeout(() => {
this.splash = false;
this.tabBarElement.style.display = 'flex';
}, 4000);
}
ionViewWillEnter()
{
this.displayTrees();
}
displayTrees()
{
this.DB.retrieveTrees().then((data)=>
{
let existingData = Object.keys(data).length;
if(existingData !== 0)
{
this.hasTrees = true;
this.trees = data;
}
else
{
console.log("we get nada!");
}
});
}
addSpecies()
{
this.navCtrl.push('Add');
}
viewSpecies(param)
{
this.navCtrl.push('Add', param);
}
}

Transparent status bar ionic2

I need transparent status bar ionic 2.
I installed npm install --save #ionic-native/status-bar.and also
refer this link https://ionicframework.com/docs/v2/native/status-bar/
I used this.statusBar.backgroundColorByHexString("#0e5591"); But It's not working.
Below my app component.
import { Component, ViewChild,Inject } from '#angular/core';
import { Nav,NavController,Platform ,AlertController,MenuController,App,IonicApp} from 'ionic-angular';
import { Splashscreen ,Network,Toast} from 'ionic-native';
import { StatusBar } from '#ionic-native/status-bar';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
public app: App;
currentuser;
#ViewChild(Nav) nav1: Nav;
auth:any;
menu;
nav:NavController;
constructor(private statusBar: StatusBar,public appCtrl: App,public menu1: MenuController,public alertCtrl:AlertController,public platform: Platform,public authservice:Authservice) {
this.auth=localStorage.getItem("email");
console.log("Auth"+this.auth);
// this.rootPage = this.isUserLoggedIn ? LoginPage : MycomplaintsPage;
// console.log(this.rootPage);
if(this.auth != undefined && this.auth != null)
{
this.rootPage = DashboardPage;
}
this.showRoot = true;
this.initializeApp();
}
initializeApp() {
this.platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
this.statusBar.styleDefault();
this.statusBar.backgroundColorByHexString("#0e5591");
Splashscreen.hide();
if(Network.type === Connection.NONE)
{
console.log("success");
let alert = this.alertCtrl.create({
title: "Internet Connection",
subTitle:"Please Check Your Network connection",
buttons: [
{
text: 'Ok',
handler: () => {
this.platform.exitApp();
}
}
]
});
alert.present();
}
});
}
exit(){
let alert = this.alertCtrl.create({
title: 'Confirm',
message: 'Do you want to exit?',
buttons: [{
text: "exit?",
handler: () => { this.exitApp() }
}, {
text: "Cancel",
role: 'cancel'
}]
})
alert.present();
}
exitApp(){
this.platform.exitApp();
}
}
I am getting this err
ORIGINAL EXCEPTION: No provider for StatusBar!
Kindly advice me,
Thanks
It looks like you have two versions of ionic native from your imports.
import { Splashscreen ,Network,Toast} from 'ionic-native';
import { StatusBar } from '#ionic-native/status-bar';
Make sure you only have #ionic-native/core in your package.json.
Also according to the latest ionic-native docs,
you need to set the plugin as provider in ngModule:
#NgModule({
...
providers: [
...
Statusbar
...
]
...
})

Open a file within the app folder with fileOpener Ionic2

this is my code :
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { FileOpener } from 'ionic-native';
#Component({
selector: 'page-installHelper',
templateUrl: 'installHelper.html'
})
export class InstallHelper {
constructor(public navCtrl: NavController) {
FileOpener.open('assets/app.apk', 'application/vnd.android.package-archive').then(
function(){
console.log("success");
}, function(err){
console.log("status : "+err.status);
console.log("error : "+err.message);
});
}
}
but I can't access the file app.apk which is in assets/app.apk
and I get the error :
Status : 9
Error : File Not Found
is it even possible to access a file within the app folders ?
Well I did it by making the app get downloaded from a server to a local folder I created in the phone and install it immediately/automatically,
Here is the code in case someone else needed it one day :
import { Component } from '#angular/core';
import { Platform, LoadingController } from 'ionic-angular';
import { StatusBar, Splashscreen } from 'ionic-native';
import { FileOpener } from 'ionic-native';
import { File } from 'ionic-native';
import { Transfer } from 'ionic-native';
import { HomePage } from '../pages/home/home';
declare var cordova: any;
#Component({
template: `<ion-nav [root]="rootPage"></ion-nav>`
})
export class MyApp {
rootPage = HomePage;
constructor(platform: Platform, public loadingCtrl: LoadingController) {
let me = this;
platform.ready().then(() => {
let loading = me.loadingCtrl.create({
content: 'Preparing The App ...'
});
loading.present();
File.createDir(cordova.file.externalDataDirectory, "appFolder", true).then(function(link){
const fileTransfer = new Transfer();
let url = 'http://yourserverhere.com/app.apk';
fileTransfer.download(url, cordova.file.externalDataDirectory +"appFolder/app.apk").then((entry) => {
loading.dismiss();
FileOpener.open(entry.toURL(), "application/vnd.android.package-archive").then(
function(){
console.log("success");
},function(err){
console.log("status : "+err.status);
console.log("error : "+err.message);
});
}, (error) => {
console.log(error);
});
},function(error){
console.log(error);
});
StatusBar.styleDefault();
Splashscreen.hide();
});
}
}
Any explanation just ask me.
Well since you want the user to download the .apk file, you could use (in your html)
<a href="assets/app.apk" download>Download apk</a>
But the user will have to manually open his downloads (or tap the popup) to install your app.
I do not know if there is a plugin which is capable of installing these apk files. (Googling for ionic 2 install external apk didn't return any results).

Categories

Resources