android - 应用程序关闭时如何获取上下文?
问题描述
在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 代码。问题是前两行不起作用的数据库代码。我已经检查过它适用于应用程序或应用程序在后台运行。
解决方案
服务有自己的上下文并作为FirebaseMessagingService
扩展服务
,因此您可以使用this
或YourServiceClassName.this
推荐阅读
- android - Admob 和 GooglePlayGames 无法协同工作
- python - 使用 django-rest-framework 的密码哈希?
- android - Android:从下拉菜单中选择歌曲并使用 MediaPlayer 播放歌曲
- javascript - Array Override itself in Node. And giving me different output
- c++ - 当我选择大于 720 的矩阵大小时,程序以错误代码退出。可能是什么原因?
- android - Android 房间数据库数据没有被插入?
- python - How to change content_subtype to html in django email_user
- django - 方法不允许在 django 中发布
- powershell - 使用 Powershell 计算 DataGridView 中的可见行数
- reactjs - 将样式化组件样式应用于第三方组件