Android 中Notification弹出通知实现代码

NotificationManager 是状态栏通知的管理类,负责发通知、清除通知等操作。

NotificationManager 是一个系统Service,可通过getSystemService(NOTIFICATION_SERVICE)方法来获取

接下来我想说的是android5.0 后的弹出通知,

网上的方法是:          

 //第一步:实例化通知栏构造器Notification.Builder:
           Notification.Builder builder =new Notification.Builder(MainActivity.this);//实例化通知栏构造器Notification.Builder,参数必填(Context类型),为创建实例的上下文
        //第二步:获取状态通知栏管理:
        NotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);//获取状态栏通知的管理类(负责发通知、清除通知等操作)
        //第三步:设置通知栏PendingIntent(点击动作事件等都包含在这里):
        Intent push =new Intent(MainActivity.this,MainActivity.class);//新建一个显式意图,第一个参数 Context 的解释是用于获得 package name,以便找到第二个参数 Class 的位置
        //PendingIntent可以看做是对Intent的包装,通过名称可以看出PendingIntent用于处理即将发生的意图,而Intent用来用来处理马上发生的意图
        //本程序用来响应点击通知的打开应用,第二个参数非常重要,点击notification 进入到activity, 使用到pendingIntent类方法,PengdingIntent.getActivity()的第二个参数,即请求参数,实际上是通过该参数来区别不同的Intent的,如果id相同,就会覆盖掉之前的Intent了
        PendingIntent contentIntent = PendingIntent.getActivity(MainActivity.this,0,push,0);
        //第四步:对Builder进行配置:
        builder
        .setContentTitle("My notification")//标题
        .setContentText("Hello World!")// 详细内容
        .setContentIntent(contentIntent)//设置点击意图
        .setTicker("New message")//第一次推送,角标旁边显示的内容
        .setLargeIcon(BitmapFactory.decodeResource(getResources(),R.drawable.ic_launcher))//设置大图标
        .setDefaults(Notification.DEFAULT_ALL);//打开呼吸灯,声音,震动,触发系统默认行为
        /*Notification.DEFAULT_VIBRATE  //添加默认震动提醒 需要VIBRATE permission
        Notification.DEFAULT_SOUND  //添加默认声音提醒
        Notification.DEFAULT_LIGHTS//添加默认三色灯提醒
        Notification.DEFAULT_ALL//添加默认以上3种全部提醒*/
        //.setLights(Color.YELLOW, 300, 0)//单独设置呼吸灯,一般三种颜色:红,绿,蓝,经测试,小米支持黄色
        //.setSound(url)//单独设置声音
        //.setVibrate(new long[] { 100, 250, 100, 250, 100, 250 })//单独设置震动
        //比较手机sdk版本与Android 5.0 Lollipop的sdk
        if(android.os.Build.VERSION.SDK_INT>= android.os.Build.VERSION_CODES.LOLLIPOP) {
        builder
        /*android5.0加入了一种新的模式Notification的显示等级,共有三种:
        VISIBILITY_PUBLIC只有在没有锁屏时会显示通知
        VISIBILITY_PRIVATE任何情况都会显示通知
        VISIBILITY_SECRET在安全锁和没有锁屏的情况下显示通知*/
        .setVisibility(Notification.VISIBILITY_PUBLIC)
        .setPriority(Notification.PRIORITY_DEFAULT)//设置该通知优先级
        .setCategory(Notification.CATEGORY_MESSAGE)//设置通知类别
        //.setColor(context.getResources().getColor(R.color.small_icon_bg_color))//设置smallIcon的背景色
        .setFullScreenIntent(contentIntent, true)//将Notification变为悬挂式Notification
        .setSmallIcon(R.drawable.ic_launcher);//设置小图标
        }
        else{
        builder
        .setSmallIcon(R.drawable.ic_launcher);//设置小图标
        }
        //第五步:发送通知请求:
        Notification notify = builder.build();//得到一个Notification对象
        mNotifyMgr.notify(1,notify);//发送通知请求
      }

 但上面的做法并不能在android5.0以下的设备上使通知弹出,因此下面的做法是自己重写Notification(网上查找的一些资料,来源忘记了,不好意思)

    如果需要使通知自动显示,那么就需要我们在接收到通知后重新定义通知的界面,并使其加载显示在Window界面上,这点需要读者了解Window的加载机制.

 其实简单点来说,就是通过windowManager的仅有的三个方法(加载,更新,删除)来实现的.如果有大神熟悉这方面的知识可以分享分享.

