如何使用NativeScript监听传入的短信?

时间:2017-05-27 14:50:46

标签: android angular android-intent nativescript

我想听RECEIVE_SMS意图读取通过Textscript中的文本消息传递的一次性密码(使用Angular2)。我正在遵循http://docs.nativescript.org/cookbook/application中列出的步骤。但是,当我运行代码时,我收到以下错误:

app/app.component.ts(12,6): error TS1005: ';' expected.
app/app.component.ts(12,14): error TS1005: ';' expected.
app/app.component.ts(12,48): error TS1005: ',' expected.
app/app.component.ts(12,57): error TS1005: ',' expected.
app/app.component.ts(12,67): error TS1005: ',' expected.
app/app.component.ts(12,82): error TS1138: Parameter declaration expected.
app/app.component.ts(12,118): error TS2503: Cannot find namespace 'android'.
app/app.component.ts(12,151): error TS2503: Cannot find namespace 'android'.
app/app.component.ts(13,36): error TS2304: Cannot find name 'android'.
app/app.component.ts(14,36): error TS2304: Cannot find name 'android'.
app/app.component.ts(17,4): error TS1128: Declaration or statement expected.
app/app.component.ts(18,1): error TS1128: Declaration or statement expected.

这是我的app.component.ts:

import { Component } from "@angular/core";

@Component({
  selector: "my-app",
  template: `
    <ActionBar title="My App"></ActionBar>
    <!-- Your UI components go here -->
  `
})
export class AppComponent {
  // Your TypeScript logic goes here
  app.android.registerBroadcastReceiver(android.provider.Telephony.SMS_RECEIVED, function onReceiveCallback(context: android.content.Context, intent: android.content.Intent) {
    console.log('rcvd');
  });
}

2 个答案:

答案 0 :(得分:1)

看起来你没有导入所需的模块

import { Component, OnInit } from "@angular/core";
import * as app from "tns-core-modules/application";
import * as platform from "tns-core-modules/platform";

//declare this to use android variable
declare var android:any;

@Component({
  selector: "my-app",
  template: `
    <ActionBar title="My App"></ActionBar>
    <!-- Your UI components go here -->
   `
 })
export class AppComponent{

 ngOnInit(){
app.android.registerBroadcastReceiver(android.provider.Telephony.SMS_RECEIVED, function onReceiveCallback(context: android.content.Context, intent: android.content.Intent) {
console.log('rcvd');
 });}
}

答案 1 :(得分:0)

您的语法不正确。你应该把你的听力函数放在ngOnInit钩子里面:

import {OnInit} from '@angular/core'

export class AppComponent implements OnInit {

    ngOnInit() {

    // your code here
    }
}