Android电子时钟-充分利用您的旧手机

MyClock

一、所使用到的资源及服务

1、实时天气服务

使用心知天气-天气数据API免费接口(其中有收费的服务,这里我用的是免费的接口https://www.seniverse.com/doc

2、使用retrofit2进行网络请求

3、使用LED字体库(DS-DIGIT.TTF可以网上查询下载)

二、包含功能

1、时间(采用24时形式)、日期(yyyy/MM/dd形式)、周

2、农历计算并自动显示(包括甲子年及生肖)

3、天气(实时天气情况,10分钟更新一次)

二、界面设计

APK采用简单的单页面形式,如下图所示:


三、主界面源码

package cn.daibz.myclock

import android.animation.ObjectAnimator
import android.graphics.Typeface
import android.os.Bundle
import android.os.Handler
import android.support.v7.app.AppCompatActivity
import android.view.View
import android.view.WindowManager
import cn.daibz.bus.helper.net.MyClockService
import cn.daibz.myclock.model.Weather
import cn.daibz.myclock.utils.BrightnessUtils
import cn.daibz.myclock.utils.DateTimeFormatUtils
import cn.daibz.myclock.utils.Lunar
import cn.daibz.myclock.utils.ResourceUtils
import kotlinx.android.synthetic.main.activity_main.*
import rx.Observable
import rx.Observer
import rx.android.schedulers.AndroidSchedulers
import rx.schedulers.Schedulers
import java.util.*
import java.util.concurrent.TimeUnit


/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
class MainActivity : AppCompatActivity() {
    private val mHideHandler = Handler()
    private val mHidePart2Runnable = Runnable {
        // Delayed removal of status and navigation bar

        // Note that some of these constants are new as of API 16 (Jelly Bean)
        // and API 19 (KitKat). It is safe to use them, as they are inlined
        // at compile-time and do nothing on earlier devices.
        fullscreen_content.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LOW_PROFILE or
                View.SYSTEM_UI_FLAG_FULLSCREEN or
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE or
                View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY or
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION or
                View.SYSTEM_UI_FLAG_HIDE_NAVIGATION
    }
    private val mShowPart2Runnable = Runnable {
        // Delayed display of UI elements
        supportActionBar?.show()
        fullscreen_content_controls.visibility = View.VISIBLE
    }
    private var mVisible: Boolean = false
    private val mHideRunnable = Runnable { hide() }
    /**
     * Touch listener to use for in-layout UI controls to delay hiding the
     * system UI. This is to prevent the jarring behavior of controls going away
     * while interacting with activity UI.
     */
    private val mDelayHideTouchListener = View.OnTouchListener { _, _ ->
        if (AUTO_HIDE) {
            delayedHide(AUTO_HIDE_DELAY_MILLIS)
        }
        false
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)

        setContentView(R.layout.activity_main)
        window.addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON)
        supportActionBar?.setDisplayHomeAsUpEnabled(true)

        mVisible = true

        // Set up the user interaction to manually show or hide the system UI.
        fullscreen_content.setOnClickListener { toggle() }

        // Upon interacting with UI controls, delay any scheduled hide()
        // operations to prevent the jarring behavior of controls going away
        // while interacting with the UI.
        dummy_button.setOnTouchListener(mDelayHideTouchListener)
        val tf = Typeface.createFromAsset(assets, "fonts/DS-DIGIT.TTF")
        tv_hour.typeface = tf
        tv_dot.typeface = tf
        tv_minute.typeface = tf
        tv_date.typeface = tf
        tv_temperature.typeface = tf
        val animator = ObjectAnimator.ofFloat(tv_dot, "alpha", 1.0f, 0.1f, 1.0f)
        animator.duration = 1000
        animator.repeatCount = ObjectAnimator.INFINITE
        animator.start()
        Observable.interval(0, 1, TimeUnit.SECONDS)
                .subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<Long> {
                    override fun onError(e: Throwable?) {
                    }

                    override fun onNext(t: Long?) {
                        val calendar = Calendar.getInstance()
                        calendar.time = Date()
                        val lunar = Lunar(calendar)
                        tv_hour.text = DateTimeFormatUtils.format(calendar.time, "HH")
                        tv_minute.text = DateTimeFormatUtils.format(calendar.time, "mm")
                        tv_date.text = String.format(Locale.CHINA, "%s %s", DateTimeFormatUtils.format(calendar.time, "yyyy/MM/dd"),
                                DateTimeFormatUtils.format2Week(calendar.time))
                        tv_lunar.setCompoundDrawablesWithIntrinsicBounds(lunar.animalsYearDrawable(), 0, 0, 0)
                        tv_lunar.text = lunar.toString()
                        val hour = calendar.get(Calendar.HOUR_OF_DAY)
                        when (hour) {
                            in 0..7 -> BrightnessUtils.changeAppBrightness(this@MainActivity, 1)
                            in 8..9 -> BrightnessUtils.changeAppBrightness(this@MainActivity, 100)
                            in 10..11 -> BrightnessUtils.changeAppBrightness(this@MainActivity, 120)
                            in 12..17 -> BrightnessUtils.changeAppBrightness(this@MainActivity, 180)
                            in 18..20 -> BrightnessUtils.changeAppBrightness(this@MainActivity, 120)
                            in 21..22 -> BrightnessUtils.changeAppBrightness(this@MainActivity, 100)
                            in 22..24 -> BrightnessUtils.changeAppBrightness(this@MainActivity, 80)
                        }
                    }

                    override fun onCompleted() {
                    }


                })

        Observable.interval(0, 10, TimeUnit.MINUTES)
                .subscribeOn(Schedulers.newThread()).observeOn(AndroidSchedulers.mainThread())
                .subscribe {
                    getWeather()
                }
    }

    private fun getWeather() {
        val service = MyClockApplication.retrofit.create(MyClockService::class.java)
        service.getWeather("shihezi")
                .subscribeOn(rx.schedulers.Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
                .subscribe(object : Observer<Weather> {
                    override fun onError(e: Throwable?) {
                    }

                    override fun onNext(w: Weather?) {
                        if (w != null) {
                            if (w.results.size != 0) {
                                val bean = w.results[0]
                                tv_weather.setCompoundDrawablesWithIntrinsicBounds(
                                        ResourceUtils.getDrawableId(this@MainActivity,
                                                String.format(Locale.CHINA, "weather_%s", bean.now.code)), 0, 0, 0)
                                tv_weather.text = bean.now.text
                                tv_temperature.text = bean.now.temperature
                                println(tv_temperature.text)
                            }
                        }
                    }

                    override fun onCompleted() {
                    }

                })
    }

    override fun onPostCreate(savedInstanceState: Bundle?) {
        super.onPostCreate(savedInstanceState)

        // Trigger the initial hide() shortly after the activity has been
        // created, to briefly hint to the user that UI controls
        // are available.
        delayedHide(100)
    }

    private fun toggle() {
        if (mVisible) {
            hide()
        } else {
            show()
        }
    }

    private fun hide() {
        // Hide UI first
        supportActionBar?.hide()
        fullscreen_content_controls.visibility = View.GONE
        mVisible = false

        // Schedule a runnable to remove the status and navigation bar after a delay
        mHideHandler.removeCallbacks(mShowPart2Runnable)
        mHideHandler.postDelayed(mHidePart2Runnable, UI_ANIMATION_DELAY.toLong())
    }

    private fun show() {
        // Show the system bar
        fullscreen_content.systemUiVisibility =
                View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN or
                View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
        mVisible = true

        // Schedule a runnable to display UI elements after a delay
        mHideHandler.removeCallbacks(mHidePart2Runnable)
        mHideHandler.postDelayed(mShowPart2Runnable, UI_ANIMATION_DELAY.toLong())
    }

    /**
     * Schedules a call to hide() in [delayMillis], canceling any
     * previously scheduled calls.
     */
    private fun delayedHide(delayMillis: Int) {
        mHideHandler.removeCallbacks(mHideRunnable)
        mHideHandler.postDelayed(mHideRunnable, delayMillis.toLong())
    }

    companion object {
        /**
         * Whether or not the system UI should be auto-hidden after
         * [AUTO_HIDE_DELAY_MILLIS] milliseconds.
         */
        private val AUTO_HIDE = true

        /**
         * If [AUTO_HIDE] is set, the number of milliseconds to wait after
         * user interaction before hiding the system UI.
         */
        private val AUTO_HIDE_DELAY_MILLIS = 3000

        /**
         * Some older devices needs a small delay between UI widget updates
         * and a change of the status and navigation bar.
         */
        private val UI_ANIMATION_DELAY = 300
    }
}
本人比较懒,源码没有太多注释,还请谅解。项目源码下载地址: MyClock
  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

DbzZcz

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值