android - 如何获取应用所在的本地时间。正在运行,与设备时间无关?

标签 android time calendar

我在谷歌上搜索了很多,但仍然不成功,我想获取我的应用程序运行的本地时间。我可以使用日历来获取该信息,但我的问题是,当用户登录应用程序时我想读取正确的时间。这意味着实际上用户必须在 9:30 登录,但如果他迟到了 30 分钟。即使他将设备中的本地时间更改回 9:30,他也会登录应用程序。 (可能性)我想读取正确的时间(即 10:00 )。由于这个问题,我想获取全局时间,而不考虑设备时间。我也可以使用服务器来实现此目的,但有时应用程序。将没有互联网设施。

我怎样才能实现这个目标?

最佳答案

如果您的设备配备了 GPS,您可以从 GPS 获取正确的本地时间。用户无法更改 GPS 时间。 ;)

您可以强制用户打开 GPS,否则关闭您的应用程序。

location.getTime()

public long getTime () 
Since: API Level 1 
Returns the UTC time of this fix, in milliseconds since January 1, 1970.

更新:

在您的 Activity 中:

protected void btnGetPoint_onClick() {
        try {
            Intent intentToFire = new Intent(
                    ReceiverPositioningAlarm.ACTION_REFRESH_SCHEDULE_ALARM);
            intentToFire.putExtra(ReceiverPositioningAlarm.COMMAND,
                    ReceiverPositioningAlarm.SENDER_ACT_DOCUMENT);

            sendBroadcast(intentToFire);

            OnNewLocationListener onNewLocationListener = new OnNewLocationListener() {
                @Override
                public void onNewLocationReceived(Location location) {
                    try {
// do what you want

                    } catch (Exception e) {
                        MessageBox.showException(ActDocument.this, e);
                    }
                }
            };

            // start listening for new location
            ReceiverPositioningAlarm.setOnNewLocationListener(
                    onNewLocationListener);
        } catch (Exception e) {
//...
        }
    }

其界面:

import android.location.Location;

public interface OnNewLocationListener {
    public abstract void onNewLocationReceived(Location location);
}

GPS 接收器:

package org.mabna.order.receivers;

import java.util.ArrayList;

import org.mabna.order.utils.Farsi;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.location.GpsStatus;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.Gravity;
import android.widget.Toast;


public class ReceiverPositioningAlarm extends BroadcastReceiver {

    public static final String COMMAND = "SENDER";
    public static final int SENDER_ACT_DOCUMENT = 0;
    public static final int SENDER_SRV_POSITIONING = 1;
    public static final int MIN_TIME_REQUEST = 5 * 1000;
    public static final int MIN_DISTANCE = 10;// in meters

    public static final String ACTION_REFRESH_SCHEDULE_ALARM =
            "org.mabna.order.ACTION_REFRESH_SCHEDULE_ALARM";

