ionic是一个开源而且比较不错的混合app开发框架,集html5+css+angularJS+cordova而开发的一个纯手机端app框架。使用ionic可以轻而易举的制作出非常漂亮的app。下面我就利用ionic2制作一个手电筒软件,控制手机的闪光灯。
1、使用ionic官方的native文档中提到的flashlight插件(手电筒)
其实ionic的插件也就可以说是cordova的插件,因为cordova插件是JS写的,而ionic中则是使用微软的typescript,因此ionic官方已经将相应的cordova插件转换为typescript的了。
根据官方文档的介绍,很简单我们就可以实现手电筒的功能了,首先我们得安装cordova的flashlight插件,其次还要安装ionic的flashlight插件,使用如下命令:
ionic cordova plugin add cordova-plugin-flashlight
npm install --save @ionic-native/flashlight
我使用的是ionic2,而就在今天,我使用的版本中,安装cordova插件发生了错误,说cordova命令不存在,当然我肯定已经安装了cordova,后来我直接把前面的ionic去掉以后即可安装了。因此你要是遇到这样的问题,那么就修改下上面的代码如下:
cordova plugin add cordova-plugin-flashlight
npm install --save @ionic-native/flashlight
安装成功后,我们得先在src/app/app.modules.ts中添加flashlight插件,否则flashlight插件在其他页面将无法使用。
2、app.modules.ts代码
import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';
/* 在此添加flashlight插件 */
import { Flashlight } from '@ionic-native/flashlight';
import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';
@NgModule({
declarations: [
MyApp,
HomePage
],
imports: [
BrowserModule,
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HomePage
],
providers: [
StatusBar,
SplashScreen,
/* 在此注入flashlight插件 */
Flashlight,
{provide: ErrorHandler, useClass: IonicErrorHandler}
]
})
export class AppModule {}
3、home.ts代码
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { Flashlight } from '@ionic-native/flashlight';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
public icon_light='./assets/icon_light/lightoff.png';
public status = {
on:false,
off:true
};
constructor(public navCtrl: NavController,public flashlight: Flashlight) {
}
lightStatus(){
if(this.flashlight.isSwitchedOn()){
this.status.on = false;
this.status.off = true;
this.icon_light='./assets/icon_light/lightoff.png';
this.flashlight.switchOff();
}else{
this.status.on = true;
this.status.off = false;
this.icon_light='./assets/icon_light/lighton.png';
this.flashlight.switchOn();
}
}
}
4、home.html代码
点击屏幕开启手电
5、home.scss代码
page-home {
.content{
background: #f2f2f2;
color:#fff;
}
.content .light{
position: absolute;
top:50%;
left: 50%;
transform: translate(-50%,-50%);
text-align: center;
padding-bottom: 10px;
color: #333;
}
.status img{
width: 100px;
padding: 100px 10px;
}
}
上面的代码,请大家把img标签前面的#号删除。
这样就完成了手电筒的功能了。
我制作的apk最终效果如下
目前已经打包为安卓的apk文件(大家需要打包成apk文件的话,请看我另一一篇文章ionic2签名打包),大家可以下载测试哈!
点此下载手电筒APK(安卓版)