我是Android开发的新手,我想在设备输入用户设置的任何特定地理围栏时从IntentService发送通知。我写了下面的代码来发送通知。
class GeofenceIntentService : IntentService("GeofenceIntentService") {
var notId: Int = 15452
override fun onHandleIntent(intent: Intent?) {
var geofencingEvent = GeofencingEvent.fromIntent(intent)
if(geofencingEvent.hasError())
{
Log.e("JK-->>","geofencingError -->> "+geofencingEvent.hasError())
return
}
var geofenceTransition = geofencingEvent.geofenceTransition
if (geofenceTransition == Geofence.GEOFENCE_TRANSITION_ENTER)
{
var pendingIntent = PendingIntent.getService(applicationContext,0,Intent(applicationContext,MainActivity::class.java),PendingIntent.FLAG_UPDATE_CURRENT)
var notification = NotificationCompat.Builder(applicationContext).setAutoCancel(true).setContentTitle("Entered In Geofence!").setContentText("Click here for return to app!!").setContentIntent(pendingIntent).build()
var notiManager: NotificationManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
notId = notId + 1
notiManager.notify(notId,notification)
Log.e("JK-->>", "Entered in geofence")
}
else if(geofenceTransition == Geofence.GEOFENCE_TRANSITION_EXIT)
{
var notiBuilder = NotificationCompat.Builder(this).setAutoCancel(true).setContentTitle("Entered In Geofence").setContentText("Click Here for return to app!").build()
var notiManager = getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
var intent = Intent(this,MainActivity::class.java)
var pendingIntent = PendingIntent.getActivity(this,0,intent,PendingIntent.FLAG_UPDATE_CURRENT)
notiBuilder.contentIntent = pendingIntent
notId = notId + 1
notiManager.notify(notId,notiBuilder)
Log.e("JK-->>", "Entered in geofence")
Log.e("JK-->>", "Exit from geofence")
}
}}
我还检查了当设备通过调试点进入或退出地理围栏时调用我的服务。 No Object获取null值,一切正常,但通知未收到。 我该怎么办?
答案 0 :(得分:2)
您需要在通知中添加图标,否则您的通知将被触发,但不会显示在状态栏上。
但为什么呢?因为它是Android OS在Required notification contents
通知对象必须包含以下内容:
A small icon, set by setSmallIcon()
。标题,由setContentTitle()设置。
详细文本,由setContentText()设置。
在Android 8.0(API级别26)及更高版本上,一个有效的通知通道ID,由setChannelId()设置或在创建通道时在NotificationCompat.Builder构造函数中提供。
var notification = NotificationCompat.Builder(applicationContext)
.setAutoCancel(true)
.setContentTitle("Entered In Geofence!")
.setContentText("Click here for return to app!!")
.setSmallIcon(R.drawable.notificationDrawableResource)
// add ^^^^^^^
.setContentIntent(pendingIntent).build()
注意:根据棒棒糖标准,您的通知图标应该是透明的,您可以使用setColor
设置背景颜色,但您必须根据Android操作系统检查setColor