与服务集成时未显示通知

问题描述

我构建了一个有趣的应用程序,以了解Android中的通知和调度程序。该应用应在随机延迟后显示通知。在该应用程序中,我将其与即使在手机屏幕关闭的情况下仍可以运行的服务集成在一起。

问题在于,由于我集成了该服务,因此通知和延迟通知停止工作。我被困住了,需要一点帮助,我下一步应该怎么做。

MainActivity.java

public class MainActivity extends Activity {

    Button button;
    String ChannelId = "Notifications";
    private final Random mRandom = new Random();
    int delayMillis;
    Handler handler;
    Runnable runnable;

    @RequiresApi(api = Build.VERSION_CODES.O)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        startService(new Intent(this,MyService.class));

    }

}

MyService.java

    public class MyService extends Service {
    
        String ChannelId = "Notifications";
        private final Random mRandom = new Random();
        int delayMillis;
        Handler handler;
        Runnable runnable;
    
        @Nullable
        @Override
        public IBinder onBind(Intent intent) {
            return null;
        }
    
        @Override
        public int onStartCommand(Intent intent,int flags,int startId) {
            showNotification();
            return START_STICKY;
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
        }
    
//The notification doesn't show when the app gets started
        private void showNotification(){
            Intent intent = new Intent(this,MainActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            PendingIntent pendingIntent = PendingIntent.getActivity(this,intent,PendingIntent.FLAG_ONE_SHOT);
    
            String[] names = {"John Doe","Jane Doe"};
            String[] txtMessage = {"hi","hello"};
    
            int nameRand = new Random().nextInt(18 - 0);
            int MsgRand = new Random().nextInt(25 - 0);
    
            Uri soundUri = Uri.parse("android.resource://" + getApplicationContext().getPackageName() + "/" + R.raw.messenger);
            NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this,ChannelId)
                    .setSmallIcon(R.drawable.ic_stat_notificationicon)
                    .setContentTitle(names[nameRand])
                    .setContentText(txtMessage[MsgRand])
                    .setAutoCancel(true)
                    .setSound(soundUri)
                    .setContentIntent(pendingIntent);
    
            notificationmanager mnotificationmanager = (notificationmanager) getSystemService(Context.NOTIFICATION_SERVICE);
            if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.O) {
                if(soundUri != null){
    
                    notificationBuilder.setDefaults(Notification.DEFAULT_ALL);
                    AudioAttributes audioAttributes = new AudioAttributes.Builder()
                            .setContentType(AudioAttributes.CONTENT_TYPE_SONIFICATION)
                            .setUsage(AudioAttributes.USAGE_NOTIFICATION)
                            .setLegacyStreamType(AudioManager.STREAM_NOTIFICATION)
                            .build();
    
                    NotificationChannel notificationChannel = new NotificationChannel(ChannelId,"Messenger",notificationmanager.IMPORTANCE_DEFAULT);
                    notificationChannel.setSound(soundUri,audioAttributes);
                    notificationChannel.setVibrationPattern(new long[]{ 0,200 });
                    notificationChannel.enableVibration(true);
                    mnotificationmanager.createNotificationChannel(notificationChannel);
//Delayed notification also doesn't show    
                    delayMillis = 10000 * mRandom.nextInt(5) + 6;
                    try {
                        Thread.sleep(delayMillis);
                        showNotification();
                    } catch (InterruptedException e) {
                        e.printstacktrace();
                    }
    
                }
            }
            int m = (int) ((new Date().getTime() / 1000L) % Integer.MAX_VALUE);
            mnotificationmanager.notify(m,notificationBuilder.build());
        }
    
    }

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.messengerserviceprovider">

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

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_messenger"
        android:label="@string/app_name"
        android:roundIcon="@drawable/ic_messenger"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <service android:name=".MyService"/>
    </application>

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

</manifest>

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)