Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 應用:計算並取得日出日落時間

編輯:關於 Android 程式設計

想讓 App 依日出日落自動調整行為(例如背光、日夜模式),關鍵就在於能算出當地的日出與日落時間。實作上會透過一個背景 Service 來運算,並把結果存起來。別忘了要在 AndroidManifest.xml 中註冊並啟動這個 Service。

一、Service 的整體架構

這個 Service 在建立時會先以預設座標計算一次日出日落時間,接著註冊 GPS 定位。一旦取得新的座標,就重新計算並寫入系統設定、發送廣播通知:

package com.android.options;

import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.IBinder;
import android.provider.Settings;
import android.util.Log;

import java.util.Calendar;

public class BacklightService extends Service {

    private static double mLatitude = -1;
    private static double mLongitude = -1;
    private final static String TAG = "BacklightService";
    private Context mContext;
    public static final String ACTION_UPDATE_BACKLIGHT_MODE =
            "android.intent.action.update.backlightmode";

    @Override
    public void onCreate() {
        super.onCreate();
        mContext = this;
        saveSunSetAanSunRiseTime();

        LocationManager locationManager =
                (LocationManager) getSystemService(LOCATION_SERVICE);
        if (locationManager != null) {
            locationManager.requestLocationUpdates(
                    LocationManager.GPS_PROVIDER, 2000, 500, mlocationListener);
        }
    }

    @Override
    public IBinder onBind(Intent arg0) {
        // 生命週期與系統一致,不需綁定到某個 Activity
        return null;
    }
}

二、計算並儲存日出日落時間

設定日期與經緯度後,呼叫天文計算類別取得日出、日落的時與分,再寫入系統設定並發送廣播:

private void saveSunSetAanSunRiseTime() {
    Calendar today = Calendar.getInstance();
    int year = today.get(Calendar.YEAR);
    int month = today.get(Calendar.MONTH);
    int day = today.get(Calendar.DAY_OF_MONTH);
    double mLatitude = 31.308928833333333;
    double mLongitude = 121.54332716666667;

    SunRisesAndSetsTime sun = new SunRisesAndSetsTime();
    if (year > 2000 && mLatitude != -1 && mLongitude != -1) {
        sun.setDate(year, month + 1, day);
        sun.setLat(mLatitude);
        sun.setLong(mLongitude);
        sun.init();

        int[] time1 = sun.getRiseTime();
        int riseHour = time1[0];
        int riseMinute = time1[1];

        int[] time2 = sun.getSetTime();
        int setHour = time2[0];
        int setMinute = time2[1];

        if (riseHour >= 0 && riseHour <= 23)
            Settings.System.putInt(mContext.getContentResolver(),
                    Settings.System.DAYTIME_HOUR, riseHour);
        if (riseMinute >= 0 && riseMinute <= 59)
            Settings.System.putInt(mContext.getContentResolver(),
                    Settings.System.DAYTIME_MINUTES, riseMinute);
        if (setHour >= 0 && setHour <= 23)
            Settings.System.putInt(mContext.getContentResolver(),
                    Settings.System.DARKNIGHT_HOUR, setHour);
        if (setMinute >= 0 && setMinute <= 59)
            Settings.System.putInt(mContext.getContentResolver(),
                    Settings.System.DARKNIGHT_MINUTES, setMinute);

        Intent i = new Intent(ACTION_UPDATE_BACKLIGHT_MODE);
        mContext.sendBroadcast(i);
    }
}

三、定位座標更新

當 GPS 回報新的位置時,把座標換算後重新計算日出日落時間:

private LocationListener mlocationListener = new LocationListener() {
    public void onLocationChanged(Location location) {
        if (location != null) {
            ChinaLocation china_lc = LocationUtils.wgtochina(
                    location.getLongitude(), location.getLatitude());
            mLongitude = china_lc.china_lng;
            mLatitude = china_lc.china_lat;
            saveSunSetAanSunRiseTime();
        }
    }

    public void onProviderDisabled(String provider) { }
    public void onProviderEnabled(String provider) { }
    public void onStatusChanged(String provider, int status, Bundle extras) { }
};

四、日出日落的天文計算核心

真正負責運算的是 SunRisesAndSetsTime 類別。它把日期與經緯度換算成太陽的黃經、赤緯等參數,透過迭代求解出日出(rise)與日落(set)的時刻,最後再轉成時、分輸出:

public class SunRisesAndSetsTime {
    private int days_of_month_1[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    private int days_of_month_2[] = { 31, 29, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
    private static final double h = -0.833;   // 太陽地平線俯角
    private static final double PI = 3.1415926;
    private static final double UTo = 180.0;

    private int latDegree, latDinute, latSecond;
    private int longDegree, longDinute, longSecond;
    private int year, month, date;
    private double glat, glong;
    private double rise, set;

    public void setDate(int mYear, int mMonth, int mDate) {
        year = mYear;
        month = mMonth;
        date = mDate;
    }

    public void setLat(double mLat) {
        latDegree = (int) mLat;
        double num1 = (mLat % 1) * 60;
        latDinute = (int) num1;
        latSecond = (int) ((num1 % 1) * 60);
    }

    public void setLong(double mLong) {
        longDegree = (int) mLong;
        double num1 = (mLong % 1) * 60;
        longDinute = (int) num1;
        longSecond = (int) ((num1 % 1) * 60);
    }

    boolean leap_year(int year) {
        return ((year % 400 == 0) || (year % 100 != 0) && (year % 4 == 0));
    }

    // 其餘 days、t_century、L_sun、G_sun、ecliptic_longitude、earth_tilt、
    // sun_deviation、GHA、e、UT_rise、UT_set、result_rise、result_set、Zone
    // 等方法,皆為天文公式的推導與迭代求解,此處省略。

    public int[] getRiseTime() {
        int[] times = new int[2];
        times[0] = (int) (rise / 15 + Zone(glong));
        times[1] = (int) (60 * (rise / 15 + Zone(glong)
                - (int) (rise / 15 + Zone(glong))));
        return times;
    }

    public int[] getSetTime() {
        int[] times = new int[2];
        times[0] = (int) (set / 15 + Zone(glong));
        times[1] = (int) (60 * (set / 15 + Zone(glong)
                - (int) (set / 15 + Zone(glong))));
        return times;
    }
}

由於日出日落時間會隨日期與所在經緯度而變,因此這個 Service 一邊用 GPS 持續追蹤位置,一邊依當天日期重新計算,就能長時間維持準確的日夜判斷,適合用來驅動自動背光或日夜模式切換等功能。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved