How can i activate the wifi when i decide the time? This is the code but for now i create the timepicker and the wifi option to turn it on is inside the picker so doesn't go. i want that if i decide in te time picker for example 3.00 AM at the 3.00 AM the wifi turns on.
package com.pkg.androidmemoryinfo;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import java.util.Calendar;
public class MainActivity extends Activity implements OnClickListener {
private Button mTimeButton;
private Calendar mCalen;
private int hourOfDay;
private int minute;
private int ampm;
private static final int Time_PICKER_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTimeButton = (Button) findViewById(R.id.time_button);
mCalen = Calendar.getInstance();
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
mTimeButton.setOnClickListener(this);
// Creating a memory_info Object
MemoryInfo memory_info = new MemoryInfo();
// Using Activity Manager System Service
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(memory_info);
// Assign Memory Value to free_memory Variable
long free_memory = memory_info.availMem / 1048576L;
// Display free Ram Memory
TextView memoryInfoView = (TextView) findViewById(R.id.device_memory_status_txt);
memoryInfoView.setText("Free RAM Memory :-"+ free_memory + " MB");
}
public void run() {
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
String ssid = info.getSSID();
TextView ssidTextView = (TextView) findViewById(R.id.wifiSSID);
ssidTextView.setText(ssid);
}
#Override
#Deprecated
protected Dialog onCreateDialog(int id) {
switch (id) {
case Time_PICKER_ID:
return new TimePickerDialog(this, TimePickerListener,
hourOfDay, minute, false);
}
return null;
}
private TimePickerDialog.OnTimeSetListener TimePickerListener =
new TimePickerDialog.OnTimeSetListener() {
// while dialog box is closed, below method is called.
public void onTimeSet(TimePicker view, int hour, int minute) {
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format = mCalen.get(Calendar.HOUR);
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
String ampmStr = (ampm == 0) ? "AM" : "PM";
// Set the Time String in Button
TextView dateInfoView = (TextView) findViewById(R.id.dateinfo);
dateInfoView.setText("L'attivazione del Wi-Fi è impostata per le ore: " + hour12format + " : " + minute + " / " + ampmStr);
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
}
};
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
showDialog(Time_PICKER_ID);
}
}
Thank you.
Related
I am able to find out the difference between two time intervals, but when the time 1st 12:00am or 00:00 and 2nd time is any other time, I am not getting accurate difference. Instead I am getting a negative difference. Upon debugging I figured out the time is actually taking of the year 1970 January. I am unable to correct it by taking today's time and calculate the difference.
package com.cksapp.memoryin;
import androidx.appcompat.app.AppCompatActivity;
import android.app.TimePickerDialog;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.google.firebase.Timestamp;
import com.google.firebase.firestore.FirebaseFirestore;
import com.google.firebase.firestore.FirebaseFirestoreSettings;
import java.security.CodeSigner;
import java.sql.Time;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
//import java.util.Date;
public class HourlyCalculator extends AppCompatActivity {
EditText wage;
TextView t1, t2, t3;
ImageView i1, i2;
Button b1;
int minutestotal;
String timex, timey;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.calculator_hourly);
wage = findViewById(R.id.hourlyrate);
t1 = findViewById(R.id.starttimetext);
t2 = findViewById(R.id.endtimetext);
t3 = findViewById(R.id.finaltime);
i1 = findViewById(R.id.startimage);
i2 = findViewById(R.id.endimage);
b1 = findViewById(R.id.calculatebutton);
Calendar c = Calendar.getInstance();
final int hour = c.get(Calendar.HOUR_OF_DAY);
final int mins = c.get(Calendar.MINUTE);
i1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final TimePickerDialog time = new TimePickerDialog(HourlyCalculator.this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay1, int minute1) {
timex = hourOfDay1 + ":" + minute1;
t1.setText(timex);
Log.d("Time1", timex);
}
},hour, mins, true);
time.show();
}
});
i2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final TimePickerDialog time2 = new TimePickerDialog(HourlyCalculator.this, new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
timey = hourOfDay + ":" + minute;
t2.setText(timey);
Log.d("Time1", timey);
}
},hour,mins,true);
time2.show();
}
});
b1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
try {
Date a = sdf.parse(timex);
Date b = sdf.parse(timey);
long difference = a.getTime() - b.getTime();
Log.d("Time", String.valueOf(difference));
/* minutestotal = (int) (difference/60000);
Log.d("Timearey", String.valueOf(minutestotal));
int totalwageinitital = Integer.parseInt(wage.getText().toString());
double totalwagepermin = totalwageinitital/60;
double finalprice = minutestotal * totalwagepermin;
t3.setText(String.valueOf(finalprice));*/
} catch (ParseException e) {
e.printStackTrace();
}
}
});
}
}
You are parsing the time using only hours and minutes, without providing the year, month and day the sdf will assume Jan 1st, 1970.
You should do this in a different way: initialize a calendar object for each date using Calendar.getInstance(), this will give you an instance with today's date, then set the hours and minutes for those 2 instances according to the hours and minutes in the picker and check the difference between their timeInMilliseconds.
Calendar time = Calendar.getInstance();
time.set(Calendar.HOUR_OF_DAY, hour);
time.set(Calendar.MINUTE, minute);
Hi i am currently working on application of reminder in android and using Firebase as database. My reminder is getting set properly without any issue but when i retrieve data from Firebase, i'am getting data of particular date but don't know how to ring it on time that user had entered.
This is my code :
Miscelleneous.java
package com.example.dell.reminder;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.support.annotation.NonNull;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.CalendarView;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.google.android.gms.tasks.OnCompleteListener;
import com.google.android.gms.tasks.Task;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DataSnapshot;
import com.google.firebase.database.DatabaseError;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import com.google.firebase.database.ValueEventListener;
import java.sql.Time;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
public class Miscelleneous extends Activity {
private static Button setting,resetting;
private EditText text;
private TextView rem1,date1,time1;
private FirebaseDatabase fdb;
private DatabaseReference db5;
private Button btn1,btn2;
private DatePickerDialog.OnDateSetListener dateSetListener;
private TimePickerDialog.OnTimeSetListener timeSetListener;
String strDate;
String timeString = "";
public static final String REM_KEY = "com.example.dell.reminder.REM_KEY";
public static final String DATE_KEY = "com.example.dell.reminder.DATE_KEY";
public static final String TIME_KEY = "com.example.dell.reminder.TIME_KEY";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.miscelleneous);
setting = (Button)findViewById(R.id.remset);
Toolbar tool = (Toolbar)findViewById(R.id.setreminder);
text = (EditText)findViewById(R.id.editText);
btn1 = (Button)findViewById(R.id.selectdate);
btn2 = (Button)findViewById(R.id.selecttime);
rem1 = (TextView)findViewById(R.id.rem1);
date1 = (TextView)findViewById(R.id.date1);
time1 = (TextView)findViewById(R.id.time11);
btn1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar cal = Calendar.getInstance();
int year = cal.get(Calendar.YEAR);
int month = cal.get(Calendar.MONTH);
int day = cal.get(Calendar.DAY_OF_MONTH);
DatePickerDialog dialog = new DatePickerDialog(Miscelleneous.this,
android.R.style.Theme_DeviceDefault_Dialog_MinWidth,dateSetListener,year,month,day);
//dialog.getWindow().setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
dialog.getDatePicker().setMinDate(System.currentTimeMillis()-1000);
dialog.show();
}
});
dateSetListener = new DatePickerDialog.OnDateSetListener() {
#Override
public void onDateSet(DatePicker datePicker, int year, int month, int day) {
// Log.d("Miscelleneous","OnDateSet: mm/dd/yyyy" +month + "/" + day + "/" + year);
Calendar calendar = Calendar.getInstance();
calendar.set(year, month, day);
month = month - 1;
SimpleDateFormat format = new SimpleDateFormat("dd/MM/yyyy");
strDate = format.format(calendar.getTime());
// date = day + "/" + month + "/" + year;
btn1.setText(strDate);
}
};
btn2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Calendar cal = Calendar.getInstance();
int hours = cal.get(Calendar.HOUR_OF_DAY);
int minute = cal.get(Calendar.MINUTE);
//int second = cal.get(Calendar.SECOND);
TimePickerDialog tdialog = new TimePickerDialog(Miscelleneous.this,
android.R.style.Theme_Holo_Light_Dialog,timeSetListener,hours,minute,false);
tdialog.show();
}
});
timeSetListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker timePicker, int hours_x, int minute_x) {
//String timeString = "";
if (hours_x == 0) {
timeString = "12:"+minute_x+" "+"a.m.";
btn2.setText(timeString);
} else if (hours_x < 12) {
timeString = hours_x + ":" + minute_x +" "+ "a.m.";
btn2.setText(timeString);
} else if (hours_x == 12) {
timeString = hours_x+":"+minute_x+" "+"p.m.";
btn2.setText(timeString);
} else {
timeString = hours_x-12+ ":" + minute_x +" "+"p.m.";
btn2.setText(timeString);
}
}
};
db5 = FirebaseDatabase.getInstance().getReference().child("user1");
setting.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if(text.getText().toString().isEmpty())
Toast.makeText(getApplicationContext(),"Please write something",Toast.LENGTH_LONG).show();
else if(btn1.getText().toString().isEmpty() && btn2.getText().toString().isEmpty()) {
Toast.makeText(getApplicationContext(),"Please select date and time",Toast.LENGTH_LONG).show();
}
else if(btn1.getText().toString().isEmpty()){
Toast.makeText(getApplicationContext(),"Please select date",Toast.LENGTH_LONG).show();
}
else if(btn2.getText().toString().isEmpty()){
Toast.makeText(getApplicationContext(),"Please select time",Toast.LENGTH_LONG).show();
}
else{
final HashMap<String,String> adddata = new HashMap<String, String>();
adddata.put("Reminder",text.getText().toString());
adddata.put("Date",btn1.getText().toString());
adddata.put("Time",btn2.getText().toString());
db5.child("Users Own").setValue(adddata).addOnCompleteListener(new OnCompleteListener<Void>() {
#Override
public void onComplete(#NonNull Task<Void> task) {
if(task.isSuccessful()){
Toast.makeText(getApplicationContext(),
"Reminder has been set successfully!!!",Toast.LENGTH_SHORT).show();
}else
{
Toast.makeText(getApplicationContext(),
"Problem in reminder setting !!",Toast.LENGTH_LONG).show();
}
}
});
retrive();
/*Intent intent = new Intent(Miscelleneous.this,History.class);
intent.putExtra(REM_KEY,validate1);
intent.putExtra(DATE_KEY,validate2);
intent.putExtra(TIME_KEY,validate3);
startActivity(intent);*/
//send();
}
}
});
}
/*private void send(){
final ArrayList<String> arrayList = new ArrayList<>();
arrayList.add(validate1);
arrayList.add(validate2);
arrayList.add(validate3);
Intent i = new Intent(Miscelleneous.this,History.class);
i.putExtra(REM_KEY,arrayList);
startActivity(i);
}*/
private void retrive(){
long current_date = System.currentTimeMillis();
long current_time = System.currentTimeMillis();
// String currentDateTimeString = DateFormat.getTimeInstance().format(new Date());
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
SimpleDateFormat sdf1 = new SimpleDateFormat("hh:mm a");
String System_Date = sdf.format(current_date);
final String System_Time = sdf1.format(current_time);
String usrdate = btn1.getText().toString().trim();
final String usrtime = btn2.getText().toString().toLowerCase().trim();
// Log.d("Miscelleneous",usrtime);
// Log.d("Miscelleneous",usrdate);
if( System_Date.equals(usrdate)){
db5.child("Users Own").addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(DataSnapshot dataSnapshot) {
String tim="",date="",remind="";
for (DataSnapshot cdata:dataSnapshot.getChildren()) {
remind = cdata.getValue(String.class).toString();
date = cdata.getValue(String.class).toString();
tim = cdata.getValue(String.class).toString();
}
if(usrtime.equals(System_Time)){
Log.d("Miscelleneous","actual reminder");
Log.d("Miscelleneous","Date:"+remind);
Log.d("Miscelleneous","Reminder:"+date);
Log.d("Miscelleneous","Time:"+tim);
rem1.setText("Reminder : "+remind);
date1.setText("Date : "+date);
time1.setText("Time : "+tim);
}
}
#Override
public void onCancelled(DatabaseError databaseError) {
}
});
//Toast.makeText(this,"User date matches with System date",Toast.LENGTH_SHORT).show();
}
else {
//Toast.makeText(this,"User date doesn't matches with System date",Toast.LENGTH_SHORT).show();
}
}
}
Can anyone give me a solution please,
Thanks
you can use AlarmManager to ringing or notify user at particular time.
private AlarmManager alarmManager;
private static Intent alarmIntent;
private static PendingIntent pendingAlarmIntent;
public void setTimings(){
private Calender alarmCalender = Calendar.getInstance();
alarmCalender.setTimeInMillis(System.currentTimeMillis());
alarmCalender.set(Calendar.HOUR_OF_DAY, "hour"); // hour=07
alarmCalender.set(Calendar.MINUTE, "minute"); // minute=01
alarmCalender.set(Calendar.SECOND, "second"); // second=0
alarmCalender.set(Calendar.MILLISECOND, "millisecond");//millisecond=0
setAlarm(AlarmManager.RTC_WAKEUP, alarmCalender, AlarmManager.INTERVAL_DAY);
}
public void setAlarm(int type, Calendar calendar, long timeInMillis){
alarmIntent = new Intent(context, yourBroadcastReciever.class);
pendingAlarmIntent = PendingIntent.getBroadcast(context, Constant.ALARM_REQUEST_CODE, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT);
alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.setRepeating(type, calendar.getTimeInMillis(), timeInMillis, pendingAlarmIntent);
}
To handle the alarm at particular time you create the Reciever
yourBroadcastReciever.class
#Override
public void onReceive(Context context, Intent intent) {
// here you handle the task when alarm ringing
}
[Note: Intent and Pending Intent is compulsory for create an Alarm]
use a broadcast receiver and set the time which you are getting.
I want to have one date and two time pickers in one dialog and I have done it, but the second time (Time to) is getting the same values as (time from). I have put some 'if cases' to try to fix it but didn't help. I get ("2016/10/27 5:41 0:00) even if I pick the time for the two "timepickers" I don't get the value for the second one or it duplicates the first one.
here is my code:
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import com.google.firebase.auth.FirebaseAuth;
import com.google.firebase.auth.FirebaseUser;
import com.google.firebase.database.DatabaseReference;
import com.google.firebase.database.FirebaseDatabase;
import java.util.Calendar;
public class AdminActivity extends AppCompatActivity implements View.OnClickListener, TimePickerDialog.OnTimeSetListener, DatePickerDialog.OnDateSetListener {
//firebase auth object
private FirebaseAuth firebaseAuth;
//view objects
private TextView textViewUserEmailadmin;
private Button buttonLogout;
private DatabaseReference databaseReference;
private EditText editTextinfo;
private TextView Textpass;
private Button buttonSave;
int day, month, year, hour, minute,hour1,minute1;
int dayFinal, monthFinal, yearFinal, hourFinal, minuteFinal,hourFinal1,minuteFinal1;
int i = 0;
Button btnDatePicker;
String a="";
String b="";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_admin);
//initializing firebase authentication object
firebaseAuth = FirebaseAuth.getInstance();
//if the user is not logged in
//that means current user will return null
if (firebaseAuth.getCurrentUser() == null) {
//closing this activity
finish();
//starting login activity
startActivity(new Intent(this, LoginActivity.class));
}
databaseReference = FirebaseDatabase.getInstance().getReference();
editTextinfo = (EditText) findViewById(R.id.editText3);
buttonSave = (Button) findViewById(R.id.buttonSave);
//getting current user
FirebaseUser user = firebaseAuth.getCurrentUser();
//initializing views
textViewUserEmailadmin = (TextView) findViewById(R.id.textViewUserEmailAdmin);
buttonLogout = (Button) findViewById(R.id.buttonLogout);
//displaying logged in user name
textViewUserEmailadmin.setText("Welcome admin " + user.getEmail());
//adding listener to button
buttonLogout.setOnClickListener(this);
buttonSave.setOnClickListener(this);
btnDatePicker = (Button) findViewById(R.id.btn_date);
// btnTimeFrom = (Button) findViewById(R.id.btn_time_from);
// btnTimeTo = (Button) findViewById(R.id.btn_time_to);
Textpass = (TextView) findViewById(R.id.Textviewpass);
btnDatePicker.setOnClickListener(this);
}
private void saveUserInformation() {
String info = editTextinfo.getText().toString().trim();
String pass = Textpass.getText().toString().trim();
i++;
UserInformation UserInformation = new UserInformation(info, pass);
// FirebaseUser user = firebaseAuth.getCurrentUser();
//databaseReference.child(user.getUid()+i++).setValue(UserInformation);
databaseReference.child("tidnr" + i).setValue(UserInformation);
Toast.makeText(this, "Information saved...", Toast.LENGTH_SHORT).show();
}
#Override
public void onClick(View view) {
//if logout is pressed
if (view == buttonLogout) {
//logging out the user
firebaseAuth.signOut();
//closing activity
finish();
//starting login activity
startActivity(new Intent(this, LoginActivity.class));
}
if (view == buttonSave) {
saveUserInformation();
}
if (view == btnDatePicker) {
if(a == "" && b == "") {
Calendar c = Calendar.getInstance();
day = c.get(Calendar.DAY_OF_MONTH);
month = c.get(Calendar.MONTH);
year = c.get(Calendar.YEAR);
DatePickerDialog datePickerDialog = new DatePickerDialog(AdminActivity.this, AdminActivity.this, year, month, day);
datePickerDialog.show();
}
}
}
#Override
public void onDateSet(DatePicker datePicker, int i, int i1, int i2) {
yearFinal=i;
monthFinal=i1 +1;
dayFinal= i2;
Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minute = c.get(Calendar.MINUTE);
if(a == "" && b == "") {
android.text.format.DateFormat dateFormat = new android.text.format.DateFormat();
//is24HourFormat = dateFormat.is24HourFormat(this);
TimePickerDialog timePickerDialog = new TimePickerDialog(AdminActivity.this, AdminActivity.this,
hour, minute, dateFormat.is24HourFormat(this));
timePickerDialog.show();
}
}
#Override
public void onTimeSet(TimePicker view, int i, int i1) {
hourFinal = i;
minuteFinal = i1;
String curTime = String.format("%02d",minuteFinal);
if(a == "" && b == ""){
a = yearFinal+"/"+monthFinal+"/"+dayFinal+" "+hourFinal+":"+curTime;
}
if(a != "" && b == "" ) {
Calendar c1 = Calendar.getInstance();
hour1 = c1.get(Calendar.HOUR_OF_DAY);
minute1 = c1.get(Calendar.MINUTE);
android.text.format.DateFormat dateFormat1 = new android.text.format.DateFormat();
//is24HourFormat = dateFormat.is24HourFormat(this);
TimePickerDialog timePickerDialog1 = new TimePickerDialog(AdminActivity.this, AdminActivity.this,
hour1, minute1, dateFormat1.is24HourFormat(this));
timePickerDialog1.show();
String curTime1 = String.format("%02d",minuteFinal1);
b = a+" "+hourFinal1+":"+curTime1;
a="";
Textpass.setText(b);
Toast.makeText(this, "test.", Toast.LENGTH_SHORT).show();
}
}
}
Replace this line
String curTime1 = String.format("%02d",minuteFinal1);
b = a+" "+hourFinal1+":"+curTime1;
with:
String curTime1 = String.format("%02d",minute1);
b = a+" "+hour1+":"+curTime1;
Well, my application would display wifi information (still work in progress for this) and set with a time picker when the wifi turns on. The problem is that i don't know how to connect the button inside the dialog of the picker "set" at the AlarmManager method. This is the code
package com.pkg.androidmemoryinfo;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.MemoryInfo;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.content.Context;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
import java.util.Calendar;
public class MainActivity extends Activity implements OnClickListener {
private Button mTimeButton;
private Calendar mCalen;
private int hourOfDay;
private int minute;
private int ampm;
private static final int Time_PICKER_ID = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTimeButton = (Button) findViewById(R.id.time_button);
mCalen = Calendar.getInstance();
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
mTimeButton.setOnClickListener(this);
// Creating a memory_info Object
MemoryInfo memory_info = new MemoryInfo();
// Using Activity Manager System Service
ActivityManager activityManager = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
activityManager.getMemoryInfo(memory_info);
// Assign Memory Value to free_memory Variable
long free_memory = memory_info.availMem / 1048576L;
// Display free Ram Memory
TextView memoryInfoView = (TextView) findViewById(R.id.device_memory_status_txt);
memoryInfoView.setText("Free RAM Memory :-"+ free_memory + " MB");
}
public void run() {
WifiManager wifi = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo info = wifi.getConnectionInfo();
String ssid = info.getSSID();
TextView ssidTextView = (TextView) findViewById(R.id.wifiSSID);
ssidTextView.setText(ssid);
}
#Override
#Deprecated
protected Dialog onCreateDialog(int id) {
switch (id) {
case Time_PICKER_ID:
return new TimePickerDialog(this, TimePickerListener,
hourOfDay, minute, false);
}
return null;
}
private TimePickerDialog.OnTimeSetListener TimePickerListener =
new TimePickerDialog.OnTimeSetListener() {
// while dialog box is closed, below method is called.
public void onTimeSet(TimePicker view, int hour, int minute) {
mCalen.set(Calendar.HOUR_OF_DAY, hour);
mCalen.set(Calendar.MINUTE, minute);
int hour12format = mCalen.get(Calendar.HOUR);
hourOfDay = mCalen.get(Calendar.HOUR_OF_DAY);
minute = mCalen.get(Calendar.MINUTE);
ampm = mCalen.get(Calendar.AM_PM);
String ampmStr = (ampm == 0) ? "AM" : "PM";
// Set the Time String in Button
TextView dateInfoView = (TextView) findViewById(R.id.dateinfo);
dateInfoView.setText("L'attivazione del Wi-Fi è impostata per le ore: " + hour12format + " : " + minute + " / " + ampmStr);
/// Here is the problem: Where have i to put this? ///
WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiManager.setWifiEnabled(true);
}
};
#SuppressWarnings("deprecation")
#Override
public void onClick(View v) {
showDialog(Time_PICKER_ID);
}
}
As you can see i don't know how put the wifi control. How can i do it? How can i create an AlarmManager with my code? I Need an example if possible. Thanks
This is one example of time picker that I think you can use.
--------Main Activity-------
package com.example.chxboxtest;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener {
private Button start_intent_button;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start_intent_button = (Button) findViewById(R.id.start_intent_button);
start_intent_button.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_intent_button: {
Intent intent = new Intent(this,TimePickerTest.class);
startActivity(intent);
}
break;
}
}
}
-------------Main Activity XML-----------------
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<Button
android:id="#+id/start_intent_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Start Intent Time Picker"
android:layout_centerInParent="true"
/>
</RelativeLayout>
-------------TimePicker class ---------------
package com.example.chxboxtest;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;
public class TimePickerTest extends Activity implements OnClickListener{
private CheckBox cBox;
private TimePicker tPicker;
private TextView showTime;
private Button done;
private String hour;
private String minute;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.time_picker_layout);
initButtons();
}
private void initButtons() {
tPicker = (TimePicker) findViewById(R.id.time_picker);
showTime = (TextView) findViewById(R.id.get_time);
done = (Button)findViewById(R.id.done);
cBox = (CheckBox) findViewById(R.id.time_picker_checkbox);
cBox.setOnClickListener(this);
done.setOnClickListener(this);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
//If check enable or disble timePicker
case R.id.time_picker_checkbox: {
if (((CheckBox) v).isChecked()) {
Toast.makeText(this, "CHECKED", Toast.LENGTH_SHORT).show();
tPicker.setEnabled(false);
} else {
Toast.makeText(this, "NOT CHECKED", Toast.LENGTH_SHORT).show();
tPicker.setEnabled(true);
}
}
break;
//If Done button pressed get time selected by user
case R.id.done:{
tPicker.clearFocus();
// re-read the values, in my case i put them in a Time object.
hour = tPicker.getCurrentHour().toString();
minute = tPicker.getCurrentMinute().toString();
if(tPicker.getCurrentMinute().intValue() < 10){
String setTimeText = hour+ " : " + "0" + minute;
showTime.setText(setTimeText);
}else{
String setTimeText = hour+ " : " + minute;
showTime.setText(setTimeText);
}
}
break;
default:
break;
}
}
}
-------------TimerPicker XML------------
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/timer_textview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/time_picker"
android:layout_toRightOf="#+id/time_picker_checkbox"
android:text="Check this to Cancel Alarm" />
<CheckBox
android:id="#+id/time_picker_checkbox"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_above="#+id/time_picker"
android:layout_centerHorizontal="true" />
<TimePicker
android:id="#+id/time_picker"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true" />
<Button
android:id="#+id/done"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="#+id/time_picker"
android:layout_centerHorizontal="true"
android:gravity="center"
android:text="Done" />
<TextView
android:id="#+id/get_time"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:gravity="center_horizontal"
android:text="Time"
android:textColor="#FF0000"
android:textSize="25sp" />
</RelativeLayout>
-------------Manifest.xml-----------
**<activity
android:name="com.example.chxboxtest.TimePickerTest"
android:configChanges="orientation|keyboardHidden">
</activity>**
Dont forget to add TimePicker class as activity.
BestPracice add all xml text in strings.xml
Cheers
I am trying to update a service from an activity. The Activity saves data to the sql lite database on the phone when the user clicks on a button. What I would like to do here, is when this button is clicked, the service is refreshed and uses the new data.
I was using start/stopservice on the button, but the app crashes and skips around to different activities.
I thought my question was similar to Android: Update / Refresh a running service and
Broadcast Receiver within a Service
However, I'm not updating a widget or another android native component. The service is a custom class.
Please note that a Broadcast receiver starts this service on Boot of the phone.
Also, Logcat window dosen't scroll the readouts. It jerks up and down. So I don't have an error log to show you.
How do I create a function that would allow the service to update when the user clicks on the button in an activity?
Here is my activity (button is at the bottom):
import java.sql.Timestamp;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import org.joda.time.DateTime;
import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningServiceInfo;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;
import com.google.android.gcm.demo.app.R;
import com.google.android.gcm.demo.app.EventList.DataView;
import com.google.android.gcm.demo.app.EventList.EventDetails;
import com.google.android.gcm.demo.app.sqllite.DatabaseSqlite;
public class AlertDetails extends Activity {
Integer id;
String name;
String date;
String startTime;
String endTime;
String location;
int alertState;
Bundle bundle;
String alertTime;
String s;
private TextView mTitleDisplay;
private TextView mDateDisplay;
private TextView mTimeDisplay;
private TextView mTimeEndDisplay;
private TextView mLocationDisplay;
private TextView mAlertDisplay;
private String update_alarmTime;
String eventYear;
String eventDay;
String eventMonth;
String eventdate;
Context context;
Intent alarmServiceControl;
DatabaseSqlite entry = new DatabaseSqlite(AlertDetails.this);
// Intent startServiceIntent = new Intent(context, AlarmsService.class);
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alertview);
bundle = getIntent().getExtras();
id = bundle.getInt("id");
name = bundle.getString("eventName");
date = bundle.getString("date");
startTime = bundle.getString("startTime");
endTime = bundle.getString("endTime");
location = bundle.getString("location");
alertState = bundle.getInt("alertState");
alertTime = bundle.getString("alertTime");
alertTime = "10:00:00";// need to be hooked up correctly to get the right
// capture our View elements
mTitleDisplay = (TextView) findViewById(R.id.titleDisplay);
mDateDisplay = (TextView) findViewById(R.id.dateDisplay);
mTimeDisplay = (TextView) findViewById(R.id.timeDisplay);
mTimeEndDisplay = (TextView) findViewById(R.id.timeEndDisplay);
mLocationDisplay = (TextView) findViewById(R.id.locationDisplay);
mAlertDisplay = (TextView) findViewById(R.id.alertDisplay);
// set start
mTimeDisplay.setText(startTime);
mTimeEndDisplay.setText(endTime);
// set title
mTitleDisplay.setText(name);
// set Date
eventYear = date.substring(0, 4);
eventDay = date.substring(5, 7);
eventMonth = date.substring(8, 10);
mDateDisplay.setText(eventDay + "-" + eventMonth + "-" + eventYear);
eventdate = eventDay + "/" + eventMonth + "/" + eventYear;
// set location
mLocationDisplay.setText(location);
if (alertState == 0) {
entry.open();
mAlertDisplay.setText("Alert is ON and Set to " +entry.getAlert(id));
entry.close();
}
if (alertState == 1) {
mAlertDisplay.setText("Alert is OFF");
}
Button button1 = (Button) findViewById(R.id.btnSetAlert);
button1.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (alertState == 0) {
alertState++;
mAlertDisplay.setText("Alert is OFF");
entry.open();
entry.updateAlertState(id, alertState);
entry.close();
} else {
//turn alarm on
entry.open();
mAlertDisplay.setText("Alert is ON and Set to " +entry.getAlert(id));
alertState = 0;
entry.updateAlertState(id, alertState);
entry.close();
}
// TODO check if service is running
stopService(new Intent(AlertDetails.this,
AlarmsService.class));
startService(new Intent(AlertDetails.this,
AlarmsService.class));
Intent intent = new Intent(AlertDetails.this,
AlertView.class);
startActivity(intent);
}
});
}
}
Here is the service I'd like to update:
package com.google.android.gcm.demo.app.Alerts;
import java.util.Calendar;
import java.util.List;
import com.google.android.gcm.demo.app.sqllite.DatabaseSqlite;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class AlarmsService extends Service {
DatabaseSqlite db = new DatabaseSqlite(this);
List<Alerts> listAlerts;
PendingIntent pendingIntent;
String tag = "alerttService";
#Override
public void onCreate() {
super.onCreate();
Toast.makeText(this, "Created from Alerts service ...",
Toast.LENGTH_LONG).show();
Log.i(tag, "Service created...");
}
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("TAG", "started onstart command Created from Alerts service .");
return super.onStartCommand(intent, flags, startId);// START_STICKY;
}
#Override
public void onStart(final Intent intent, int startId) {
super.onStart(intent, startId);
Toast.makeText(this, "Created from Alerts service started...",
Toast.LENGTH_LONG).show();
Log.i(tag, "Service started. ..");
// for looops
Thread thread = new Thread() {
#Override
public void run() {
Boolean x = true;
while (x) {
db.open();
listAlerts = db.getAlarmsForService();
db.close();
int alerts=listAlerts.size();
for (int i = 0; i < alerts; i++) {
Alerts item = listAlerts.get(i);
item.getRowId();
item.getRemoteServerId();
String alertInMills = item.getAlertDateInMills();
String alertDuration = item.getAlertDurationInMinutes();
String eventName = item.getEventName();
// intent.putExtra("eventState", item.getEventState());
// intent.putExtra("startTime", item.getStartTime());
// intent.putExtra("alertState", item.getAlertState());
// intent.putExtra("eventName", item.getEventName());
// intent.putExtra("location", item.getLocation());
// intent.putExtra("alertTime", item.getAlertTime());
// intent.putExtra("date", item.getDate());
long longAlertInMills = Long.parseLong(alertInMills);
pendingIntent = PendingIntent.getService(AlarmsService.this, 0,intent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar calendar = Calendar.getInstance();
// go to data base for time in mills
calendar.setTimeInMillis(longAlertInMills);
alarmManager.set(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
pendingIntent);
//
System.out.println(calendar.toString());
}
//
System.out.println("thread");
x = false;
}
}
};
thread.start();
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service destroyed...", Toast.LENGTH_LONG).show();
}
#Override
public IBinder onBind(Intent intent) {
return null;
}
}
BroadCast Receiver:
package com.google.android.gcm.demo.app.Alerts;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.util.Log;
public class AlarmsBroadcastReceiver extends BroadcastReceiver {
private static final String TAG = "BootReceiver";
Intent startServiceIntent;
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
startServiceIntent = new Intent(context, AlarmsService.class);
context.startService(startServiceIntent);
Log.d("TAG", "alarmBroadcastReceiver");
System.out.println("alarm broadcast ...");
}
}
}