Android自定义Notification添加点击事件

Android自定义Notification添加点击事件,第1张

概述前言在上一篇文章中《Notification自定义界面》中我们实现了自定义的界面,那么我们该怎么为自定义的界面添加点击事件呢?像酷狗在通知栏有“上一首”,“下一首”等控制按钮,我们需要对按钮的点击事件进行响应,不

前言

在上一篇文章中《Notification自定义界面》中我们实现了自定义的界面,那么我们该怎么为自定义的界面添加点击事件呢?像酷狗在通知栏 有“上一首”,“下一首”等控制按钮,我们需要对按钮的点击事件进行响应,不过方法和之前的点击设置不一样,需要另外处理,下面我将进行简单的说明。

实现

同样,我们需要一个Service的子类MyService,然后在MyService的onCreate中设置,如下代码:

public class MyService extends Service { public static final String ONCliCK = "com.app.onclick"; private broadcastReceiver receiver_onclick = new broadcastReceiver() {  @OverrIDe  public voID onReceive(Context context,Intent intent) {   if (intent.getAction().equals(ONCliCK)) {    Vibrator vibrator = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);    vibrator.vibrate(1000);   }  } }; @OverrIDe public voID onCreate() {  super.onCreate();  Notification notification = new Notification(R.drawable.ic_launcher,"JcMan",System.currentTimeMillis());  RemoteVIEws vIEw = new RemoteVIEws(getPackagename(),R.layout.notification);  notification.contentVIEw = vIEw;  IntentFilter filter_click = new IntentFilter();  filter_click.addAction(ONCliCK);  //注册广播  registerReceiver(receiver_onclick,filter_click);  Intent Intent_pre = new Intent(ONCliCK);  //得到PendingIntent  PendingIntent pendIntent_click = PendingIntent.getbroadcast(this,Intent_pre,0);  //设置监听  notification.contentVIEw.setonClickPendingIntent(R.ID.btn,pendIntent_click);  //前台运行  startForeground(1,notification); } @OverrIDe public IBinder onBind(Intent intent) {  return null; }}

可以看到,我们先得到broadcastReceiver的一个对象,然后在onReceiver里面实现我们的 *** 作,我设置成点击时候手机震动一秒钟,当然不要忘记在配置文件添加震动的权限,不然到时候就会出错了。如果对广播没有了解的,那么可以先去了解一下广播的机制,这里我使用的是动态注册广播的方法,还有另外一种方法来注册,不过我更喜欢动态注册的罢了。

小结

看到在Notification添加一个Progressbar来实现下载的进度提示,这里需要用到更新Notification界面的知识,虽然和在Activity中更新界面不太一样,但是也不是在复杂,因为我并没有用到这方面的知识,所以这里就不给大家介绍了,有兴趣的可以搜相关的内容。

总结

以上是内存溢出为你收集整理的Android自定义Notification添加点击事件全部内容,希望文章能够帮你解决Android自定义Notification添加点击事件所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1143538.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-31
下一篇 2022-05-31

发表评论

登录后才能评论

评论列表(0条)

保存