微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

我如何创建一个带有更新通知并在后台运行的计时器

如何解决我如何创建一个带有更新通知并在后台运行的计时器

所以我试图构建一个具有简单功能的小应用程序。

一个 15 分钟倒计时的计时器,显示剩余时间,计时器应继续在后台运行,显示间的持续通知,计时器完成后应删除/更新之前的通知并播放警报声。

基本上是您的常规闹钟。

我做的第一件事是在我的活动中设置一个计时器,并每秒更新一次通知。 问题是当应用程序最小化时它停止了。我在网上做了一些搜索,找到了服务。现在我试图弄清楚它是如何工作的,但我不确定该放什么位置以及如何在活动和通知中保持显示计时器。 (以及从哪里开始最后的警报通知

我当前的代码

通知服务

public class NotificationService extends Service {
private final IBinder mBinder = new LocalBinder();
private final int NOTIFICATION_ID = 123;
private int TimeOut = 0;
private Timer Timer;

notificationmanager manager;
NotificationCompat.Builder builder;

@Override
public void onCreate() {
    super.onCreate();
    startForeground(NOTIFICATION_ID,Notify());
    Timer = new Timer();
    Timer.schedule(new TeaTimerTask(),1000);
}


class TeaTimerTask extends TimerTask {

    @Override
    public void run() {
        if (TimeOut > 0) {
            TimeOut = TimeOut - 1;
            Notify();
        } else {
            Timer.cancel();
            Timer.purge();
            //to the next notification
        }
    }
};

public Notification Notify() {
    createNotificationChannel();

    int sec = TimeOut % 60;
    int min = (int) TimeOut / 60;
    String time = String.format("%d:%02d",min,sec);

    Intent local = new Intent();
    local.setAction("com.example.teatimer");
    local.putExtra("remainingTime",time);
    this.sendbroadcast(local);

    builder = new NotificationCompat.Builder(this,"TeaTimer")
            .setSmallIcon(R.drawable.teacupiconpng)
            .setContentTitle("TeaTimer")
            .setContentText("Your tea is still hot: " + time)
            .setStyle(new NotificationCompat.BigTextStyle()
                    .bigText("Your tea is almost ready,i'll notify you when it's cool ?.\n\n" + time))
            .setongoing(true)
            .setPriority(NotificationCompat.PRIORITY_LOW);

    if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        builder.setColor(getResources().getColor(R.color.colorPrimary));
    }
    Intent notificationIntent = new Intent(this,CoolingActivity.class);
    notificationIntent.putExtra("Time",900);
    PendingIntent contentIntent = PendingIntent.getActivity(this,notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);

    builder.setContentIntent(contentIntent);
    manager = (notificationmanager) getSystemService(Context.NOTIFICATION_SERVICE);
    return builder.build();
}

private void createNotificationChannel() {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = "TeaTimer";
        String description = "All notifications for the app TeaTimer";
        NotificationChannel channel = new NotificationChannel("TeaTimer",name,notificationmanager.IMPORTANCE_LOW);
        channel.setDescription(description);
        notificationmanager notificationmanager = getSystemService(notificationmanager.class);
        notificationmanager.createNotificationChannel(channel);
    }
}


@Nullable
@Override
public IBinder onBind(Intent intent) {
    return mBinder;
}

public class LocalBinder extends Binder {
    NotificationService getService() {
        return NotificationService.this;
    }
}
}

CoolingDownActivity

public class CoolingActivity extends AppCompatActivity {
WebView webView;
TextView txt1;
TextView txt2;
TextView TimerView;
int TimeOut;

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_cooling);

    Window window = CoolingActivity.this.getwindow();
    window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYstem_BAR_BACKGROUNDS);
    window.setStatusBarColor(ContextCompat.getColor(CoolingActivity.this,R.color.colorDarkPurple));

    webView = findViewById(R.id.web_view);
    WebSettings webSettings = webView.getSettings();
    webSettings.setJavaScriptEnabled(true);
    webSettings.setUseWideViewPort(true);
    webSettings.setLoadWithOverviewmode(true);
    String file = "file:///android_asset/farting-teabag.gif";
    webView.loadUrl(file);


    txt1 = (TextView) findViewById(R.id.Loading1_2);
    txt2 = (TextView) findViewById(R.id.Loading1_3);

    Intent intent = new Intent(this,NotificationService.class);
    intent.putExtra("totalTime",TimeOut);
    startService(intent);


    TimerView = (TextView) findViewById(R.id.Timer);
}

public void TeaIsReady() {
    Intent i = new Intent(this,StillHotActivity.class);
    startActivity(i);
}

@Override
protected void onNewIntent(Intent intent) {
    super.onNewIntent(intent);
    Intent myIntent = getIntent(); // gets the prevIoUsly created intent
    int newTime = myIntent.getIntExtra("Time",0);
    if (newTime != 0) {
        TimeOut = newTime;
    }

}
}

我觉得我真的不应该这么难,而且有一种更简单的解决方案。

非常感谢!我希望你有一个美好的一天。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。