I created an android app that has to set device's time because the device cannot remember time. don't know how to set device's time.
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();
}
}
Add these lines inside your Manifest file to request permission:
<uses-permission android:name="android.permission.SET_TIME"
tools:ignore="ProtectedPermissions" />
<permission android:name="android.permission.SET_TIME" android:protectionLevel="signature|system"/>
And inside your java code:
Calendar c = Calendar.getInstance();
c.set(year, month, day, hour, minutes, seconds);
AlarmManager am = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
am.setTime(c.getTimeInMillis());
Related
I have created a broadcast receiver that should run when date changes, but it does not work when I change date of my phone. But when I change action to Change time zone, it works fine. I change phone's time zone and it runs perfectly. How should I test DATE_CHANGED action?
this is how did I add the Broadcast receiver in Manifest:
<receiver android:name=".service.CheckVersionBroadcast"
android:enabled="true">
<intent-filter>
<action android:name="android.intent.action.DATE_CHANGED"/>
</intent-filter>
</receiver>
This is my Broadcast Receiver:
public class CheckVersionBroadcast extends BroadcastReceiver {
CheckVersion checkVersion;
String latestVersion;
#Override
public void onReceive(Context context, Intent intent) {
checkVersion = new CheckVersion();
try {
latestVersion = checkVersion.execute().get();
Toast.makeText(ApplicationLoader.applicationContext,latestVersion,Toast.LENGTH_SHORT).show();
if(!latestVersion.equals(BuildConfig.VERSION_NAME)){
ApplicationLoader loader = new ApplicationLoader();
long when = System.currentTimeMillis();
loader.setUpNotification(ApplicationLoader.applicationContext,when);
}
} catch (ExecutionException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
try {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
Date strDate = sdf.parse(date1);
String sDate1 = date2;
Date date1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").parse(sDate1);
if (date1.after(strDate)) {}
}catch(exception e){
}
I want to run Async Task in Android every intervals.
my interval is = { 15 min , 30 min , 1 hour ....etc
Depending on the users' choice.
When I start my application then I want to fetch my current time and after every n interval I want to execute Async Task
int intv = 15;
SimpleDateFormat sd = new SimpleDateFormat(
"HH:mm:ss");
Date date = new Date();
sd.setTimeZone(TimeZone.getTimeZone("GMT+05:30"));
System.out.println(sd.format(date));
String currenttime = sd.format(date);
Date myDateTime = null;
try
{
myDateTime = sd.parse(currenttime);
}
catch (ParseException e)
{
e.printStackTrace();
}
System.out.println("This is the Actual Date:"+sd.format(myDateTime));
Calendar cal = new GregorianCalendar();
cal.setTime(myDateTime);
cal.add(Calendar.MINUTE , intv ); //here I am adding Interval
System.out.println("This is Hours Added Date:"+sd.format(cal.getTime()));
try {
Date afterintv = sd.parse(sd.format(cal.getTime()));
if(afterintv.after(myDateTime)){ //here i am comparing
System.out.println("true..........");
new SendingTask().execute; //this is the function i have to execute
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
But I am not getting how to do.
If you want to run the AsyncTask after sometime you can use Thread.sleep in your AsyncTask. In this case is the SendingTask class. Here is a sample:
class SendingTask extends AsyncTask{
// Interval is in milliseconds
int interval = 1000;
public SendingTask(int interval) {
// Setting delay before anything is executed
this.interval = interval;
}
#Override
protected Object doInBackground(Object[] params) {
// Wait according to interval
try {
Thread.sleep(interval);
} catch (InterruptedException e) {
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Object o) {
super.onPostExecute(o);
// update UI and restart asynctask
textView3.setText("true..........");
new SendingTask(3000).execute();
}
}
I need to run a function only once (when it's night, change the image of the imageview) and when I use it in oncreate(), it runs every time I start the
activity.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
startAnim();
}
}
private void startAnim(){
Date dateNow=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yy-MM-dd HH:mm:ss");
String night=String.format("%tF",dateNow)+" 19:00:00";
try {
Date dateNight=sdf.parse(night);
if(dateNow.after(dateNight)){
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
int width = metric.widthPixels; // 屏幕宽度(像素)
int height = metric.heightPixels; // 屏幕高度(像素)
RotateAnimation ra=new RotateAnimation(0,100,width/2,height/2-80);
ra.setDuration(4000);
sunMoon.startAnimation(ra);
} catch (ParseException e) {
e.printStackTrace();
}
}
}
Either a file or store in a Shared Preference. Example for a save method:
private void saveLastRanTime(String key, long lastRunTime) {
SharedPreferences prefs = getApplicationContext().getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
SharedPreferences.Editor editor = prefs.edit();
editor.putLong(key, lastRunTime); // Store the key somewhere instead of passing in each time
editor.apply();
}
Example check:
private boolean wasLastRunToday(String keyOfPreference) {
SharedPreferences prefs = getApplicationContext().getSharedPreferences(getPackageName(), Context.MODE_PRIVATE);
long lastRanAt = prefs.getLong(keyOfPreference, -1); // Save key somewhere..
if (lastRanAt == -1) { // In the event it was never saved before.
return false;
}
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(lastRanAt);
int dayLastRanAt = cal.get(Calendar.DAY_OF_YEAR);
cal.setTimeInMillis(System.currentTimeMillis());
int today = cal.get(Calendar.DAY_OF_YEAR);
return today == dayLastRanAt;
}
Which would make your startAnim() method look more like:
private void startAnim() {
if (wasLastRunToday("LAST_ANIMIATION_RUNTIME")) {
return;
}
Date dateNow=new Date();
SimpleDateFormat sdf=new SimpleDateFormat("yy-MM-dd HH:mm:ss");
String night=String.format("%tF",dateNow)+" 19:00:00";
try {
Date dateNight=sdf.parse(night);
if(dateNow.after(dateNight)) {
DisplayMetrics metric = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metric);
int width = metric.widthPixels; // 屏幕宽度(像素)
int height = metric.heightPixels; // 屏幕高度(像素)
RotateAnimation ra=new RotateAnimation(0,100,width/2,height/2-80);
ra.setDuration(4000);
sunMoon.startAnimation(ra);
saveLastRanTime("LAST_ANIMIATION_RUNTIME", dateNow.getTime());
}
catch (ParseException e) {
e.printStackTrace();
}
}
}
Record the time of your last time running startAnim() in a file. Read this file when you start the activity to decide run startAnim() or not.
I am writing app to schedule SMS from alarm Manager. It works for me only one time and second time onwards it generate the multiple SMS.
Times are saved in SQL LITE and after send a SMS from Broadcast receiver read the DB and set the next alarm.
if 1 SMS has sent, second time it sends 2 SMS. next time 3 sms, and so on. I am using AmarmManager array and PendingIntents array to set alarm.
here is my coding... Please elp me... i am spending fer day for this taks..
public void SetAlarm(MessageInfo info, long delay, int amcount)
{
try
{
AlarmMSGInfo = info;
SaveMSGINFOPreference();
//Save Sent Status to Preference..
//savePreferences("SENT", old);
// register the alarm broadcast here
AMCount = amcount;
registerReceiver(mReceiver, new IntentFilter("com.rememberme.rm") );
//pendingIntent = PendingIntent.getBroadcast( this, 0, new Intent("com.techblogon.alarmexample"),0 );
pendingIntent[amcount] = PendingIntent.getBroadcast( RememberMe.this,amcount, new Intent("com.rememberme.rm"),PendingIntent.FLAG_ONE_SHOT );
alarmManager[amcount] = (AlarmManager)(this.getSystemService( Context.ALARM_SERVICE ));
alarmManager[amcount].set( AlarmManager.RTC_WAKEUP, delay , pendingIntent[amcount] );
}
catch(Exception e)
{
//Toast.makeText(RememberMe.this, e.toString(), Toast.LENGTH_LONG).show();
Toast.makeText(RememberMe.this, "Alarm cannot be set...", Toast.LENGTH_LONG).show();
}
}
This is my Broadcast receiver ..
private void RegisterAlarmBroadcast()
{
//This is the call back function(BroadcastReceiver) which will be call when your
//alarm time will reached.
mReceiver = new BroadcastReceiver()
{
private static final String TAG = "Alarm Example Receiver";
#Override
public void onReceive(Context context, Intent intent)
{
String s = intent.getAction().toString();
if(intent.getAction() != null )
{
Log.i(TAG,"BroadcastReceiver::OnReceive() >>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
//Toast.makeText(context, "Congrats!. Your Alarm time has been reached", Toast.LENGTH_LONG).show();
MessageInfo temp= LoadMSGINFOPreference();
if(temp == null )
{
}
else
{
String snt = loadSavedPreferences("SENT");
if(snt== "")
Sent = 0;
else
Sent = Integer.valueOf(snt);
int status = 0;
if(Sent == 0)
{
//MessageInfo SentInfo = dbHandler.Get_MessageInfo(Sent);
//status = SentInfo.getStatus();
//}
//Toast.makeText(RememberMe.this, String.valueOf(msgType) , Toast.LENGTH_LONG).show();
//if(status == 0)
//{
if(temp.getMSGType() == 1)
{
_Recipients = ReadPhoneNumbers(temp.getRecipients());
_Message = temp.getMessage();
for(String number:_Recipients)
{
try
{
String num = number;
//Toast.makeText(context, "Congrats!. Your Alarm time has been reached : " + num + ":", Toast.LENGTH_LONG).show();
sendSMS(num, _Message);
}
catch (Exception e)
{
Toast.makeText(getApplicationContext(), e.toString(),Toast.LENGTH_LONG).show();
//Toast.makeText(getApplicationContext(),"SMS faild, please try again later!",Toast.LENGTH_LONG).show();
e.printStackTrace();
}
}
alarmManager[AMCount].cancel(pendingIntent[AMCount]);
}
//Updaate te record to set status = 1...(SEND)
temp.setStatus(1);
dbHandler.Update_MessageInfo(temp);
savePreferences("SENT", String.valueOf(temp.getID()));
//take nearest Record from da DB.
MessageInfo minfo = new MessageInfo();
ArrayList<MessageInfo> msgInfo_array_from_db = dbHandler.Get_MessageInfos();
if(msgInfo_array_from_db.size() > 0)
{
minfo = GetLatestMSGInfo(msgInfo_array_from_db);
//Set tat record to alarm manager...
SetAlarm(minfo, minfo.getDelay(), temp.getID());
}
//}
}
}
};
}
private void SaveMSGINFOPreference()
{
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
Editor prefsEditor = sp.edit();
Gson gson = new Gson();
String json = gson.toJson(AlarmMSGInfo);
prefsEditor.putString("AlarmMSGInfo", json);
prefsEditor.commit();
}
I am trying to get Date from Datepicker, my code is below
dpResult = (DatePicker) findViewById(R.id.dpResult);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Calendar current = Calendar.getInstance();
gettingDate();
}
private void gettingDate() {
// TODO Auto-generated method stub
int day = dpResult.getDayOfMonth();
int month= dpResult.getMonth();
int year = dpResult.getYear();
SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy");
formatedDate = sdf.format(new Date(year, month, day));
// You can parse the String back to Date object by calling
try {
date = sdf.parse(formatedDate);
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Toast.makeText(getApplicationContext(), ""+formatedDate, 1000).show();
}
});
my toast shows date-month correctly but in year first two digits as 39 i.e like 3913,3914 etc please help me
you have to use this format for getting perfect and right year.
dpResult.getYear()-1900;
use dpResult.getYear()-1900
int year = dpResult.getYear();
Date is deprecated, you should use Calendar instead with the following syntax
Calendar cal = Calendar.getInstance()
cal.set(dpResult.getYear(), dpResult.getMonth()-1,getDayOfMonth())