我创建了一个必须设置设备时间的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();
}
}
答案 0 :(得分:0)
在清单文件中添加以下行以请求权限:
<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());