首页 > 解决方案 > Android Studio 通知

问题描述

我有一个通知问题,我想显示的意图是,如果计数器达到 0,它会给我一个时间到的通知,但如果没关系,一切都很好,但如果我没有收到通知时间到了,有人可以帮忙吗?提前致谢!在此文本下方,您可以找到我卡住的代码。

package com.example.melkanalysetimer;

import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.NotificationCompat;

import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class wit extends AppCompatActivity {
    private TextView countdownText;
    private Button countdownButton;
    private Button krat;
    private Button remove;
    private TextView scoreb;
    private TextView money;
    private TextView reset;

    private CountDownTimer countDownTimer;
    private long timeLeftInMilliseconds = 960000;
    private boolean timerRunning;
    private static final long START_TIME_IN_MILLIS = 960000;

    int score = 0;
    double geld = 0.00;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_wit);

        countdownText = findViewById(R.id.countdown_text);
        countdownButton = findViewById(R.id.countdown_button);
        krat = findViewById(R.id.b_add);
        scoreb = findViewById(R.id.tv_score);
        remove = findViewById(R.id.b_remove);
        money = findViewById(R.id.ssgeld);
        reset = findViewById(R.id.button_reset);

        scoreb.setText("Kratjes: "+ score);
        money.setText("Geld: "+ geld);

        krat.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                score++;
                scoreb.setText("Kratjes: "+ score);
                geld = geld + 1.5;
                money.setText("Geld: "+ geld);
            }
        });

        remove.setOnClickListener(new View.OnClickListener(){
            @Override
            public void onClick(View view) {
                if(score >= 1){
                    score--;
                }
                scoreb.setText("Kratjes: "+ score);
                if(geld >= 1.5){
                    geld = geld - 1.5;
                }
                money.setText("Geld: "+ geld);
            }
        });

        reset.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                resetTimer();
            }
        });

        countdownButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                startStop();
            }
        });

        updateTimer();
    }

    public void startStop() {
        if (timerRunning) {
            stopTimer();
        } else {
            startTimer();
        }
    }

    public void startTimer() {
        countDownTimer = new CountDownTimer(timeLeftInMilliseconds, 1000) {
            @Override
            public void onTick(long l) {
                timeLeftInMilliseconds = l;
                updateTimer();
            }

            @Override
            public void onFinish() {
                addNotification();
            }

        }.start();

        countdownButton.setText("PAUZE");
        timerRunning = true;
    }

    public void stopTimer() {
        countDownTimer.cancel();
        countdownButton.setText("START");
        timerRunning = false;
    }

    public void resetTimer() {
        timeLeftInMilliseconds = START_TIME_IN_MILLIS;
        updateTimer();
    }

    public void addNotification() {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.mipmap.ic_launcher_round)
                .setContentTitle("TEST!!")
                .setContentText("TEST!");

        Intent notificationIntent = new Intent(this, wit.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(contentIntent);

        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        manager.notify(0, builder.build());
    }

    public void updateTimer() {
        int minutes = (int) timeLeftInMilliseconds / 60000;
        int seconds = (int) timeLeftInMilliseconds % 60000 / 1000;

        String timeLeftText;

        timeLeftText = "" + minutes;
        timeLeftText += ":";
        if (seconds < 10) timeLeftText += "0";
        timeLeftText += seconds;

        countdownText.setText(timeLeftText);
    }
}

标签: androidandroid-studionotificationsandroid-notificationscountdowntimer

解决方案


您好,此代码在较新的 android 版本上缺少处理通道,您需要添加启动 android 的通道 o 这是 kotlin 中添加最大优先级通道的工作代码示例

     override fun onMessageReceived(remoteMessage: RemoteMessage) {
    
    // Check if message contains a notification payload.
    remoteMessage.notification?.let {
        if (BuildConfig.DEBUG)
            Log.d(TAG, "Message Notification Body: ${it.body}")
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {

            val channels = ArrayList<NotificationChannel>(2)
            val channel = NotificationChannel(
                getString(R.string.default_notification_channel_id),
                getString(R.string.default_notification_channel_id),
                NotificationManager.IMPORTANCE_DEFAULT
            ).apply {
                description = getString(R.string.default_notification_channel_id)
            }
            val channelHigh = NotificationChannel(
                getString(R.string.HIGH_notification_channel_id),
                getString(R.string.HIGH_notification_channel_id),
                NotificationManager.IMPORTANCE_HIGH
            ).apply {
                description = getString(R.string.HIGH_notification_channel_id)
            }

            channels.add(channel)
            channels.add(channelHigh)
            // Register the channel with the system
            val notificationManager: NotificationManager =
                getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager

            notificationManager.createNotificationChannels(channels)
        }


        // Create an Intent for the activity you want to start
        val resultIntent = Intent(this, SplashActivity::class.java)
        // Create the TaskStackBuilder
        val resultPendingIntent: PendingIntent? = 
             TaskStackBuilder.create(this).run {
            // Add the intent, which inflates the back stack
            addNextIntentWithParentStack(resultIntent)
            // Get the PendingIntent containing the entire back stack
            getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT)
        }
        val builder = NotificationCompat.Builder(
            this,
            if (!it.channelId.isNullOrEmpty()) it.channelId!! else
                getString(R.string.HIGH_notification_channel_id)
        )
            .setSmallIcon(R.drawable.notification_icon).setAutoCancel(true)
            .setContentTitle(if (it.title.isNullOrEmpty()) 
            getString(R.string.app_name) else it.title)
            .setContentText(it.body)
            .setPriority(NotificationCompat.PRIORITY_MAX)
            .
            setContentIntent(resultPendingIntent)

        if (it.imageUrl != null) {
            val bitmap = getBitmapfromUrl(it.imageUrl)
            builder.setLargeIcon(bitmap)
                .setStyle(
                    NotificationCompat.BigPictureStyle()
                        .bigPicture(bitmap)
                        .bigLargeIcon(null)
                )

        } else {
            val bitmap = BitmapFactory.decodeResource(resources, R.drawable.app_icon)
            builder.setLargeIcon(bitmap)
        }

        with(NotificationManagerCompat.from(this)) {
            // notificationId is a unique int for each notification that you must define
            notify(Date().time.toInt(), builder.build())
        }
    }
}

这是检查后在java中创建通道部分

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)

private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    CharSequence name = getString(R.string.channel_name);
    String description = getString(R.string.channel_description);
    int importance = NotificationManager.IMPORTANCE_DEFAULT;
    NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
    channel.setDescription(description);
    // Register the channel with the system; you can't change the importance
    // or other notification behaviors after this
    NotificationManager notificationManager = getSystemService(NotificationManager.class);
    notificationManager.createNotificationChannel(channel);
}
}

这是你的代码

public void addNotification() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        createNotificationChannel();
    }
    NotificationCompat.Builder builder = new NotificationCompat.Builder(this, getString(R.string.CHANNEL_ID))
            .setSmallIcon(R.mipmap.ic_launcher_round)
            .setContentTitle("TEST!!")
            .setContentText("TEST!");

    Intent notificationIntent = new Intent(this, wit.class);
    PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
    builder.setContentIntent(contentIntent);

    NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
    manager.notify(0, builder.build());
}

private void createNotificationChannel() {
// Create the NotificationChannel, but only on API 26+ because
// the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = getString(R.string.channel_name);
        String description = getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel(getString(R.string.CHANNEL_ID), name, importance);
        channel.setDescription(description);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }

}

推荐阅读