如何从Odoo服务器向Android设备推送自定义通知并建立通信隧道
Hey there! I’ve built a similar Odoo-to-Android push notification setup before, so let me walk you through the core steps and key details to get this working smoothly:
Instead of building a direct peer-to-peer tunnel (which is unreliable for mobile devices due to network restrictions), the standard reliable approach uses Firebase Cloud Messaging (FCM) as the middleman. Here’s the flow:
- Android app registers with FCM to get a unique device token
- The app sends this token to your Odoo server, where it’s linked to a specific user/record
- When a targeted event happens in Odoo (e.g., new order, task assignment), your Odoo code calls FCM’s API to send a push notification to the associated device token
- FCM routes the notification to the target Android device
You’ll need a custom Odoo module to handle token storage and push logic:
Step 2.1: Store FCM Device Tokens
Extend the res.users model (or create a new one) to save device tokens:
from odoo import models, fields class ResUsers(models.Model): _inherit = 'res.users' fcm_device_token = fields.Char(string='FCM Device Token', help="Unique token for Android device push notifications")
Step 2.2: Implement Push Notification Logic
Use Python’s requests library to call FCM’s v1 API (legacy HTTP works too, but v1 is recommended). You’ll need your Firebase project’s service account credentials for authentication:
import requests import json from odoo import models, api class PushNotification(models.Model): _name = 'push.notification' @api.model def send_notification(self, user_id, title, body, custom_data=None): user = self.env['res.users'].browse(user_id) if not user.fcm_device_token: return False # Replace with your Firebase project ID url = "https://fcm.googleapis.com/v1/projects/YOUR_FIREBASE_PROJECT_ID/messages:send" # Auth token generated via Firebase Admin SDK or JWT signing (store securely!) headers = { "Authorization": "Bearer YOUR_FCM_AUTH_TOKEN", "Content-Type": "application/json" } payload = { "message": { "token": user.fcm_device_token, "notification": { "title": title, "body": body }, "data": custom_data or {} } } response = requests.post(url, headers=headers, data=json.dumps(payload)) return response.status_code == 200
Pro tip: Never hardcode credentials—store them in Odoo’s config file or use a secure secrets manager.
Step 2.3: Trigger Notifications on Events
Call the send_notification method whenever your target event occurs. For example, when a new sale order is assigned:
from odoo import models, api class SaleOrder(models.Model): _inherit = 'sale.order' @api.model_create_multi def create(self, vals_list): orders = super().create(vals_list) for order in orders: # Send notification to the assigned salesperson self.env['push.notification'].send_notification( user_id=order.user_id.id, title="New Order Assigned", body=f"Order {order.name} is waiting for your review", custom_data={"order_id": str(order.id), "type": "order_assignment"} ) return orders
On the Android app, integrate FCM to receive and customize notifications:
Step 3.1: Add FCM Dependencies
Add these to your app-level build.gradle:
dependencies { implementation 'com.google.firebase:firebase-messaging:23.4.0' }
Step 3.2: Retrieve & Sync Device Token to Odoo
Implement a FirebaseMessagingService to get the token and send it to your Odoo server:
class MyFirebaseMessagingService : FirebaseMessagingService() { override fun onNewToken(token: String) { super.onNewToken(token) // Send token to Odoo via your custom API endpoint (use Retrofit/OkHttp) syncTokenWithOdoo(token) } private fun syncTokenWithOdoo(token: String) { // Example: Use Retrofit to call Odoo's JSON-RPC or a custom REST endpoint // Pass the current user's credentials to link the token correctly } }
Step 3.3: Handle Incoming Notifications
Customize how notifications are displayed and handled in onMessageReceived:
override fun onMessageReceived(remoteMessage: RemoteMessage) { super.onMessageReceived(remoteMessage) val title = remoteMessage.notification?.title ?: "Odoo Alert" val body = remoteMessage.notification?.body ?: "You have a new update" val customData = remoteMessage.data // Build custom notification val notificationBuilder = NotificationCompat.Builder(this, "ODOO_PUSH_CHANNEL") .setSmallIcon(R.drawable.ic_odoo_notification) .setContentTitle(title) .setContentText(body) .setPriority(NotificationCompat.PRIORITY_HIGH) .setAutoCancel(true) // Add intent to open specific app screen if custom data exists customData["order_id"]?.let { orderId -> val intent = Intent(this, OrderDetailActivity::class.java).apply { putExtra("ORDER_ID", orderId) } val pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_IMMUTABLE) notificationBuilder.setContentIntent(pendingIntent) } val notificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager notificationManager.notify(System.currentTimeMillis().toInt(), notificationBuilder.build()) }
- Token Sync: Android can refresh tokens periodically—make sure your app resends the updated token to Odoo whenever
onNewTokenis called - Permissions: For Android 13+, request the
POST_NOTIFICATIONSpermission to show notifications - Odoo Security: Use authenticated endpoints when syncing tokens (e.g., Odoo’s JSON-RPC with user credentials)
- Testing: Use Firebase Console’s Cloud Messaging tab to test notifications before integrating with Odoo
内容的提问来源于stack exchange,提问作者Caludio