自定义Notification的思路:

  1.继承重写NotificationCompat,Builder来实现类似的Notification

  2.自定义通知界面

  3.自定义NotificationManager,发送显示通知

废话不多说,先上主要代码:

public class HeadsUp  {
  private Context context;
  /**
   * 出现时间 单位是 second
   */
  private long duration= 3;
  /**
   *
   */
  private Notification notification;
  private Builder builder;
  private boolean isSticky=false;
  private boolean activateStatusBar=true;
  private Notification silencerNotification;
  /**
   * 间隔时间
   */
  private int code;
  private CharSequence titleStr;
  private CharSequence msgStr;
  private int icon;
  private View customView;
  private boolean isExpand;
  private HeadsUp(Context context) {
    this.context=context;
  }
  public static class Builder extends NotificationCompat.Builder {
    private HeadsUp headsUp;
    public Builder(Context context) {
      super(context);
      headsUp=new HeadsUp(context);
    }
    public Builder setContentTitle(CharSequence title) {
      headsUp.setTitle(title);
      super.setContentTitle(title);    //状态栏显示内容
      return this;
    }
    public Builder setContentText(CharSequence text) {
      headsUp.setMessage(text);
      super.setContentText(text);
      return this;
    }
    public Builder setSmallIcon(int icon) {
      headsUp.setIcon(icon);
      super.setSmallIcon(icon);
      return this;
    }
    public HeadsUp buildHeadUp(){
      headsUp.setNotification(this.build());
      headsUp.setBuilder(this);
      return headsUp;
    }
    public Builder setSticky(boolean isSticky){
      headsUp.setSticky(isSticky);
      return this;
    }
  }
  public Context getContext() {
    return context;
  }
  public long getDuration() {
    return duration;
  }
  public Notification getNotification() {
    return notification;
  }
  protected void setNotification(Notification notification) {
    this.notification = notification;
  }
  public View getCustomView() {
    return customView;
  }
  public void setCustomView(View customView) {
    this.customView = customView;
  }
  public int getCode() {
    return code;
  }
  protected void setCode(int code) {
    this.code = code;
  }
  protected Builder getBuilder() {
    return builder;
  }
  private void setBuilder(Builder builder) {
    this.builder = builder;
  }
  public boolean isSticky() {
    return isSticky;
  }
  public void setSticky(boolean isSticky) {
    this.isSticky = isSticky;
  }
}
public class HeadsUpManager {
  private WindowManager wmOne;
  private FloatView floatView;
  private Queue<HeadsUp> msgQueue;
  private static HeadsUpManager manager;
  private Context context;
  private boolean isPolling = false;
  private Map<Integer, HeadsUp> map;
  private  NotificationManager notificationManager=null;
  public static HeadsUpManager getInstant(Context c) {
    if (manager == null) {
      manager = new HeadsUpManager(c);
    }
    return manager;
  }
  private HeadsUpManager(Context context) {
    this.context = context;
    map = new HashMap<Integer, HeadsUp>();
    msgQueue = new LinkedList<HeadsUp>();
    wmOne = (WindowManager) context
        .getSystemService(Context.WINDOW_SERVICE);
    notificationManager= (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
  }
  public void notify(HeadsUp headsUp) {
    if (map.containsKey(headsUp.getCode())) {
      msgQueue.remove(map.get(headsUp.getCode()));
    }
    map.put(headsUp.getCode(), headsUp);
    msgQueue.add(headsUp);
    if (!isPolling) {
      poll();
    }
  }
  public synchronized void notify(int code,HeadsUp headsUp) {
    headsUp.setCode(code);
    notify(headsUp);
  }
  public synchronized void cancel(HeadsUp headsUp) {
    cancel(headsUp.getCode());
  }
  private synchronized void poll() {
    if (!msgQueue.isEmpty()) {
      HeadsUp headsUp = msgQueue.poll();
      map.remove(headsUp.getCode());
//      if ( Build.VERSION.SDK_INT < 21 ||  headsUp.getCustomView() != null ){
        isPolling = true;
        show(headsUp);
        System.out.println("自定义notification");
//      }else {
//        //当 系统是 lollipop 以上,并且没有自定义布局以后,调用系统自己的 notification
//        isPolling = false;
//        notificationManager.notify(headsUp.getCode(),headsUp.getBuilder().setSmallIcon(headsUp.getIcon()).build());
//        System.out.println("调用系统notification");
//      }
    } else {
      isPolling = false;
    }
  }
  private void show(HeadsUp headsUp) {
    floatView = new FloatView(context, 20);
    WindowManager.LayoutParams params = FloatView.winParams;
    params.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL
        | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
        |WindowManager.LayoutParams.FLAG_FULLSCREEN
        | WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN;
    params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ERROR;
    params.width = WindowManager.LayoutParams.MATCH_PARENT;
    params.height = WindowManager.LayoutParams.WRAP_CONTENT;
    params.format = -3;
    params.gravity = Gravity.CENTER | Gravity.TOP;
    params.x = floatView.originalLeft;
    params.y = 10;
    params.alpha = 1f;
    wmOne.addView(floatView, params);
    ObjectAnimator a = ObjectAnimator.ofFloat(floatView.rootView, "translationY", -700, 0);
    a.setDuration(600);
    a.start();
    floatView.setNotification(headsUp);
    if(headsUp.getNotification()!=null){
      notificationManager.notify(headsUp.getCode(), headsUp.getNotification());
    }
  }
  public void cancel(){
    if(floatView !=null && floatView.getParent()!=null) {
      floatView.cancel();
    }
  }
  protected void dismiss() {
    if (floatView.getParent()!=null) {
      wmOne.removeView(floatView);
      floatView.postDelayed(new Runnable() {
        @Override
        public void run() {
          poll();
        }
      }, 200);
    }
  }
  protected  void animDismiss(){
    if(floatView !=null && floatView.getParent()!=null){
      ObjectAnimator a = ObjectAnimator.ofFloat(floatView.rootView, "translationY", 0, -700);
      a.setDuration(700);
      a.start();
      a.addListener(new Animator.AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animator) {
        }
        @Override
        public void onAnimationEnd(Animator animator) {
          dismiss();
        }
        @Override
        public void onAnimationCancel(Animator animator) {
        }
        @Override
        public void onAnimationRepeat(Animator animator) {
        }
      });
    }
  }
  protected void animDismiss(HeadsUp headsUp){
      if(floatView.getHeadsUp().getCode()==headsUp.getCode()){
        animDismiss();
      }
  }
  public void cancel(int code) {
    if (map.containsKey(code)) {
      msgQueue.remove(map.get(code));
    }
    if(floatView!=null && floatView.getHeadsUp().getCode()==code){
      animDismiss();
    }
  }
  public void close() {
    cancelAll();
    manager = null;
  }
  public void cancelAll() {
    msgQueue.clear();
    if (floatView!=null && floatView.getParent()!=null) {
      animDismiss();
    }
  }
}
public class FloatView extends LinearLayout {
  private float rawX = 0;
  private float rawY=0;
  private float touchX = 0;
  private float startY = 0;
  public LinearLayout rootView;
  public int originalLeft;
  public int viewWidth;
  private float validWidth;
  private VelocityTracker velocityTracker;
  private int maxVelocity;
  private Distance distance;
  private ScrollOrientationEnum scrollOrientationEnum=ScrollOrientationEnum.NONE;
  public static WindowManager.LayoutParams winParams = new WindowManager.LayoutParams();
  public FloatView(final Context context, int i) {
    super(context);
    LinearLayout view = (LinearLayout) LayoutInflater.from(getContext()).inflate(R.layout.notification_bg, null);
    maxVelocity= ViewConfiguration.get(context).getScaledMaximumFlingVelocity();
    rootView = (LinearLayout) view.findViewById(R.id.rootView);
    addView(view);
    viewWidth = context.getResources().getDisplayMetrics().widthPixels;
    validWidth=viewWidth/2.0f;
    originalLeft = 0;
  }
  public void setCustomView(View view) {
    rootView.addView(view);
  }
  @Override
  protected void onFinishInflate() {
    super.onFinishInflate();
  }
  private HeadsUp headsUp;
  private long cutDown;
  private  Handler mHandle=null;
  private CutDownTime cutDownTime;
  private class CutDownTime extends Thread{
    @Override
    public void run() {
      super.run();
      while (cutDown>0){
        try {
          Thread.sleep(1000);
          cutDown--;
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
      if(cutDown==0) {
        mHandle.sendEmptyMessage(0);
      }
    }
  };
  public HeadsUp getHeadsUp() {
    return headsUp;
  }
private int pointerId;
  public boolean onTouchEvent(MotionEvent event) {
    rawX = event.getRawX();
    rawY=event.getRawY();
    acquireVelocityTracker(event);
    cutDown= headsUp.getDuration();
    switch (event.getAction()) {
      case MotionEvent.ACTION_DOWN:
        touchX = event.getX();
        startY = event.getRawY();
        pointerId=event.getPointerId(0);
        break;
      case MotionEvent.ACTION_MOVE:
        switch (scrollOrientationEnum){
          case NONE:
            if(Math.abs((rawX - touchX))>20) {
              scrollOrientationEnum=ScrollOrientationEnum.HORIZONTAL;
            }else if(startY-rawY>20){
              scrollOrientationEnum=ScrollOrientationEnum.VERTICAL;
            }
            break;
          case HORIZONTAL:
            updatePosition((int) (rawX - touchX));
            break;
          case VERTICAL:
            if(startY-rawY>20) {
              cancel();
            }
            break;
        }
        break;
      case MotionEvent.ACTION_UP:
        velocityTracker.computeCurrentVelocity(1000,maxVelocity);
        int dis= (int) velocityTracker.getYVelocity(pointerId);
        if(scrollOrientationEnum==ScrollOrientationEnum.NONE){
          if(headsUp.getNotification().contentIntent!=null){
            try {
              headsUp.getNotification().contentIntent.send();
              cancel();
            } catch (PendingIntent.CanceledException e) {
              e.printStackTrace();
            }
          }
          break;
        }
        int toX;
        if(preLeft>0){
          toX= (int) (preLeft+Math.abs(dis));
        }else{
          toX= (int) (preLeft-Math.abs(dis));
        }
        if (toX <= -validWidth) {
          float preAlpha=1-Math.abs(preLeft)/validWidth;
          preAlpha=preAlpha>=0?preAlpha:0;
          translationX(preLeft,-(validWidth+10),preAlpha,0);
        } else if (toX <= validWidth) {
          float preAlpha=1-Math.abs(preLeft)/validWidth;
          preAlpha=preAlpha>=0?preAlpha:0;
          translationX(preLeft,0,preAlpha,1);
        }else{
          float preAlpha=1-Math.abs(preLeft)/validWidth;
          preAlpha=preAlpha>=0?preAlpha:0;
          translationX(preLeft, validWidth + 10, preAlpha, 0);
        }
        preLeft = 0;
        scrollOrientationEnum=ScrollOrientationEnum.NONE;
        break;
    }
    return super.onTouchEvent(event);
  }
  /**
   *
   * @param event 向VelocityTracker添加MotionEvent
   *
   * @see android.view.VelocityTracker#obtain()
   * @see android.view.VelocityTracker#addMovement(MotionEvent)
   */
  private void acquireVelocityTracker( MotionEvent event) {
    if(null == velocityTracker) {
      velocityTracker = VelocityTracker.obtain();
    }
    velocityTracker.addMovement(event);
  }
  private int preLeft;
  public void updatePosition(int left) {
      float preAlpha=1-Math.abs(preLeft)/validWidth;
      float leftAlpha=1-Math.abs(left)/validWidth;
      preAlpha = preAlpha>=0 ? preAlpha : 0;
      leftAlpha = leftAlpha>=0 ? leftAlpha : 0;
      translationX(preLeft,left,preAlpha,leftAlpha);
    preLeft = left;
  }
  public void translationX(float fromX,float toX,float formAlpha, final float toAlpha ){
    ObjectAnimator a1=ObjectAnimator.ofFloat(rootView,"alpha",formAlpha,toAlpha);
    ObjectAnimator a2 = ObjectAnimator.ofFloat(rootView, "translationX", fromX, toX);
    AnimatorSet animatorSet=new AnimatorSet();
    animatorSet.playTogether(a1,a2);
    animatorSet.addListener(new Animator.AnimatorListener() {
      @Override
      public void onAnimationStart(Animator animation) {
      }
      @Override
      public void onAnimationEnd(Animator animation) {
        if(toAlpha==0){
          HeadsUpManager.getInstant(getContext()).dismiss();
          cutDown=-1;
          if(velocityTracker!=null) {
            velocityTracker.clear();
            try {
              velocityTracker.recycle();
            } catch (IllegalStateException e) {
            }
          }
        }
      }
      @Override
      public void onAnimationCancel(Animator animation) {
      }
      @Override
      public void onAnimationRepeat(Animator animation) {
      }
    });
    animatorSet.start();
  }
  public void setNotification(final HeadsUp headsUp) {
    this.headsUp = headsUp;
    mHandle= new Handler(){
      @Override
      public void handleMessage(Message msg) {
        super.handleMessage(msg);
        HeadsUpManager.getInstant(getContext()).animDismiss(headsUp);
      }
    };
    cutDownTime= new CutDownTime();
    if(!headsUp.isSticky()){
      cutDownTime.start();
    }
    cutDown= headsUp.getDuration();
    if (headsUp.getCustomView() == null) {
      View defaultView = LayoutInflater.from(getContext()).inflate(R.layout.notification, rootView, false);
      rootView.addView(defaultView);
      ImageView imageView = (ImageView) defaultView.findViewById(R.id.iconIM);
      TextView titleTV = (TextView) defaultView.findViewById(R.id.titleTV);
      TextView timeTV = (TextView) defaultView.findViewById(R.id.timeTV);
      TextView messageTV = (TextView) defaultView.findViewById(R.id.messageTV);
      imageView.setImageResource(headsUp.getIcon());
      titleTV.setText(headsUp.getTitleStr());
      messageTV.setText(headsUp.getMsgStr());
      SimpleDateFormat simpleDateFormat=new SimpleDateFormat("HH:mm");
      timeTV.setText( simpleDateFormat.format(new Date()));
    } else {
      setCustomView(headsUp.getCustomView());
    }
  }
  protected void cancel(){
    HeadsUpManager.getInstant(getContext()).animDismiss();
    cutDown = -1;
    cutDownTime.interrupt();
    if(velocityTracker!=null) {
      try {
        velocityTracker.clear();
        velocityTracker.recycle();
      } catch (IllegalStateException e) {
      }
    }
  }
  enum ScrollOrientationEnum {
    VERTICAL,HORIZONTAL,NONE
  }
}

具体用法:

PendingIntent pendingIntent=PendingIntent.getActivity(MainActivity.this,11,new Intent(MainActivity.this,MainActivity.class),PendingIntent.FLAG_UPDATE_CURRENT);
   View view=getLayoutInflater().inflate(R.layout.custom_notification, null);
   view.findViewById(R.id.openSource).setOnClickListener(new View.OnClickListener() {
     @Override
     public void onClick(View v) {
     }
   });
   HeadsUpManager manage = HeadsUpManager.getInstant(getApplication());
   HeadsUp.Builder builder = new HeadsUp.Builder(MainActivity.this);
   builder.setContentTitle("提醒")
       //要显示通知栏通知,这个一定要设置
       .setSmallIcon(R.drawable.icon)
       .setContentText("你有新的消息")
       //2.3 一定要设置这个参数,负责会报错
       .setContentIntent(pendingIntent)
       //.setFullScreenIntent(pendingIntent, false)
   HeadsUp headsUp = builder.buildHeadUp();
   headsUp.setCustomView(view);
   manage.notify(1, headsUp);
 }

总结

以上所述是小编给大家介绍的Android 中Notification弹出实现代码,希望对大家有所帮助,如果大家有任何疑问请给我留言,小编会及时回复大家的。在此也非常感谢大家对我们网站的支持!

(0)

相关推荐

