首页 > 解决方案 > 应用程序关闭时如何获取上下文?

问题描述

在firebase消息传递系统中,该onMessageReceived()方法在应用程序关闭并获得推送通知时运行。所以我想在onMessageReceived()方法中使用 SQLite。SQLite 必须需要上下文,但由于应用程序已关闭,我无法在方法中获取 ApplicationContext。应用程序关闭时如何获取应用程序上下文?

@Override
    public void onMessageReceived(RemoteMessage remoteMessage) {
        DatabaseHelper database = new DatabaseHelper(FirebaseMessagingService.this);
        database.updateTicket(Integer.parseInt(remoteMessage.getData().get("idx")));

        try{
            Badges.setBadge(this, 1);
        }catch(BadgesNotSupportedException e){
            e.printStackTrace();
        }

        Intent intent = new Intent(this, MainActivity.class);
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        String channelId = "Default";

        NotificationCompat.Builder builder = new  NotificationCompat.Builder(this, channelId)
                .setSmallIcon(R.mipmap.ic_launcher)
                .setContentTitle(remoteMessage.getNotification().getTitle())
                .setContentText(remoteMessage.getNotification().getBody()).setAutoCancel(true).setContentIntent(pendingIntent);;
        NotificationManager manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            NotificationChannel channel = new NotificationChannel(channelId, "Default channel", NotificationManager.IMPORTANCE_DEFAULT);
            manager.createNotificationChannel(channel);
        }
        manager.notify(0, builder.build());

        //sendPushNotification(remoteMessage.getData().get("title"), remoteMessage.getData().get("body"));
    }

这是我的 onMessageReceived 代码。问题是前两行不起作用的数据库代码。我已经检查过它适用于应用程序或应用程序在后台运行。

标签: android

解决方案


服务有自己的上下文并作为FirebaseMessagingService 扩展服务 ,因此您可以使用thisYourServiceClassName.this


推荐阅读