notice

  • Can be created on active or broadcast receivers

Basic usage

  1. By calling thegetSystemServicecreateNotificationManagerManagement notice
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    Copy the code
  2. useBuilderConstructor creationNotificationobject
    Notification notification = new NotificationCompat.Builder(context).build();
    Copy the code
    • emptyNotificationobject
    • Can be in the finalbuild()Method to set any number of concatenated methods
    Notification notification = new NotificationCompat.Builder(context)
            .setContentTitle("This is content title")
            .setContentText("This is content text")
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.small_icon)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.large_icon))
            .build();
    Copy the code
    • setContentTitle: Specifies the notification title. You can view it from the system status bar
    • setContentText: Specifies the notification body. You can view it from the system status bar
    • setWhen: Specifies the time when a notification is created, in milliseconds. The notification will be displayed when you drop down the system status bar
    • setSmallIcon: Small icon for setting notifications. Only images of pure alpha layers can be used to display in the system status bar
    • setLargeIcon: Large icon for setting notifications. You can see it when you drop down the system status bar
  3. callNotificationManagerthenotify()methods
    manager.notify(1, notification);
    Copy the code
    • The first parameter is a unique ID
    • The second parameter is the Notification object
  4. Click notification effect
    • PendingIntent: An Intent that delays execution
    • throughgetActivity(),getBroadcast()orgetServiceTo obtain
    • The first argument is Context

      The second argument is usually not needed; you can just pass in 0

      The third parameter is the Intent object

      The fourth parameter determines the behavior of the PendingIntentFLAG_ONE_SHOT FLAG_NO_CREATE FLAG_CANCEL_CURRENT FLAG_UPDATE_CURRENTFour values are available, usually 0
    • inNotificationCompat.BuilderThe constructor is kind of concatenationsetContentIntent()addPendingIntentobject
    Intent intent = new Intent(this, NotificationActivity.class);
    PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    Notification notification = new NotificationCompat.Builder(this)
            .setContentTitle("This is content title")
            .setContentText("This is content text")
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.small_icon)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.large_icon))
            .setContentIntent(pi)
            .build();
    manager.notify(1, notification);
    Copy the code
  5. Cancel the notification
    1. inNotificationCompat.BuilderA:setAutoCancel()methods
      Notification notification = new NotificationCompat.Builder(this)
              ...
              .setAutoCancel(true)
              .build();
      Copy the code
    2. Explicitly callNotificationManagerthecancel()methods
      NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); manager.cancel(1); / / to idCopy the code

Advanced skills

  • Play audio during notification
    • setSound()To receive aUriparameter
    • E.g.
      Notification notification = new NotificationCompat.Builder(this)
              ...
              .setSound(Uri.fromFile(new File("/system/media/audio/ringtones/Luna.ogg")))
              .build();
      Copy the code
  • Notification vibration
    • attributevibrateIs an array of long integers that sets the number of milliseconds for which the phone will rest and vibrate
    • A value of subscript 0 indicates how long the phone is still, a value of subscript 1 indicates how long the phone vibrates, a value of subscript 2 indicates how long the phone is still, and so on
    • E.g.
      Notification notification = new NotificationCompat.Builder(this)
              ...
              .setVibrate(new long[] {0, 1000, 1000, 1000})
              .build();
      Copy the code
    • Declare permissions<user-permission android:name="android.permission.VIBRATE" />
  • Flashing LED light when notification
    • setLights()The method takes three parameters

      The first parameter specifies the color of the LED light

      The second parameter specifies how long the LED lights are on, in milliseconds

      The third parameter specifies how long the LED lights are dimmed, in milliseconds
    • E.g.
      Notification notification = new NotificationCompat.Builder(this)
              ...
              .setLights(Color.GREEN, 1000, 1000)
              .build();
      Copy the code
  • Default Notification effect
    Notification notification = new NotificationCompat.Builder(this)
              ...
              .setDefaults(NotificationCompat.DEAULT_ALL)
              .build();
    Copy the code