  • Android编程使用Service实现Notification定时发送功能示例

    本文实例讲述了Android编程使用Service实现Notification定时发送功能.分享给大家供大家参考,具体如下: /** * 通过启动或停止服务来管理通知功能 * * @description: * @author ldm * @date 2016-4-29 上午9:15:15 */ public class NotifyControlActivity extends Activity { private Button notifyStart;// 启动通知服务 private Bu

  • Android 使用AlarmManager和NotificationManager来实现闹钟和通知栏

    实现闹钟运行的效果如下: 通知栏的运行后效果图如下: 布局文件(activity_main.xml) <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools&qu

  • Android 通知使用权(NotificationListenerService)的使用

    Android  通知使用权(NotificationListenerService)的使用 简介 当下不少第三方安全APP都有消息管理功能或者叫消息盒子功能,它们能管理过滤系统中的一些无用消息,使得消息栏更清爽干净.其实此功能的实现便是使用了Android中提供的通知使用权权限.Android4.3后加入了通知使用权NotificationListenerService,就是说当你开发的APP拥有此权限后便可以监听当前系统的通知的变化,在Android4.4后还扩展了可以获取通知详情信息.下面

  • android使用NotificationListenerService监听通知栏消息

    NotificationListenerService是通过系统调起的服务,在应用发起通知时,系统会将通知的应用,动作和信息回调给NotificationListenerService.但使用之前需要引导用户进行授权.使用NotificationListenerService一般需要下面三个步骤. 注册服务 首先需要在AndroidManifest.xml对service进行注册. <service android:name=".NotificationCollectorService&q

  • Android Notification的多种用法总结

    Android Notification的多种用法总结 我们在用手机的时候,如果来了短信,而我们没有点击查看的话,是不是在手机的最上边的状态栏里有一个短信的小图标提示啊?你是不是也想实现这种功能呢?今天的Notification就是解决这个问题的. 我们也知道Android系统也是在不断升级的,有关Notification的用法也就有很多种,有的方法已经被android抛弃了,现在我实现了三种不同的方法,并适应不同的android版本.现在我就把代码公布出来,我喜欢把解释写在代码中,在这里我就不

  • Android Notification 使用方法详解

    Android Notification 使用方法详解 用TaskStackBuilder来获取PendingIntent处理点击跳转到别的Activity,首先是用一般的PendingIntent来进行跳转. mBuilder = new NotificationCompat.Builder(this).setContent(view) .setSmallIcon(R.drawable.icon).setTicker("新资讯") .setWhen(System.currentTim

  • Android实现Service下载文件,Notification显示下载进度的示例

    先放个gif..最终效果如果: 主要演示了Android从服务器下载文件,调用Notification显示下载进度,并且在下载完毕以后点击通知会跳转到安装APK的界面,演示是在真实的网络环境中使用真实的URL进行演示,来看看代码: MainActivity代码非常简单,就是启动一个Service: public class MainActivity extends AppCompatActivity { String download_url="http://shouji.360tpcdn.co

  • Android 中Notification弹出通知实现代码

    NotificationManager 是状态栏通知的管理类,负责发通知.清除通知等操作. NotificationManager 是一个系统Service,可通过getSystemService(NOTIFICATION_SERVICE)方法来获取 接下来我想说的是android5.0 后的弹出通知, 网上的方法是: //第一步:实例化通知栏构造器Notification.Builder: Notification.Builder builder =new Notification.Build

  • Android 中Popwindow弹出菜单的两种方法实例

    Android 中Popwindow弹出菜单的两种方法实例 1.popWindow就是对话框的一种方式! 此文讲解的android中对话框的一种使用方式,它叫popWindow. 2.popWindow的特性 Android的对话框有两种:PopupWindow和AlertDialog.它们的不同点在于: AlertDialog的位置固定,而PopupWindow的位置可以随意. AlertDialog是非阻塞线程的,而PopupWindow是阻塞线程的. PopupWindow的位置按照有无偏

  • 详解Android中Notification通知提醒

    在消息通知时,我们经常用到两个组件Toast和Notification.特别是重要的和需要长时间显示的信息,用Notification就最 合适不过了.当有消息通知时,状态栏会显示通知的图标和文字,通过下拉状态栏,就可以看到通知信息了,Android这一创新性的UI组件赢得了用户的一 致好评,就连苹果也开始模仿了.今天我们就结合实例,探讨一下Notification具体的使用方法.  首先说明一下我们需要实现的功能是:在程序启动时,发出一个通知,这个通知在软件运行过程中一直存在,相当于qq的托盘

  • Android 从底部弹出Dialog(横向满屏)的实例代码

    项目中经常需要底部弹出框,这里我整理一下其中我用的比较顺手的一个方式(底部弹出一个横向满屏的dialog). 效果图如下所示(只显示关键部分): 步骤如下所示: 1.定义一个dialog的布局(lay_share.xml) <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/androi

  • 浅析Android Service中实现弹出对话框的坑

    一.手机版本问题,大多数文章没有涉及这个点,导致他们的代码并无法正常使用 M版本以上需要使用的Type--> TYPE_APPLICATION_OVERLAY AlertDialog.Builder builder=new AlertDialog.Builder(getApplicationContext()); builder.setTitle("提示"); builder.setMessage("service弹框"); builder.setNegati

  • Android 自定义弹出框实现代码

    废话不多说了,直接给大家上关键代码了. - (void)viewDidLoad { [super viewDidLoad]; // Do any additional setup after loading the view. [self showAlertView:@"11111"]; } //自定义弹出框 -(void)showAlertView:(NSString *)strTipText { UIView *showView=[[UIView alloc]init]; [sho

  • Android自定义dialog 自下往上弹出的实例代码

    具体代码如下所示: package com.example.idmin.myapplication.wiget; import android.app.Dialog; import android.content.Context; import android.os.Bundle; import android.view.Gravity; import android.view.View; import android.view.WindowManager; import android.wid

  • vue中实现弹出层动画效果的示例代码

    1 <template> <div class="home"> <!-- 首先将要过渡的元素用transition包裹,并设置过渡的name --> <transition name="mybox"> <div class="box" v-show="boxshow"></div> </transition> <button @click

  • Android中Notification用法实例总结

    本文实例总结了 Android中Notification用法.分享给大家供大家参考,具体如下: 我们在用手机的时候,如果来了短信,而我们没有点击查看的话,是不是在手机的最上边的状态栏里有一个短信的小图标提示啊?你是不是也想实现这种功能呢?今天的Notification就是解决这个问题的. 我们也知道Android系统也是在不断升级的,有关Notification的用法也就有很多种,有的方法已经被android抛弃了,现在我实现了三种不同的方法,并适应不同的android版本.现在我就把代码公布出

  • Android实现输入法弹出时把布局顶上去和登录按钮顶上去的解决方法

    背景:在写登录界面时,老板就觉得在输入密码的时候谈出来的输入法软键盘把登录按钮遮挡住了(入下图所示,不爽),连输入框都被挡了一半,于是不满意了,要叫我改,于是我看QQ的登录效果,我就去研究了一下,弹出输入法整个布局上来了,终于让老板满意了. (如上图这样,老板不满意的,呵呵) 1,咱们就解决问题吧. 我看了很多博客和问答,很多人都说直接在在AndroidManifest.xml中给这个Activity设置 <activity android:windowSoftInputMode="sta

随机推荐