Flutter firebase background notification I pushed the image notification but it's showing only text but if app open it's working fine but app terminated or minimize it's showing only default notification I tried everything but it doesn't work I referred this also https://pub.dev/packages/firebase_messaging no use.
check this image
background notification not showing that image?
Application.kt
package YOUR PACKAGE
import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback
import io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin
import io.flutter.view.FlutterMain
import io.flutter.plugins.firebasemessaging.FlutterFirebaseMessagingService
import com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin
class Application : FlutterApplication(), PluginRegistrantCallback {
override fun onCreate() {
super.onCreate()
FlutterFirebaseMessagingService.setPluginRegistrant(this);
FlutterMain.startInitialization(this)
}
override fun registerWith(registry: PluginRegistry?) {
if (!registry!!.hasPlugin("io.flutter.plugins.firebasemessaging")) {
FirebaseMessagingPlugin.registerWith(registry!!.registrarFor("io.flutter.plugins.firebasemessaging.FirebaseMessagingPlugin"));
}
if (!registry!!.hasPlugin("com.dexterous.flutterlocalnotifications")) {
FlutterLocalNotificationsPlugin.registerWith(registry!!.registrarFor("com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin"));
}
}
}
MainActivity.kt
package YOUR PACKAGE
import io.flutter.embedding.android.FlutterActivity
class MainActivity: FlutterActivity() {
}
AndroidManifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="YOUR PACKAGE"
xmlns:tools="http://schemas.android.com/tools">
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<application
android:name=".Application"
android:label="APP_NAME"
android:icon="#drawable/home_logo"
tools:replace="android:label">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="#style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="#style/NormalTheme"
/>
<!-- Displays an Android View that continues showing the launch screen
Drawable until Flutter paints its first frame, then this splash
screen fades out. A splash screen is useful to avoid any visual
gap between the end of Android's launch screen and the painting of
Flutter's first frame. -->
<meta-data
android:name="io.flutter.embedding.android.SplashScreenDrawable"
android:resource="#drawable/launch_background"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<!-- Add below to ensure we get the payload when tapping on a notification -->
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id"/>
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
main.dart
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
print('on message $message');
showNotification(message);
},
onBackgroundMessage: Platform.isIOS
? null
: myBackgroundMessageHandler,
onResume: (Map<String, dynamic> message) async {
print('on resume $message');
showNotification(message);
},
onLaunch: (Map<String, dynamic> message) async {
print('on launch $message');
showNotification(message);
},
);
myBackgroundMessageHandler method in same main.dart
static Future<dynamic> myBackgroundMessageHandler(Map<String, dynamic> message) {
final notification = message['notification'];
final data = message['data'];
print(notification);
}
Firebase send notification json Rest API
#header:
Content-Type:application/json
Authorization:key=YOUR FIREBASE SERVER KEY
#body -> raw
{
"notification":{
"title":"Plan Expired",
"body":"Your plan has expired please upgrade your plan today"
},
"data": {
"image":"https://i.ytimg.com/vi/zZ72Ujn8Rfw/maxresdefault.jpg"
},
"to":"NOTIFICATION TOKEN"
}
To show images you may need to use image tag inside notification in your Firebase send notification json Rest API. The below code worked for me.
{
"notification":{
"title":"Plan Expired",
"body":"Your plan has expired please upgrade your plan today",
"image":"https://imgsv.imaging.nikon.com/lineup/dslr/df/img/sample/img_01.jpg"
}
"to":"NOTIFICATION_TOKEN"
}
Related
i have this issue when i tried to run my app in a physical device in debug mode.
When I try to debug the next code:
class SocketService with ChangeNotifier {
ServerStatus _serverStatus = ServerStatus.Connecting;
SocketService() {
this._initConfig();
}
void _initConfig() async {
IO.Socket socket = IO.io('http://192.168.56.1:3000/', <String, dynamic>{
'transports': ['websocket'],
'autoConnect': true,
});
socket.on('connect', (_) {
print('connect');
});
socket.on('event', (data) => print(data));
socket.on('disconnect', (_) => print('disconnect'));
socket.on('fromServer', (_) => print(_));
}
}
And in my backend i have this:
file index.js
const express = require('express');
const path = require('path');
require('dotenv').config();
const app = express();
const server = require('http').createServer(app);
module.exports.io = require('socket.io')(server);
require('./sockets/socket');
const publicPath = path.resolve( __dirname, 'public' );
app.use( express.static( publicPath ) );
server.listen( process.env.PORT, ( err ) => {
if ( err ) throw new Error(err);
console.log('Servidor corriendo en puerto', process.env.PORT );
});
file socket.js
const { io } = require('../index');
io.on('connection', client => {
console.log('Cliente conectado');
client.on('disconnect', () => {
console.log('Cliente desconectado');
});
client.on('mensaje', ( payload ) => {
console.log('Mensaje', payload);
io.emit( 'mensaje', { admin: 'Nuevo mensaje' } );
});
});
In web works good and print's the 'disconnect' adn the 'connect' perfectly, but when i tried to debug in my cellphone, nothings happends, i don't get any message from the socket instance, if anyone knows how to solved this I would appreciate.
You can upload your code into the Heroku server or you can make a ngrok URL to connect the socket with a physical device.
I figure out what was the problem, was with the AndroidManifest
The way I solved was with the next code
In the <application> I add this line android:usesCleartextTraffic="true"
The result was this:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.band_names">
<uses-permission android:name="android.permission.INTERNET"/>
<application
android:label="band_names"
android:icon="#mipmap/ic_launcher"
android:usesCleartextTraffic="true">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="#style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:windowSoftInputMode="adjustResize">
<!-- Specifies an Android theme to apply to this Activity as soon as
the Android process has started. This theme is visible to the user
while the Flutter UI initializes. After that, this theme continues
to determine the Window background behind the Flutter UI. -->
<meta-data
android:name="io.flutter.embedding.android.NormalTheme"
android:resource="#style/NormalTheme"
/>
<!-- Displays an Android View that continues showing the launch screen
Drawable until Flutter paints its first frame, then this splash
screen fades out. A splash screen is useful to avoid any visual
gap between the end of Android's launch screen and the painting of
Flutter's first frame. -->
<meta-data
android:name="io.flutter.embedding.android.SplashScreenDrawable"
android:resource="#drawable/launch_background"
/>
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
<!-- Don't delete the meta-data below.
This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
<meta-data
android:name="flutterEmbedding"
android:value="2" />
</application>
</manifest>
I am using firebase_messaging: ^5.0.1 package to achieve push notifications, everything is working fine in IOS whereas coming to the android when my mobile application running background I am receiving a notification but it is not navigating to the respective screens, it just opens the default screen. How to achieve navigation to that particular screen.
PS: I implemented click_action functionality that's the reason it's working fine in iOS but Android it shows the below message
W/FirebaseMessaging( 8260): Missing Default Notification Channel metadata in AndroidManifest. Default value will be used.
Here is my AndroidManifest:
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.check">
<!-- io.flutter.app.FlutterApplication is an android.app.Application that
calls FlutterMain.startInitialization(this); in its onCreate method.
In most cases you can leave this as-is, but you if you want to provide
additional functionality it is fine to subclass or reimplement
FlutterApplication and put your custom class here. -->
<application
android:name="io.flutter.app.FlutterApplication"
android:label="Cargill FC"
android:icon="#mipmap/ic_launcher">
<activity
android:name=".MainActivity"
android:launchMode="singleTop"
android:theme="#style/LaunchTheme"
android:configChanges="orientation|keyboardHidden|keyboard|screenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
android:hardwareAccelerated="true"
android:allowBackup="false"
android:fullBackupContent="false"
android:windowSoftInputMode="adjustResize">
<!-- This keeps the window background of the activity showing
until Flutter renders its first frame. It can be removed if
there is no splash screen (such as the default splash screen
defined in #style/LaunchTheme). -->
<meta-data
android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
android:value="true" />
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<action android:name="FLUTTER_NOTIFICATION_CLICK" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
</application>
</manifest>
Push notificatio code:
#override
void initState() {
super.initState();
tabController = new TabController(length: 2, vsync: this);
_firebaseMessaging.configure(
onMessage: (Map<String, dynamic> message) async {
onFirebaseMessage(message);
},
onLaunch: (Map<String, dynamic> message) async {
print("onLaunch: $message");
},
onResume: (Map<String, dynamic> message) async {
print("onResume: $message");
},
);
_firebaseMessaging.requestNotificationPermissions(const IosNotificationSettings(sound: true, badge: true, alert: true));
_firebaseMessaging.onIosSettingsRegistered.listen((IosNotificationSettings settings) {
print("Settings registered: $settings");
});
_firebaseMessaging.getToken().then(registerFirebaseTokenForUser);
}
Here onMessage is the only thing working perfectly in Android. I want to achieve the same when it is running background.
For those who are not able to find "string.xml", you can find it under: android>app>src>main>res>values. It is not the same as styles.xml. If you do not have one yet, you can create one:
Right click "values" folder,
Click New/Values Resource File
Copy, and paste the following text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="default_notification_channel_id" translatable="false">fcm_default_channel</string>
</resources>
Maksim has a pretty solid answer here including links to the official docs. You need to add a the following meta-data tag in you Manifest:
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id"/>
And in string.xml you can declare default_notification_channel_id in the following way:
<string name=“default_notification_channel_id”>Channel ID</string>
Then you must provide an attribute with that specific id when sending push notifications.
EDIT
It is possible to have multiple meta-data tags in your AndroidManifest.xml:
<meta-data
android:name="io.flutter.app.android.SplashScreenUntilFirstFrame"
android:value="true" />
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/default_notification_channel_id"/>
Adding FLUTTER_NOTIFICATION_CLICK is required to be sent, for onResume and onLunch to be executed.
{
"notification": {...},
"click_action": "FLUTTER_NOTIFICATION_CLICK"
}
For my golang server, this meant adding the AndroidConfig
message := &messaging.Message{
Topic: topic,
Notification: &messaging.Notification{/* */}
Data: data,
APNS: &messaging.APNSConfig{/* */}
Android: &messaging.AndroidConfig{
Notification: &messaging.AndroidNotification{
ClickAction: "FLUTTER_NOTIFICATION_CLICK",
},
},
}
1- At first, add this meta code after </activity> tag in AndroidManifest.xml which located in path <flutter project path>/android/app/src/main/AndroidManifest.xml
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="#string/notification_channel_id" />
Note: If you set this meta inside <activity> the code will not work.
2- Modify file (or create new file if not exists) in this path <flutter project path>/android/app/src/main/res/values/string.xml to be like this:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<string name="default_notification_channel_id" translatable="false">fcm_default_channel</string>
</resources>
This will solve the problem Missing Default Notification Channel metadata in AndroidManifest. Default value will be used.
But after that, you need to create this channel in Android, to do that go to file <flutter project path>//android/app/src/main/kotlin/com/examble/project_name/Application.kt and add this function:
private fun createChannel(){
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
// Create the NotificationChannel
val name = getString(R.string.default_notification_channel_id)
val channel = NotificationChannel(name, "default", NotificationManager.IMPORTANCE_HIGH)
val notificationManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notificationManager.createNotificationChannel(channel)
}
}
Then call it from onCreate() function:
override fun onCreate() {
super.onCreate()
createChannel()
.........
}
Adding 'click_action': 'FLUTTER_NOTIFICATION_CLICK' to my notification's data solved this for me
If your flutter version is greater than 1.12 you don't need to create any file like Application.java or Application.kt just add the below meta value to you AndroidManifest file
<meta-data
android:name="com.google.firebase.messaging.default_notification_channel_id"
android:value="high_importance_channel" />
Reference: https://firebase.flutter.dev/docs/messaging/overview/
I am following this documentation for receiving push notification on react native android https://github.com/evollu/react-native-fcm, I am able to receive the device token id, but I am not able to receive any notification when I am using sending manually from firebase using that device id:
This is the code on my react native app:
import {Platform} from 'react-native';
import FCM, {FCMEvent, RemoteNotificationResult, WillPresentNotificationResult, NotificationType} from 'react-native-fcm';
// this shall be called regardless of app state: running, background or not running. Won't be called when app is killed by user in iOS
FCM.on(FCMEvent.Notification, async (notif) => {
// there are two parts of notif. notif.notification contains the notification payload, notif.data contains data payload
if(notif.local_notification){
//this is a local notification
}
if(notif.opened_from_tray){
//iOS: app is open/resumed because user clicked banner
//Android: app is open/resumed because user clicked banner or tapped app icon
}
// await someAsyncCall();
if(Platform.OS ==='ios'){
//optional
//iOS requires developers to call completionHandler to end notification process. If you do not call it your background remote notifications could be throttled, to read more about it see https://developer.apple.com/documentation/uikit/uiapplicationdelegate/1623013-application.
//This library handles it for you automatically with default behavior (for remote notification, finish with NoData; for WillPresent, finish depend on "show_in_foreground"). However if you want to return different result, follow the following code to override
//notif._notificationType is available for iOS platfrom
switch(notif._notificationType){
case NotificationType.Remote:
notif.finish(RemoteNotificationResult.NewData) //other types available: RemoteNotificationResult.NewData, RemoteNotificationResult.ResultFailed
break;
case NotificationType.NotificationResponse:
notif.finish();
break;
case NotificationType.WillPresent:
notif.finish(WillPresentNotificationResult.All) //other types available: WillPresentNotificationResult.None
break;
}
}
});
FCM.on(FCMEvent.RefreshToken, (token) => {
console.log(token)
// fcm token may not be available on first load, catch it here
});
class App extends Component {
componentDidMount() {
// iOS: show permission prompt for the first call. later just check permission in user settings
// Android: check permission in user settings
FCM.requestPermissions().then(()=>console.log('granted')).catch(()=>console.log('notification permission rejected'));
FCM.getFCMToken().then(token => {
console.log(token)
// store fcm token in your server
});
this.notificationListener = FCM.on(FCMEvent.Notification, async (notif) => {
// optional, do some component related stuff
});
// initial notification contains the notification that launchs the app. If user launchs app by clicking banner, the banner notification info will be here rather than through FCM.on event
// sometimes Android kills activity when app goes to background, and when resume it broadcasts notification before JS is run. You can use FCM.getInitialNotification() to capture those missed events.
// initial notification will be triggered all the time even when open app by icon so send some action identifier when you send notification
FCM.getInitialNotification().then(notif => {
console.log(notif)
});
}
componentWillUnmount() {
// stop listening for events
this.notificationListener.remove();
}
Android Manifest file looks as below:
<?xml version="1.0" encoding="utf-8"?>
<manifest package="fi.rogerstudio.possis"
xmlns:android="http://schemas.android.com/apk/res/android">
<uses-permission android:name="com.google.android.gms.permission.ACTIVITY_RECOGNITION"/>
<uses-permission android:name="com.example.healthgps.permission.MAPS_RECEIVE" />
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<uses-permission android:name="android.permission.VIBRATE" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-feature android:name="android.hardware.location.gps" />
<application
android:name=".MainApplication"
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:supportsRtl="true">
<activity android:name=".MainActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:theme="#style/Theme.Exponent.Light"
android:windowSoftInputMode="adjustResize"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
<intent-filter>
<data android:scheme="exp6a747c4f7f604b89a93d9f3d281cbb77"/>
<action android:name="android.intent.action.VIEW"/>
<category android:name="android.intent.category.DEFAULT"/>
<category android:name="android.intent.category.BROWSABLE"/>
</intent-filter>
</activity>
<service
android:name="io.invertase.firebase.messaging.MessagingService"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT" />
</intent-filter>
</service>
<service android:name="io.invertase.firebase.messaging.InstanceIdService" android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<service android:name="com.evollu.react.fcm.MessagingService" android:enabled="true" android:exported="true">
<intent-filter>
<action android:name="com.google.firebase.MESSAGING_EVENT"/>
</intent-filter>
</service>
<service android:name="com.evollu.react.fcm.InstanceIdService" android:exported="false">
<intent-filter>
<action android:name="com.google.firebase.INSTANCE_ID_EVENT"/>
</intent-filter>
</service>
<!-- The Facebook SDK runs FacebookInitProvider on startup and crashes if there isn't an ID here -->
<meta-data android:name="com.facebook.sdk.ApplicationId" android:value="fb0"/>
<!-- react-native-background-geolocation licence -->
<meta-data android:name="com.transistorsoft.locationmanager.license" android:value="14ef777231a8412c8b2d109443999356a2c13e62c07e2868345f5e13f01b3c83" />
<meta-data android:name="com.google.firebase.messaging.default_notification_icon" android:resource="#mipmap/ic_launcher"/>
<receiver android:name="com.evollu.react.fcm.FIRLocalMessagingPublisher"/>
<receiver android:enabled="true" android:exported="true" android:name="com.evollu.react.fcm.FIRSystemBootEventReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.QUICKBOOT_POWERON"/>
<action android:name="com.htc.intent.action.QUICKBOOT_POWERON"/>
<category android:name="android.intent.category.DEFAULT" />
</intent-filter>
</receiver>
</application>
</manifest>
I see your current problem is about your installed package. You made some conflict package install.
Please remove io.invertase.firebase.messaging from your app.
npm uninstall react-native-firebase --save
Then you also need to remove from your settings.gradle
I am making an App that allows user to login with Instagram. Now the login procedure that I've understood is as follows:
Register the App at Instagram Developer as a client to acquire client_id etc.
Call the Instagram URL along with your client_id with get the grant_code
Send the grant_code back to Instagram (I'm going to do this from back-end) to get the access token.
This StackOverFlow Question has the same problem I do. I understand from the answer that I need deep linking so that I can provide it as a redirect_uri to Instagram so that It redirects back to my app after login.
Now I can't get the Deep Linking to work. Below is the component where the app is listening for the URL.
Top Most Component in The App
import React, { Component } from 'react';
import { Linking } from 'react-native';
import Router from './Router';
class App extends Component {
componentDidMount() {
Linking.getInitialURL().then(url => {
if (url) {
console.log(`Initial url is ${url}`);
}
})
.catch(err => {
console.error(err);
});
Linking.addEventListener('url', this.handleOpenURL);
}
componentWillUnmount() {
Linking.removeEventListener('url', this.handleOpenURL);
}
handleOpenURL(event) {
console.log(event.url);
}
render() {
return <Router />;
}
}
export default App;
Android Manifest.xml
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.numu"
android:versionCode="1"
android:versionName="1.0">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
<uses-sdk
android:minSdkVersion="16"
android:targetSdkVersion="22" />
<application
android:name=".MainApplication"
android:allowBackup="true"
android:label="#string/app_name"
android:icon="#mipmap/ic_launcher"
android:theme="#style/AppTheme">
<activity
android:name=".MainActivity"
android:label="#string/app_name"
android:configChanges="keyboard|keyboardHidden|orientation|screenSize"
android:windowSoftInputMode="adjustResize">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
<intent-filter android:label="filter_react_native">
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<!-- Accepts URIs that begin with "http://www.numu.com/app” -->
<data android:scheme="http"
android:host="www.numu.com"
android:pathPrefix="/app" />
<!-- Accepts URIs that begin with "numu://app” -->
<data android:scheme="numu"
android:host="app" />
</intent-filter>
</activity>
<activity android:name="com.facebook.react.devsupport.DevSettingsActivity" />
</application>
This is my Router Component
import { StackNavigator } from 'react-navigation';
import LoginPage from './components/LoginPage';
import IntroText from './components/IntroText';
const RouterComponent = StackNavigator({
LoginPage: { screen: LoginPage, path: 'login' },
IntroText: { screen: IntroText, path: 'intro },
});
export default RouterComponent;
This is my progress so far. I have been testing by entering http://www.numu.com/app/intro and numu://app/intro into my chrome browser (mobile), but the app doesn'r open.
I would also appreciate if anyone could tell me an alternative to this method. I have tried a package for this purpose. It also requires that I give a redirect_uri
Thanks
I'm developing a NativeScript app which involves push notifications.Whenever push notification came I need to store notification contents into database.
For that I have written some code in "onMessageReceived" function.This code is in the page in which GCM registration code is there.
If app is running then every thing working fine. The problem is if app is closed then "onMessageReceived" function is not even executing(I checked with console logs).
So for that I'm trying to place "onMessageReceived" function in app.js so that even app is closed it will execute.For that I'm trying to import the "nativescript-push-notifications" in app.js, but getting error saying "application is null,it's not passed correctly".Below is my app.js code.
app.js
var application = require("application");
var gcm=require("nativescript-push-notifications");
if(gcm.onMessageReceived) {
gcm.onMessageReceived(function callback(data) {
console.log("message received:::: ", "" + JSON.stringify(data));
storeInDatabase(data);// some function to store notification content into db.
});
}
application.mainModule="main-page";
application.start({ moduleName: "main-page" });
Can we import "nativescript-push-notifications" reference in app.js??
Any suggestions will be helpful.Thanks.
Application is null because your app has not started yet try adding the plugin in the application launch event
var application = require("application");
application.start({ moduleName: "main-page" });
application.on(application.launchEvent, function (args) {
if (args.android) {
var gcm = require("nativescript-push-notifications");
gcm.register({ senderID: 'conversate-1148' }, function (data) {
self.set("message", "" + JSON.stringify(data));
}, function () { });
if (gcm.onMessageReceived) {
gcm.onMessageReceived(function callback(data) {
console.log("message received:::: ", "" + JSON.stringify(data));
storeInDatabase(data);// some function to store notification content into db.
});
}
} else if (args.ios !== undefined) {
//Do ios stuff here
}
});
In addition to Osei's code you might want to check out your AndroidManifest.xml file (generated in your platforms/android folder) and make sure the following permissions are set :
<uses-permission android:name="android.permission.GET_ACCOUNTS" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="com.google.android.c2dm.permission.RECEIVE" />
and also that the plugin is registered as a service in the same AndroidManifest.xml file as follows:
<activity android:name="com.telerik.pushplugin.PushHandlerActivity"/>
<receiver android:name="com.google.android.gms.gcm.GcmReceiver" android:exported="true" android:permission="com.google.android.c2dm.permission.SEND" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
<category android:name="com.pushApp.gcm" />
</intent-filter>
</receiver>
<service android:name="com.telerik.pushplugin.PushPlugin" android:exported="false" >
<intent-filter>
<action android:name="com.google.android.c2dm.intent.RECEIVE" />
</intent-filter>
</service>