Добавить разрешение для уведомления на экране блокировки Android программным способом - PullRequest
0 голосов
/ 10 апреля 2020

В моем приложении Android я не могу включить уведомление на экране блокировки. Как вы можете видеть на скриншоте, все опции отключены. Как включить эту опцию программно? В настоящее время я тестирую это приложение в своем телефоне MI Xiaomi Phone и имею эту проблему. Как можно решить это? Пожалуйста, проверьте скриншот Сильфон и дайте мне предложение для этой проблемы. спасибо

enter image description here

Я уже устал от этого кода, но уведомление не отображается на экране блокировки как в основном я не могу включить это разрешение.

Вот мой код:

    package maxpro.com.ramadantime.BoradCastReceiver;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Build;
import android.os.PowerManager;
import android.os.Vibrator;
import android.provider.Settings;
import android.view.WindowManager;
import android.widget.Toast;

import java.io.IOException;

import androidx.core.app.NotificationCompat;
import maxpro.com.ramadantime.MainActivity;
import maxpro.com.ramadantime.R;
import maxpro.com.ramadantime.Splash.SplashActivity;

import static android.content.Context.POWER_SERVICE;

public class MyBroadCastReceiver extends BroadcastReceiver {
    Notification notification;
    MediaPlayer mediaPlayer;
    @Override
        public void onReceive (Context context, Intent intent)
        {

            // Logic to turn on the screen
            PowerManager powerManager = (PowerManager) context.getSystemService(POWER_SERVICE);

            if (!powerManager.isInteractive()){ // if screen is not already on, turn it on (get wake_lock for 10 seconds)
                @SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wl = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK |PowerManager.ACQUIRE_CAUSES_WAKEUP |PowerManager.ON_AFTER_RELEASE,"MH24_SCREENLOCK");
                wl.acquire(10000);
                @SuppressLint("InvalidWakeLockTag") PowerManager.WakeLock wl_cpu = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK,"MH24_SCREENLOCK");
                wl_cpu.acquire(10000);
            }

            try {
                Uri myUri = Uri.parse("android.resource://" + context.getPackageName() + "/" + R.raw.m);
               mediaPlayer = new MediaPlayer();
                mediaPlayer.setDataSource(context,myUri);
                mediaPlayer.setAudioStreamType(AudioManager.STREAM_ALARM);
                mediaPlayer.setLooping(true);
                mediaPlayer.prepare();
            } catch (IOException e) {
                e.printStackTrace();
            }
            mediaPlayer.start();
            // Put here YOUR code.
            Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
            showNotification("notification","alarm",context);

        }

        public void setAlarm (Context context)
        {
            AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            Intent i = new Intent(context, MyBroadCastReceiver.class);
            PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
            am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
        }

        public void cancelAlarm (Context context)
        {
            Intent intent = new Intent(context, MyBroadCastReceiver.class);
            PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
            AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
            alarmManager.cancel(sender);
        }


    @SuppressLint("NewApi")
    public void showNotification(String title, String message, Context context) {
        AudioAttributes att = new AudioAttributes.Builder()
                .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                .setContentType(AudioAttributes.CONTENT_TYPE_SPEECH)
                .build();
        Intent intent = new Intent(context, SplashActivity.class);
        String channel_id = "notification";
        intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, PendingIntent.FLAG_ONE_SHOT);
        Uri uri = Uri.parse("android.resource://"+context.getPackageName()+"/" + R.raw.m);
        NotificationCompat.Builder builder = new NotificationCompat.Builder(context, channel_id)
                .setSmallIcon(R.drawable.background)
                .setSound(uri)
                .setContentTitle("Weekly Alarm")
                .setContentText("beeeep")
                .setContentIntent(pendingIntent);
        //wake up device and show even when on lock screen
        final long[] DEFAULT_VIBRATE_PATTERN = {0, 250, 250, 250};
        builder.setVibrate(DEFAULT_VIBRATE_PATTERN);
        builder.setLights(Color.WHITE, 2000, 3000);
        builder.setSound(Settings.System.DEFAULT_NOTIFICATION_URI);

// This is the answer to OP's question, set the visibility of notification to public.
        builder.setVisibility(NotificationCompat.VISIBILITY_PUBLIC);
        NotificationManager notificationManager = (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
        notificationManager.notify(0, builder.build());

    }
    }

С помощью этого кода я могу go настроить уведомления, но я хочу включить его программным способом, не показывая его пользователю

public static void goToNotificationSettings(Context context) {
    Intent intent = new Intent();
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(Uri.fromParts(SCHEME, context.getPackageName(), null));
    } else if (Build.VERSION.SDK_INT > Build.VERSION_CODES.N_MR1) {
        intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
        intent.putExtra("app_package", context.getPackageName());
    } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        intent.setAction("android.settings.APP_NOTIFICATION_SETTINGS");
        intent.putExtra("app_package", context.getPackageName());
        intent.putExtra("app_uid", context.getApplicationInfo().uid);
    } else if (Build.VERSION.SDK_INT == Build.VERSION_CODES.KITKAT) {
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.addCategory(Intent.CATEGORY_DEFAULT);
        intent.setData(Uri.parse("package:" + context.getPackageName()));
    } else {
        return;
    }
    context.startActivity(intent);
}
...