1. 程式人生 > 程式設計 >Android服務應用ClockService實現鬧鐘功能

Android服務應用ClockService實現鬧鐘功能

ClockService安卓服務應用實現鬧鐘,供大家參考,具體內容如下

建立ClockActivity,可輸入一個時間(使用Time文字框),再建立一個ClockService在用於計時,到時間後,以在Activity中發出通知(在下方的TextView中顯示“時間到”)。

注意:這裡涉及到了Service操作Activity

Android服務應用ClockService實現鬧鐘功能

Android服務應用ClockService實現鬧鐘功能

Android服務應用ClockService實現鬧鐘功能

實驗步驟:使用BoundService方式開啟服務

1、首先定義佈局檔案,這裡不做過多贅述

Android服務應用ClockService實現鬧鐘功能

3、 定義一個Service服務類,然後在類裡面定義一個MyBinder的內部類,用於獲取Service物件與Service物件狀態。在內部類中必須要實現的方法onBind方法返回MyBinder服務物件。在內部類中定義一個getHandler方法獲取Handler物件用於MainActivity和MyService之間的訊息傳遞。

Android服務應用ClockService實現鬧鐘功能

Handler訊息傳遞關鍵程式碼如下:

Android服務應用ClockService實現鬧鐘功能

Android服務應用ClockService實現鬧鐘功能

4、 建立MainActivity中的單擊事件

Android服務應用ClockService實現鬧鐘功能

5、服務的繫結需要建立ServiceConnection物件並實現相應的方法,然後在重寫的onServiceConnected方法中獲取後臺Service,程式碼如下:

Android服務應用ClockService實現鬧鐘功能

- 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>

- MyService.java程式碼

package com.example.clock;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.widget.EditText;
public class MyService extends Service {
 public MyService() {
 }
 @Override
 public IBinder onBind(Intent intent) {
 return new MyBinder(); //必須實現的方法,用於活動與服務之間的繫結
 }
 public class MyBinder extends Binder {
 MyHandler handler;
 public MyService getMyService() {
  return MyService.this;
 }
 public MyHandler getHandler() {
  handler=new MyHandler();//初始化一個訊息物件
  return handler; //返回該訊息物件
 }
 }
 public class MyHandler extends Handler {
 public String[] nums;
 public String str;
 public String str1;
 public void handleMessage(Message msg) {
  str1= String.valueOf(msg.obj); //獲取MainActivity中傳遞的訊息
  Log.d("渣",str1);
  new Thread(new Runnable() {
  @Override
  public void run() { //開啟一個執行緒
   nums=str1.split(":"); //將獲取到的字串拆分成陣列
   //將字串中的時間轉換成秒
   int time1=Integer.parseInt(nums[2])+60*60*Integer.parseInt(nums[1])+60*Integer.parseInt(nums[1]);
   for(int time = time1;time>=0;time--){ //通過for迴圈對對時間進行迴圈
   if(time==0){ //如果時間倒計時到0,則顯示(時間到)字樣
    MainActivity.textView.setText("時間到!");
   }
   try { //將time秒重新轉換成時間字串
    int hour = 0;
    int minutes = 0;
    int sencond = 0;
    int temp = time % 3600;
    if (time > 3600) {
    hour = time / 3600;
    if (temp != 0) {
     if (temp > 60) {
     minutes = temp / 60;
     if (temp % 60 != 0) {
      sencond = temp % 60;
     }
     } else {
     sencond = temp;
     }
    }
    } else {
    minutes = time / 60;
    if (time % 60 != 0) {
     sencond = time % 60;
    }
    }
    str=(hour<10?("0"+hour):hour) + ":" + (minutes<10?("0"+minutes):minutes)
     + ":" + (sencond<10?("0"+sencond):sencond);
    MainActivity.num.setText(str); //及時更新EditText的值
    Thread.sleep(1000); //執行緒休眠1秒
   } catch (Exception e) {
    e.printStackTrace();
   }
   }
  }
  }).start();
 }
 }

 @Override
 public void onDestroy() {
 super.onDestroy();
 }
}

MainAcivity.java

package com.example.clock;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Binder;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
 MyService.MyBinder myBinder;
 public static EditText num;
 int flag = 0;
 String str;
 Intent intent;
 public static TextView textView;
 @Override
 protected void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);
 setContentView(R.layout.activity_main);
 textView=findViewById(R.id.text1);
 final Button btnStart = (Button) findViewById(R.id.btnStart);
 num = (EditText) findViewById(R.id.num);
 btnStart.setOnClickListener(new View.OnClickListener() {
  @Override
  public void onClick(View v) {
  if (flag == 0) {
   if (num.getText().length() < 1) { //如果未輸入數值,則獲取預設填充值(Hint)
   str = String.valueOf(num.getHint());
   }else {
   str=num.getText().toString(); //獲取輸入的值
   }
   flag = 1; //用於判斷按鈕狀態
   btnStart.setText("暫停");
   num.setEnabled(false); //將EditText設定為不可編輯
   intent = new Intent(MainActivity.this,MyService.class); //建立啟動Service的Intent物件
   bindService(intent,conn,BIND_AUTO_CREATE); //繫結指定Service
   Log.d("time",String.valueOf(str));
  } else {
   flag = 0;
   btnStart.setText("開始");
   myBinder.getMyService().onDestroy();
  }
  }
 });
 }
 ServiceConnection conn = new ServiceConnection() {
 @Override
 public void onServiceConnected(ComponentName name,IBinder service) {//設定與服務進行通訊
  myBinder = (MyService.MyBinder) service; //獲取服務中的MyBinder物件
  Message message = new Message(); //建立訊息物件
  message.obj = str; //傳遞引數,str是獲取到的值
  MyService.MyHandler handler = myBinder.getHandler(); //獲取MyService中的Handler物件
  handler.sendMessage(message); //通過Handler物件傳送訊息
 }

 @Override
 public void onServiceDisconnected(ComponentName name) {

 }
 };
}

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支援我們。