Advanced features

  • setStyle(): Builds rich text notification content

    To receive aNotificationCompat.StyleParameter to build concrete rich text information
    • Display long text
      Notification notification = new NotificationCompat.Builder(this)
              ...
              .setStyle(new NotificationCompat.BigTextStyle().bigText("blabla"))
              .build();
      Copy the code
    • Show large images
      Notification notification = new NotificationCompat.Builder(this)
              ...
              .setStyle(new NotificationCompat.BigPictureStyle().bigPicture
                  (BitmapFactory.decodeResource(getResources(), R.drawable.large_image))
              .build();
      Copy the code
  • setPriority: Sets the importance of notifications

    Accepts an integer parameter that sets the importance of this parameter. Five constants are optional
    • PRIORITY_DEFAULT: The default importance is the same as if the value is not set
    • PRIORITY_min: The lowest level of importance. The system may only display this notification in certain scenarios
    • PRIORITY_LOW: Low importance. The system may reduce such notifications or change the order in which they are displayed next to more important notifications
    • PRIORITY_HIGH: A high degree of importance. The system may enlarge such notifications or change the order in which they are displayed to a higher place
    • PRIORITY_MAX: The highest level of importance that must be immediately visible to the user, or even require the user to respond
    • E.g.
      Notification notification = new NotificationCompat.Builder(this)
              ...
              .setPriority(NotificationCompat.PRIORITY_MAX)
              .build();
      Copy the code

Call the camera and album

Calling the Camera

  • shooting
    File outputImage = new File(getExternalCacheDir(), "output_image.jpg"); try { if (outputImage.exists()) { outputImage.delete(); } outputImage.createNewFile(); } catch (IOException e) { e.printStackTrace(); } if (Build.VERSION.SDK_INT >= 24) { imageUri = FileProvider.getUriForFile(MainActivity.this, "com.example.cameraalbumtest.fileprovider", outputImage); } else { imageUri = Uri.fromFile(outputImage); } / / start the camera application Intent Intent = new Intent (" android. Media. Action. IMAGE_CAPTURE "); intent.putExtra(MediaStore.EXTRA_OUTPUT, imageUri); startActivityForResult(intent, TAKE_PHOTO);Copy the code
    • Create a File object to store the content captured by the camera, and store the image in the app associated cache directory of the MOBILE SD card
      • The application associated cache directory is the location on the SD card where the current application cache data is storedgetExternalCacheDir()You can get the directory
      • The path issdcard/Android/data/<package name>/cache
      • Starting with Android 6.0, reading and writing SD cards are classified as dangerous permissions, and any other directory stored on the SD card is subject to runtime permissions
    • If the OS version is earlier than Android 7.0, callUrithefromFile()Method to convert a File object to a Uri object

      This Uri object identifies the local real path of the image
    • If the OS version is at least Android 7.0, callFileProviderthegetUriForFile()Method converts the File object to an encapsulated Uri object
      • getUriForFile()Receive three parameters

        The first argument is the Context object

        The second argument can be any unique string

        The third argument is the File object
      • Starting with Android 7.0, urIs that directly use the local real path are considered unsafe and will throw oneFileUriExposedExceptionabnormal
      • FileProviderA special kind of content provider that uses a similar mechanism to the content provider to secure data and optionally share encapsulated URIs externally
    • To build aIntentObject and put thisIntenttheactionSpecified asandroid.media.action.IMAGE_CAPTURECall again,IntenttheputExtra()Method to specify the output address (Uri) of the image
    • callstartActivityForResult()Start the activity
  • Displays pictures taken
    @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { switch(requestCode) { case TAKE_PHOTO: If (the resultCode = = RESULT_OK) {try {/ / will take pictures of display Bitmap Bitmap. = BitmapFactory decodeStream (getContentResolver () .openInputStream()); picture.setImageBitmap(bitmap); } catch (FileNotFoundException e) { e.printStackTrace(); } } break; default: break; }}Copy the code