如何使用Kotlin从Android中的IntentService发送通知
我是新的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") } }}
我也检查过,当设备通过放置调试点进入或离开地理围栏时,我的服务被调用。 没有对象获得空值,一切正常,但通知不会收到。 我能怎么做??
您需要在通知中添加图标,否则您的通知将被触发,但不会显示在状态栏上。
但为什么? 因为它是android操作系统的最低要求之一,在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
来设置背景颜色,但你必须把一个支票调用setColor
为Android操作系统
Notification bar icon turns white in Android 5 Lollipop