Как сделать вибросигнал в android? - PullRequest
0 голосов
/ 09 мая 2020

Я новичок в Android и столкнулся с проблемой создания вибрирующего уведомления.

Ни один из этих подходов не работает:

AndroidManifest. xml:

<uses-permission android:name="android.permission.VIBRATE" />

Затем в моем модуле:

            NotificationChannel channel = new NotificationChannel(CHANNEL_ID, "channel",
                    NotificationManager.IMPORTANCE_HIGH);
            channel.setDescription("channel description");
            channel.enableVibration(true);
            channel.setVibrationPattern(new long[]{100, 200, 300, 400, 500, 400, 300, 200, 400});
            manager.createNotificationChannel(channel);

Второй подход:

            builder = new NotificationCompat.Builder(context, CHANNEL_ID);
        } else {
            builder = new NotificationCompat.Builder(context);
        }

        Intent activityIntent = new Intent(context, MainActivity.class);
        activityIntent.putExtra("FromNotification", true);
        PendingIntent action = PendingIntent.getActivity(context, 0, activityIntent, PendingIntent.FLAG_CANCEL_CURRENT);

        builder.setLargeIcon(BitmapFactory.decodeResource(res, R.drawable.ic_stat_icon_))
                .setSmallIcon(R.drawable.ic_stat_icon_).setTicker("Large text!").setAutoCancel(true)
                 .setVibrate(new long[] { 1000, 1000, 1000, 1000, 1000})
                .setContentTitle(notificationMessage).setPriority(NotificationCompat.PRIORITY_HIGH)
                .setCategory(NotificationCompat.CATEGORY_CALL).setContentText(contentText)
                .setFullScreenIntent(action, true);

Как мне изменить код, чтобы это работало?

Ответы [ 2 ]

0 голосов
/ 09 июня 2020

Что мне подходит:

activity_main. xml

<? xml version= "1.0" encoding= "utf-8" ?>
<android.support.constraint.ConstraintLayout
   xmlns: android = "http://schemas.android.com/apk/res/android"
   xmlns: app = "http://schemas.android.com/apk/res-auto"
   xmlns: tools = "http://schemas.android.com/tools"
   android :layout_width= "match_parent"
   android :layout_height= "match_parent"
   android :padding= "16dp"
   tools :context= ".MainActivity" >
   <Button
      android :id = "@+id/btnCreateNotification"
      android :layout_width= "0dp"
      android :layout_height= "wrap_content"
      android :text = "Create notification"
      app :layout_constraintBottom_toBottomOf= "parent"
      app :layout_constraintEnd_toEndOf= "parent"
      app :layout_constraintStart_toStartOf= "parent"
      app :layout_constraintTop_toTopOf= "parent" />
</android.support.constraint.ConstraintLayout>

Main Activity

public class MainActivity extends AppCompatActivity {
   private final static String default_notification_channel_id = "default";
   @Override
   protected void onCreate (Bundle savedInstanceState) {
      super .onCreate(savedInstanceState);
      setContentView(R.layout. activity_main );
      Button btnCreateNotification = findViewById(R.id. btnCreateNotification );
      btnCreateNotification.setOnClickListener( new View.OnClickListener() {
         @Override
         public void onClick (View v) {
            Intent intent = new Intent(getApplicationContext(), MainActivity. class );
            final PendingIntent resultPendingIntent =
            PendingIntent. getActivity (
               MainActivity. this,
               0,
               intent,
               PendingIntent. FLAG_CANCEL_CURRENT
            );
            NotificationCompat.Builder mBuilder =
               new NotificationCompat.Builder(MainActivity. this,
               default_notification_channel_id )
               .setSmallIcon(R.drawable. ic_launcher_foreground )
               .setContentTitle( "Test" )
               .addAction(R.drawable. ic_launcher_foreground, "Add", resultPendingIntent)
               .setContentIntent(resultPendingIntent)
               .setStyle( new NotificationCompat.BigTextStyle().bigText( "Big View Styles" ))
               .setContentText( "Hello! This is my first push notification" );
            NotificationManager mNotificationManager = (NotificationManager)
               getSystemService(Context. NOTIFICATION_SERVICE );
            mNotificationManager.notify(( int ) System. currentTimeMillis (), mBuilder.build()) ;
         }
      });
   }
}

в вашем манифесте

<uses-permission android :name= "android.permission.VIBRATE" />

Результат, как вы видите

enter image description here

0 голосов
/ 09 мая 2020

Это работает для меня, вы можете попробовать

//----------------------------------

 protected void displayNotification() {

        Log.i("Start", "notification");

      // Invoking the default notification service //
        NotificationCompat.Builder  mBuilder =
                new NotificationCompat.Builder(this);
        mBuilder.setAutoCancel(true);

        mBuilder.setContentTitle("New Message");
        mBuilder.setContentText("You have "+unMber_unRead_sms +" new message.");
        mBuilder.setTicker("New message from PayMe..");
        mBuilder.setSmallIcon(R.drawable.icon2);

      // Increase notification number every time a new notification arrives //
        mBuilder.setNumber(unMber_unRead_sms);

      // Creates an explicit intent for an Activity in your app //

        Intent resultIntent = new Intent(this, FreesmsLog.class);

        TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
        stackBuilder.addParentStack(FreesmsLog.class);

      // Adds the Intent that starts the Activity to the top of the stack //
        stackBuilder.addNextIntent(resultIntent);
        PendingIntent resultPendingIntent =
                stackBuilder.getPendingIntent(
                        0,
                        PendingIntent.FLAG_UPDATE_CURRENT
                );
        mBuilder.setContentIntent(resultPendingIntent);

      //  mBuilder.setOngoing(true);
        Notification note = mBuilder.build();
        note.defaults |= Notification.DEFAULT_VIBRATE;
        note.defaults |= Notification.DEFAULT_SOUND;

        mNotificationManager =
                (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
      // notificationID allows you to update the notification later on. //
        mNotificationManager.notify(notificationID, mBuilder.build());

    }
...