【问题标题】:How can I set device time by my Android App如何通过我的 Android 应用设置设备时间
【发布时间】:2018-11-26 13:53:15
【问题描述】:

我创建了一个必须设置设备时间的 Android 应用,因为设备无法记住时间。不知道如何设置设备的时间。

Date c = Calendar.getInstance().getTime();
SimpleDateFormat df = new SimpleDateFormat("dd-MMM-yyyy 
HH:mm:ss");
String formattedDate = df.format(c);

SharedPreferences time = getSharedPreferences("PREFS",0);

Date Time = null;
try {
    Time = df.parse(time.getString("time",""));
} catch (ParseException e) {
    e.printStackTrace();
}
if (Time == null)
{
    SharedPreferences.Editor editor = time.edit();
    editor.putString("time", formattedDate);
    editor.apply();
    Toast.makeText(MainActivity.this, formattedDate, 
    Toast.LENGTH_SHORT).show();
}
else
{
    try {
        if (Time.before(df.parse(formattedDate)))
        {
            SharedPreferences.Editor editor = time.edit();
            editor.putString("time", formattedDate);
            editor.apply();

            **** I want set device's time here from "time"
        }
        if (Time.after(df.parse(formattedDate)))
        {
            **** I want set device's time here from "time"
        }
    } catch (ParseException e) {
        e.printStackTrace();
    }
}

【问题讨论】:

  • 你能发布任何以前的试用代码吗?
  • 感谢我已经编辑了我的问题。
  • 迈克速度。我已经看到了该解决方案,但它对我不起作用。

标签: android


【解决方案1】:

在您的清单文件中添加这些行以请求权限:

<uses-permission android:name="android.permission.SET_TIME"
        tools:ignore="ProtectedPermissions" />
    <permission android:name="android.permission.SET_TIME" android:protectionLevel="signature|system"/>

在你的 java 代码中:

Calendar c = Calendar.getInstance();
    c.set(year, month, day, hour, minutes, seconds);
    AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    am.setTime(c.getTimeInMillis());

【讨论】:

  • 在此之后我看到这样的错误。 E / BoostFramework:BoostFramework():Exception_1 = java.lang.ClassNotFoundException:在路径上找不到类“com.qualcomm.qti.Performance”:DexPathList [[],nativeLibraryDirectories = [/system/lib,/vendor/lib ]] droidRuntime:致命异常:主进程:com.kakda.clock,PID:6506 java.lang.SecurityException:setTime:用户 10526 和当前进程都没有 android.permission.SET_TIME。
  • 你可以去settings->apps->choose your app->permissions并把权限添加到你的app吗?
  • 我的应用中有日历权限,我已经允许了,但还是不行。
  • 好的,我将创建一个示例项目进行测试,并让您知道和/或相应地更新答案。感谢您的反馈
  • 是的,我在等你的样品。谢谢。
猜你喜欢
  • 2015-06-12
  • 1970-01-01
  • 1970-01-01
  • 2012-04-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多