【问题标题】:Android Studio notificationAndroid Studio 通知
【发布时间】:2020-09-13 12:27:30
【问题描述】:

我的通知有问题,我想显示的目的是,如果计数器达到 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);
    }
}

【问题讨论】:

    标签: android android-studio notifications android-notifications countdowntimer


    【解决方案1】:

    您好,此代码在较新的 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中创建通道的部分

    如果(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);
        }
    
    }
    

    【讨论】:

    • 非常感谢您的回复,但是如果我可以问,我如何在我的代码中获取该部分,如果您想提供帮助,那将非常棒,非常感谢!我的代码是java
    • 您好,请检查 android 版本,然后根据需要创建通知通道,然后像往常一样创建通知,然后我将使用在 java 中创建通道来更新代码
    • 检查此developer.android.com/training/notify-user/build-notification 也不要忘记在通知管理器中添加您的频道 ID NotificationCompat.Builder builder = new NotificationCompat.Builder(this, CHANNEL_ID) .setSmallIcon(R.drawable.notification_icon) .setContentTitle("我的通知") .setContentText("Hello World!") .setPriority(NotificationCompat.PRIORITY_DEFAULT);
    • 提前非常感谢你,但我只是不明白我是如何在我的代码中得到它的,我不知道你是否可以/想要帮助这个?如果是这样,我真的很喜欢你,因为我已经处理了一段时间并且无法修复它。
    • 我已经添加了您的代码以及添加的部分代码是如何工作的,祝你好运
    猜你喜欢
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 2020-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多