Android利用ClockService實(shí)現(xiàn)一個(gè)定時(shí)鬧鐘功能?針對(duì)這個(gè)問題,這篇文章詳細(xì)介紹了相對(duì)應(yīng)的分析和解答,希望可以幫助更多想解決這個(gè)問題的小伙伴找到更簡(jiǎn)單易行的方法。

創(chuàng)建ClockActivity,可輸入一個(gè)時(shí)間(使用Time文本框),再創(chuàng)建一個(gè)ClockService在用于計(jì)時(shí),到時(shí)間后,以在Activity中發(fā)出通知(在下方的TextView中顯示“時(shí)間到”)。
注意:這里涉及到了Service操作Activity



實(shí)驗(yàn)步驟:使用BoundService方式開啟服務(wù)
1、首先定義布局文件,這里不做過多贅述

3、 定義一個(gè)Service服務(wù)類,然后在類里面定義一個(gè)MyBinder的內(nèi)部類,用于獲取Service對(duì)象與Service對(duì)象狀態(tài)。在內(nèi)部類中必須要實(shí)現(xiàn)的方法onBind方法返回MyBinder服務(wù)對(duì)象。在內(nèi)部類中定義一個(gè)getHandler方法獲取Handler對(duì)象用于MainActivity和MyService之間的消息傳遞。

Handler消息傳遞關(guān)鍵代碼如下:


4、 創(chuàng)建MainActivity中的單擊事件

5、服務(wù)的綁定需要?jiǎng)?chuàng)建ServiceConnection對(duì)象并實(shí)現(xiàn)相應(yīng)的方法,然后在重寫的onServiceConnected方法中獲取后臺(tái)Service,代碼如下:

- Activity_main.xml代碼:
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical"> <LinearLayout android:layout_width="match_parent" android:layout_height="110dp" android:layout_marginHorizontal="20dp" android:orientation="horizontal"> <TextView android:layout_width="150dp" android:layout_height="80dp" android:layout_marginTop="15dp" android:background="@drawable/shape" android:gravity="center_horizontal" android:text="鬧鐘" android:textAlignment="center" android:textSize="50sp"></TextView> <EditText android:autofillHints="true" android:hint="10:10:10" android:id="@+id/num" android:layout_width="match_parent" android:layout_height="80dp" android:layout_marginLeft="15dp" android:layout_marginTop="5dp" android:background="@drawable/shape" android:gravity="center" android:inputType="time" android:textSize="35sp"></EditText> </LinearLayout> <Button android:id="@+id/btnStart" android:layout_width="match_parent" android:layout_height="80dp" android:layout_marginHorizontal="20dp" android:layout_marginTop="15dp" android:background="@drawable/shape" android:text="開始" android:textSize="50sp"></Button> <TextView android:id="@+id/text1" android:layout_width="match_parent" android:layout_height="300dp" android:layout_margin="20dp" android:background="@drawable/shape" android:gravity="center" android:text="倒計(jì)時(shí)" android:textSize="100sp"></TextView> </LinearLayout>
本文題目:Android利用ClockService實(shí)現(xiàn)一個(gè)定時(shí)鬧鐘功能-創(chuàng)新互聯(lián)
URL地址:http://www.chinadenli.net/article6/doccog.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供建站公司、軟件開發(fā)、網(wǎng)站建設(shè)、網(wǎng)站設(shè)計(jì)公司、商城網(wǎng)站、電子商務(wù)
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請(qǐng)盡快告知,我們將會(huì)在第一時(shí)間刪除。文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如需處理請(qǐng)聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時(shí)需注明來源: 創(chuàng)新互聯(lián)
猜你還喜歡下面的內(nèi)容