    private static Location currentLocation;
    private static Location prevLocation;
    private static Context _context;
    private String provider = LocationManager.GPS_PROVIDER;
    private static LocationManager locationManager;
    private static LocationListener locationListener = new LocationListener() {

        @Override
        public void onStatusChanged(String provider, int status, Bundle extras) {
            try {
                String strStatus = "";
                switch (status) {
                case GpsStatus.GPS_EVENT_FIRST_FIX:
                    strStatus = "GPS_EVENT_FIRST_FIX";
                    break;
                case GpsStatus.GPS_EVENT_SATELLITE_STATUS:
                    strStatus = "GPS_EVENT_SATELLITE_STATUS";
                    break;
                case GpsStatus.GPS_EVENT_STARTED:
                    strStatus = "GPS_EVENT_STARTED";
                    break;
                case GpsStatus.GPS_EVENT_STOPPED:
                    strStatus = "GPS_EVENT_STOPPED";
                    break;

                default:
                    strStatus = String.valueOf(status);
                    break;
                }
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

        @Override
        public void onProviderEnabled(String provider) {
        }

        @Override
        public void onProviderDisabled(String provider) {
        }

        @Override
        public void onLocationChanged(Location location) {
            try {
                gotLocation(location);
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    };

    @Override
    public void onReceive(final Context context, Intent intent) {

        _context = context;

        locationManager = (LocationManager) context
                .getSystemService(Context.LOCATION_SERVICE);

        if (locationManager.isProviderEnabled(provider)) {
            locationManager.requestLocationUpdates(provider, MIN_TIME_REQUEST,
                    MIN_DISTANCE, locationListener);

            Location gotLoc = locationManager.getLastKnownLocation(provider);
            gotLocation(gotLoc);
        } else {
            Toast t = Toast.makeText(context,
                    Farsi.Convert("please turn the GPS on"),
                    Toast.LENGTH_LONG);
            t.setGravity(Gravity.CENTER, 0, 0);
            t.show();

            Intent settinsIntent = new Intent(
                    android.provider.Settings.ACTION_LOCATION_SOURCE_SETTINGS);
            settinsIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            _context.startActivity(settinsIntent);
        }
    }

    private static void gotLocation(Location location) {
        try {
            prevLocation = currentLocation == null ?
                    null : new Location(currentLocation);
            currentLocation = location;

            if (isLocationNew()) {
                // saveLocation(location);

                // informing the classes outside of this class that e new point
                // received
                OnNewLocationReceived(location);

                stopLocationListener();
            }
        } catch (Exception e) {
            Toast.makeText(_context,
                    "error" + e.getMessage(),
                    Toast.LENGTH_SHORT).show();
        }
    }

    private static boolean isLocationNew() {
        if (currentLocation == null) {
            return false;
        } else if (prevLocation == null) {
            return true;
        } else if (currentLocation.getTime() == prevLocation.getTime()) {
            return false;
        } else {
            return true;
        }
    }

    public static void stopLocationListener() {
        if (locationManager != null)
        {
            locationManager.removeUpdates(locationListener);
        }
    }

    // listener ----------------------------------------------------

    static ArrayList<OnNewLocationListener> arrOnNewLocationListener =
            new ArrayList<OnNewLocationListener>();

    // Allows the user to set a OnNewLocationListener outside of this class and
    // react to the event.
    // A sample is provided in ActDocument.java in method: startStopTryGetPoint
    public static void setOnNewLocationListener(
            OnNewLocationListener listener) {
        arrOnNewLocationListener.add(listener);
    }

    public static void clearOnNewLocationListener(
            OnNewLocationListener listener) {
        arrOnNewLocationListener.remove(listener);
    }

    // This function is called after the new point received
    private static void OnNewLocationReceived(Location location) {
        // Check if the Listener was set, otherwise we'll get an Exception when
        // we try to call it
        if (arrOnNewLocationListener != null) {
            // Only trigger the event, when we have any listener

            for (int i = arrOnNewLocationListener.size() - 1; i >= 0; i--) {
                arrOnNewLocationListener.get(i).onNewLocationReceived(
                        location);
            }
        }
    }
}

在 list 中:

<receiver android:name=".ReceiverPositioningAlarm" >

            <!-- this Broadcast Receiver only listens to the following intent -->
            <intent-filter >
                <action android:name="org.mabna.order.ACTION_REFRESH_SCHEDULE_ALARM" />
            </intent-filter>
        </receiver>

关于android - 如何获取应用所在的本地时间。正在运行,与设备时间无关?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10594228/

相关文章:

java - Android SharedPreferences 问题 - 从另一个类获取数据

javascript - 有人可以向我解释这个 JavaScript 实时时钟吗?

javascript - 如何在鼠标悬停时在完整日历中显示开始和结束时间?

javascript - 寻找生日的日期选择器而不是 jQuery UI Datepicker

java - 为什么 JodaTime 和 Calendar 返回不同的结果

android - Android Studio 的配置文件

安卓布局 : 1 imageview on fixed position and 2 imageviews fill up the remaining space

Android Build 使用 Proguard 和 Gradle 失败

algorithm - 不同的方式 int n 可以分成 1 或 2 组

PHP/MySQL 显示自用户上次登录以来的时间