Android利用ClockService實現一個定時鬧鐘功能?針對這個問題,這篇文章詳細介紹了相對應的分析和解答,希望可以幫助更多想解決這個問題的小伙伴找到更簡單易行的方法。

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



實驗步驟:使用BoundService方式開啟服務
1、首先定義布局文件,這里不做過多贅述

3、 定義一個Service服務類,然后在類里面定義一個MyBinder的內部類,用于獲取Service對象與Service對象狀態。在內部類中必須要實現的方法onBind方法返回MyBinder服務對象。在內部類中定義一個getHandler方法獲取Handler對象用于MainActivity和MyService之間的消息傳遞。

Handler消息傳遞關鍵代碼如下:


4、 創建MainActivity中的單擊事件

5、服務的綁定需要創建ServiceConnection對象并實現相應的方法,然后在重寫的onServiceConnected方法中獲取后臺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="倒計時" android:textSize="100sp"></TextView> </LinearLayout>
本文題目:Android利用ClockService實現一個定時鬧鐘功能-創新互聯
URL地址:http://www.yijiale78.com/article6/doccog.html
成都網站建設公司_創新互聯,為您提供建站公司、軟件開發、網站建設、網站設計公司、商城網站、電子商務
聲明:本網站發布的內容(圖片、視頻和文字)以用戶投稿、用戶轉載內容為主,如果涉及侵權請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網站立場,如需處理請聯系客服。電話:028-86922220;郵箱:631063699@qq.com。內容未經允許不得轉載,或轉載時需注明來源: 創新互聯