I have a problem with my code. i first create an alarm with a notification,Then I set the alarm for the following times - 6AM, 12PM and 6PM. However when I run the application, the alarm is always on,and does not go on at 6AM, 12PM and 6PM. The notifications are also not on time. Im using toggle button.
My code :
AlarmFragmen.java`
public class AlarmFragment extends Fragment {
private static final String ARG_PARAM1 = "param1";
private static final String ARG_PARAM2 = "param2";
private String mParam1;
private String mParam2;
private PendingIntent pendingIntent;
private TextView textViewEnamPagi, textViewDuabelas, textViewenamSore, textResult;
private ToggleButton toggleButtonEnamPagi, toggleButtonDuaBelas, toggleButtonEnamSore;
public AlarmFragment() {
}
public static AlarmFragment newInstance(String param1, String param2) {
AlarmFragment fragment = new AlarmFragment();
Bundle args = new Bundle();
args.putString(ARG_PARAM1, param1);
args.putString(ARG_PARAM2, param2);
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (getArguments() != null) {
mParam1 = getArguments().getString(ARG_PARAM1);
mParam2 = getArguments().getString(ARG_PARAM2);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_alarm, container, false);
toggleButtonEnamPagi = (ToggleButton) v.findViewById(R.id.toggleButton);
textViewEnamPagi = (TextView) v.findViewById(R.id.textViewEnamPagi);
textViewDuabelas = (TextView) v.findViewById(R.id.textView);
textViewenamSore = (TextView) v.findViewById(R.id.textEnamSore);
toggleButtonDuaBelas = (ToggleButton) v.findViewById(R.id.toggleButton2);
toggleButtonEnamSore = (ToggleButton) v.findViewById(R.id.toggleEnamSore);
textViewEnamPagi.setText("OFF Pukul 06.00 AM");
textViewDuabelas.setText("OFF Pukul 12.00 PM");
textViewenamSore.setText("OFF Pukul 18.00 PM");
startSix();
startDuaBelas();
startEnamSore();
toggleButtonEnamPagi.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(toggleButtonEnamPagi.isChecked()){
textViewEnamPagi.setText("ON Pukul 06.00 AM");
SharedPreferences preferences = getActivity().getPreferences(1);
SharedPreferences.Editor edt = preferences.edit();
edt.putBoolean("tgEnam", true);
edt.commit();
}else {
textViewEnamPagi.setText("OFF Pukul 06.00 AM");
SharedPreferences preferences = getActivity().getPreferences(1);
SharedPreferences.Editor edt = preferences.edit();
edt.putBoolean("tgEnam", false);
edt.commit();
}
}
});
toggleButtonDuaBelas.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(toggleButtonDuaBelas.isChecked()){
textViewDuabelas.setText("ON Pukul 12.00 PM");
SharedPreferences preferences = getActivity().getPreferences(0);
SharedPreferences.Editor edt = preferences.edit();
edt.putBoolean("tgDuabelas", true);
edt.commit();
}else{
textViewDuabelas.setText("OFF Pukul 12.00 PM");
SharedPreferences preferences = getActivity().getPreferences(0);
SharedPreferences.Editor edt = preferences.edit();
edt.putBoolean("tgDuabelas", false);
edt.commit();
}
}
});
toggleButtonEnamSore.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(toggleButtonEnamSore.isChecked()){
SharedPreferences preferences = getActivity().getPreferences(0);
SharedPreferences.Editor edt = preferences.edit();
edt.putBoolean("tgEnamsore", true);
edt.commit();
}else{
SharedPreferences preferences = getActivity().getPreferences(0);
SharedPreferences.Editor edt = preferences.edit();
edt.putBoolean("tgEnamsore", false);
edt.commit();
}
}
});
return v;
}
public void startSix(){
SharedPreferences preferences = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean tgenam = preferences.getBoolean("tgEnam", true);
if(tgenam == true){
textViewEnamPagi.setText("ON Pukul 06.00 AM");
toggleButtonEnamPagi.setChecked(true);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 6);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date date = calendar.getTime();
Intent myIntent = new Intent(getActivity().getApplication(), MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getActivity().getApplication(), 0, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, date.getTime(), pendingIntent);
}
}
public void startDuaBelas() {
SharedPreferences preferences = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean tgduabelas = preferences.getBoolean("tgDuabelas", true);
if (tgduabelas == true) {
textViewDuabelas.setText("ON Pukul 12.00 PM");
toggleButtonDuaBelas.setChecked(true);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 12);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date date = calendar.getTime();
Intent myIntent = new Intent(getActivity().getApplication(), MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getActivity().getApplication(), 1, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, date.getTime(), pendingIntent);
}
}
public void startEnamSore() {
SharedPreferences preferences = getActivity().getPreferences(Context.MODE_PRIVATE);
boolean tgenamsore = preferences.getBoolean("tgEnamsore", true);
if (tgenamsore == true) {
textViewenamSore.setText("ON Pukul 18.00 PM");
toggleButtonEnamSore.setChecked(true);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, 18);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.SECOND, 0);
Date date = calendar.getTime();
Intent myIntent = new Intent(getActivity().getApplication(), MyReceiver.class);
pendingIntent = PendingIntent.getBroadcast(getActivity().getApplication(), 2, myIntent, 0);
AlarmManager alarmManager = (AlarmManager) getActivity().getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, date.getTime(), pendingIntent);
}
}
And MyReceiver.java
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Intent service1 = new Intent(context, AlarmFragment.class);
service1.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startService(service1);
Intent myIntent = new Intent(context, MyAlarmService.class);
context.startService(myIntent);
}
AlarmService.java
public class MyAlarmService extends Service{
NotificationManager manager;
Notification myNotication;
private NotificationManager mManager;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate()
{
// TODO Auto-generated method stub
super.onCreate();
}
#TargetApi(Build.VERSION_CODES.JELLY_BEAN)
#SuppressWarnings("static-access")
#Override
public void onStart(Intent intent, int startId)
{
super.onStart(intent, startId);
manager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mManager = (NotificationManager) this.getApplicationContext().getSystemService(this.getApplicationContext().NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(),MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity( this.getApplicationContext(),0, intent1,PendingIntent.FLAG_CANCEL_CURRENT);
Notification.Builder builder = new Notification.Builder(MyAlarmService.this);
builder.getNotification().flags = Notification.FLAG_AUTO_CANCEL;
builder.setAutoCancel(true);
builder.setTicker("this is ticker text");
builder.setContentTitle("Alarm ON");
builder.setContentText("Wake UP");
builder.setSmallIcon(R.drawable.image);
builder.setContentIntent(pendingIntent);
//builder.setOngoing(true);
builder.setSubText("Time to code"); //API level 16
builder.setNumber(1);
builder.build();
builder.setVibrate(new long[]{1000,1000,1000,1000,1000});
Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.song);
builder.setSound(uri);
myNotication = builder.getNotification();
manager.notify(0, myNotication);
}
#Override
public void onDestroy()
{
// TODO Auto-generated method stub
super.onDestroy();
}
}
Please help me to solve my problem, thx
Related
I have an alarm aplication, where i want an int to be passed to the Alarm Receiver with an intent, but for some Reason, the AlarmReceiver class does not get the intent. The int gets Enterd by an EditText
here the Variables were created in MainActivity
private int intToPass;
public static final String MyPREFERENCES = "MyPrefs";
private static long intervall = 500;
private String myEnteredText;
private AlarmManager am;
private Intent intent;
private PendingIntent pendingIntent;
here is the code for the set alarm button in MainActivity:
mStartBtn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//Variables
AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE);
long time;
intent = new Intent(MainActivity.this, AlarmReceiverActivity.class);
pendingIntent = PendingIntent.getActivity(MainActivity.this, 2, intent, PendingIntent.FLAG_CANCEL_CURRENT);
am = (AlarmManager) getSystemService(ALARM_SERVICE);
//Save
SharedPreferences prefs = getSharedPreferences(MyPREFERENCES, Context.MODE_PRIVATE);
myEnteredText = scoreEnter.getText().toString();
SharedPreferences.Editor editor = prefs.edit();
editor.putString("sharedPrefKey", myEnteredText);
editor.apply();
if (((ToggleButton) view).isChecked()) {
try {
intToPass = Integer.parseInt(scoreEnter.getText().toString());
//Calendar
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, timePicker1.getCurrentHour());
calendar.set(Calendar.MINUTE, timePicker1.getCurrentMinute());
//Extra
intent.putExtra("Test", intToPass);
//hour format
time = (calendar.getTimeInMillis() - (calendar.getTimeInMillis() % 60000));
if (System.currentTimeMillis() > time) {
if (calendar.AM_PM == 0)
time = time + (1000 * 60 * 60 * 12);
else
time = time + (1000 * 60 * 60 * 24);
}
//Set alarm
am.setRepeating(AlarmManager.RTC_WAKEUP, time, intervall, pendingIntent);
if (mToast != null) {
mToast.cancel();
}
mToast = Toast.makeText(getApplicationContext(), "Alarm Set", Toast.LENGTH_LONG);
mToast.show();
} catch (NumberFormatException nfe) {
mToast = Toast.makeText(MainActivity.this, "Enter number", Toast.LENGTH_LONG);
mToast.show();
((ToggleButton) view).setChecked(false);
}
} else {
if (am!=null){
repam.cancel(pendingIntent);
Toast.makeText(MainActivity.this, "ALARM OFF", Toast.LENGTH_SHORT).show();
}
}
}
});
This is the AlarmReceiver class
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
mWakelock = pm.newWakeLock(PowerManager.FULL_WAKE_LOCK, "wecker:myWakeLog");
mWakelock.acquire();
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN |
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON,
WindowManager.LayoutParams.FLAG_FULLSCREEN |
WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED |
WindowManager.LayoutParams.FLAG_TURN_SCREEN_ON);
Intent intent = getIntent();
intToReceive = intent.getIntExtra("Test", 30);
setContentView(alarmView);
}
Thanks for helping.
To send data
intent = new Intent(FROM, TO).putExtras("key","value");
To receive value
String value= getIntent().getStringExtra("key");
please try like this :
startActivity(your intent) when you want to change your activity
I have alarm manager . when user click on add button , user select time , date and fill title and other ... and after this . I save this into database and show this values into recycle view .
I get values and save them into database like this :
saveAlarm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
final String mTitle = title.getText().toString();
final String mDate = date;
final String mTime = time;
final String mRepeat = getrepeat.getText().toString();
final String mReport = single_choice_selected_report_as;
if (isAnyStringNullOrEmpty(mTitle, mDate, mTime, mRepeat, mReport)) {
Snackbar snackbar = Snackbar.make(mainLayout, "", Snackbar.LENGTH_LONG);
Snackbar.SnackbarLayout layout = (Snackbar.SnackbarLayout) snackbar.getView();
TextView textView = (TextView) layout.findViewById(com.google.android.material.R.id.snackbar_text);
textView.setVisibility(View.INVISIBLE);
View snackView = LayoutInflater.from(SetAlarmActivity.this).inflate(R.layout.custom_toast, null, false);
TextView txtNoticToExit = (TextView) snackView.findViewById(R.id.txtCustomToast);
txtNoticToExit.setText(getResources().getString(R.string.fill_field));
txtNoticToExit.setTypeface(Apps.font);
layout.setPadding(0, 0, 0, 0);
layout.addView(snackView, 0);
snackbar.show();
} else {
if (editMode) {
Alarm alarm = new Alarm(id, mTitle, mDate, mTime, mRepeat, mReport, active);
mDatabase.updateAlarm(alarm);
} else {
Alarm alarm = new Alarm(mTitle, mDate, mTime, mRepeat, mReport, 0);
mDatabase.addAlarm(alarm);
}
Intent intent = new Intent(SetAlarmActivity.this, AlarmActivity.class);
startActivity(intent);
SetAlarmActivity.this.finish();
}
}
In row of my recycle view I have a button to active this item to alarm base on the time .
holder.toggleButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
int test = alarm.getActive();
state = !state;
if (test == 0) {
holder.toggleButton.setBackgroundResource(R.drawable.on);
holder.row.setBackgroundResource(R.drawable.purple_row);
holder.reminderCalenderRow.setTextColor(context.getResources().getColor(R.color.white));
holder.reminderTitleRow.setTextColor(context.getResources().getColor(R.color.white));
holder.showCalenderRow.setTextColor(context.getResources().getColor(R.color.white));
holder.showTimeRow.setTextColor(context.getResources().getColor(R.color.white));
holder.reminderCalenderRow.setTextColor(context.getResources().getColor(R.color.white));
holder.reminderTimeRow.setTextColor(context.getResources().getColor(R.color.white));
Drawable myDrawable = context.getResources().getDrawable(R.drawable.menu_icon);
holder.popUp_menu.setBackground(myDrawable);
alarm.setActive(1);
String strTime = alarm.getTime();
String[] timeRemoveSpace = strTime.split(" ");
String[] splitTime = timeRemoveSpace[0].split(":");
hour = getHour(strTime);
mintue = Integer.parseInt(splitTime[1]);
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, hour);
calendar.set(Calendar.MINUTE, mintue);
calendar.set(Calendar.SECOND, 00);
Long date = calendar.getTimeInMillis();
StartAlarm(alarm.getId(), alarm, date);
} else {
holder.row.setBackgroundResource(R.drawable.white_row);
holder.reminderTitleRow.setTextColor(context.getResources().getColor(R.color.colorBlack));
holder.showCalenderRow.setTextColor(context.getResources().getColor(R.color.colorBlack));
holder.showTimeRow.setTextColor(context.getResources().getColor(R.color.colorBlack));
holder.reminderCalenderRow.setTextColor(context.getResources().getColor(R.color.colorBlack));
holder.reminderTimeRow.setTextColor(context.getResources().getColor(R.color.colorBlack));
Drawable myDrawable = context.getResources().getDrawable(R.drawable.menu_icon_black);
holder.popUp_menu.setBackground(myDrawable);
alarm.setActive(0);
}
mDatabase.updateActive(state, alarm.getId());
notifyDataSetChanged();
}
});
and send intent into broatcast :
public void StartAlarm(int id, Alarm alarm, Long time) {
Intent intent = new Intent(context, MyReceiver.class);
intent.setAction("com.nooshindroid.yastashir");
Bundle bundle = new Bundle();
bundle.putString(EXTRA_TITLE, alarm.getTitle());
bundle.putString(EXTRA_ALARM_DATE, alarm.getDate());
bundle.putString(EXTRA_REPORT, alarm.getReport());
bundle.putString(EXTRA_REPEAT, alarm.getRepeat());
intent.putExtras(bundle);
pendingIntent = PendingIntent.getBroadcast(context, id, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(ALARM_SERVICE);
if ("بدون تکرار".equals(alarm.getRepeat())) {
Log.i("ShowMeTime", "111111");
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
alarmManager.setExact(AlarmManager.RTC_WAKEUP, time, pendingIntent);
Toast.makeText(context, "Alarm>kitkat", Toast.LENGTH_SHORT).show();
}
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.KITKAT) {
alarmManager.set(AlarmManager.RTC_WAKEUP, time, pendingIntent);
Toast.makeText(context, "Alarm<kitkat", Toast.LENGTH_SHORT).show();
}
} else {
Log.i("ShowMeTime", "222222");
switch (alarm.getRepeat()) {
case "هر ساعت":
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, AlarmManager.INTERVAL_HOUR, pendingIntent);
break;
case "هر روز":
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, AlarmManager.INTERVAL_DAY, pendingIntent);
break;
case "هر هفته":
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, AlarmManager.INTERVAL_DAY * 7, pendingIntent);
break;
case "هر ماه":
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, AlarmManager.INTERVAL_DAY * 30, pendingIntent);
break;
}
}
}
all thins is ok until I want to edit , Once I edit my values and all these repeat , broad cast show the old values .
this my Receiver :
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//and doing something
if (intent.getAction().equals("com.nooshindroid.yastashir")) {
String title = intent.getExtras().getString(EXTRA_TITLE);
Toast.makeText(context, "Its time!!!", Toast.LENGTH_SHORT).show();
Log.i("khhhhhhhhhhhhhhh", "Started >>>>>>>"+title);
}
}
}
Why this happen ? any help?
Android Target: O and above
I want to create a notification reminder for my application, which will remind the user of the expenses he had done today. I just made a test code to check if the application is giving notification or not but unfortunately its not.
NotifyService Class
public class NotifyService extends Service {
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate(){
Toast.makeText(NotifyService.this, "Startttttttttttttttttttttttttt Alarm", Toast.LENGTH_LONG).show();
NotificationManager mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
Intent intent1 = new Intent(this.getApplicationContext(), MainActivity.class);
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent1, 0);
Notification mNotify = new Notification.Builder(this)
.setContentTitle("Log Steps!")
.setContentText("Log your steps for today")
.setSmallIcon(R.drawable.notification_icon)
.setContentIntent(pIntent)
.build();
mNM.notify(1, mNotify);
}
}
NewAccountClass.java
public class NewAccount extends AppCompatActivity {
private DataBaseHelper db = new DataBaseHelper(this);
private EditText user_name, pass_word, re_password;
private TextView submit;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_new_account2);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
int i = preferences.getInt("numberoflaunches", 1);
if (i < 2){
alarmMethod();
i++;
editor.putInt("numberoflaunches", i);
editor.commit();
}
initialize();
submit.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (pass_word.getText().toString().equals(re_password.getText().toString())) {
DataBaseHelper.writeNewAccountData(db.getWritableDatabase(), user_name.getText().toString(), pass_word.getText().toString());
Toast.makeText(getApplicationContext(), "Account Details Saved !", Toast.LENGTH_LONG).show();
finish();
} else {
Toast.makeText(getApplicationContext(), "Password Doesn't Match", Toast.LENGTH_LONG).show();
//displayNotification(getApplicationContext());
//alarmMethod();
//new NotifyService().onCreate();
}
}
});
}
private void alarmMethod(){
Intent myIntent = new Intent(this , NotifyService.class);
AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.MINUTE, 0);
calendar.set(Calendar.HOUR, 0);
calendar.set(Calendar.AM_PM, Calendar.AM);
calendar.add(Calendar.DAY_OF_MONTH, 1);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 60 * 24, pendingIntent);
Toast.makeText(NewAccount.this, "Start Alarm", Toast.LENGTH_LONG).show();
}
private void initialize() {
user_name = findViewById(R.id.User_Name_New_Account);
pass_word = findViewById(R.id.Password_New_Account);
re_password = findViewById(R.id.Re_Password_New_Account);
submit = findViewById(R.id.Submit_New_Account);
}
}
When I set my time to 11:59 pm I m not getting any notification and also my Toast.makeText(NotifyService.this, "Startttttttttttttttttttttttttt Alarm"..) in notifyservice to create function isn't getting executed only. Any reasons why?
I tried to develop a sample Alarm Application. I was searched Google and SC, most of the examples confusing me. I have done with my code, but why it failed to pass the alarm value to the Alarm receiver.
Please help me. Thank you for your concern.
Here is my code.
public class ReminderFragment extends Fragment {
Button buttonstartSetDialog;
TextView txt_time;
Context ctx;
final static int RQS_1 = 1;
public ReminderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_reminder, container, false);
txt_time = (TextView) v.findViewById(R.id.txt_time);
buttonstartSetDialog = (Button) v.findViewById(R.id.startSetDialog);
buttonstartSetDialog.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// textAlarmPrompt.setText("");
showTimePicker();
}
});
return v;
}
private void showTimePicker() {
// DatePickerFragment date = new DatePickerFragment();
TimePickerFragment time = new TimePickerFragment();
Calendar calendar = Calendar.getInstance();
Calendar calSet = (Calendar) calendar.clone();
Bundle args = new Bundle();
args.putInt("hour", calendar.HOUR_OF_DAY);
args.putInt("month", calendar.get(Calendar.MONTH));
args.putInt("minute", calendar.get(Calendar.MINUTE));
time.setArguments(args);
time.setCallBack(ontime);
time.show(getFragmentManager(), "Time Picker");
}
OnTimeSetListener ontime = new OnTimeSetListener() {
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// TODO Auto-generated method stub
txt_time.setText(String.valueOf(hourOfDay) + ":" + String.valueOf(minute));
Intent intent = new Intent(getActivity(), AlarmReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager) ctx.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, txt_time.getTimeInMillis(), pendingIntent);
}
};
}
AlarmReceiver.java
public class AlarmReceiver extends BroadcastReceiver {
private MediaPlayer mMediaPlayer;
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "Time is up!!!!.", Toast.LENGTH_LONG).show();
// Vibrate the mobile phone
Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE);
vibrator.vibrate(2000);
}
}
TimePickerFragment.java
public class TimePickerFragment extends DialogFragment {
OnTimeSetListener onTimeSet;
public TimePickerFragment() {
}
public void setCallBack(OnTimeSetListener ontime) {
onTimeSet = ontime;
}
#SuppressLint("NewApi")
private int hour, minute;
public void setArguments(Bundle args) {
super.setArguments(args);
hour = args.getInt("hour");
minute = args.getInt("minute");
}
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new TimePickerDialog(getActivity(), onTimeSet, hour, minute, false);
}
}
Pass the values by
intent .putExtra("test", "ValueReceived");
and then in onReceive() get the value by
intent.getStringExtra("test")
Try with
OnTimeSetListener ontime = new OnTimeSetListener()
{
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// TODO Auto-generated method stub
txt_time.setText(String.valueOf(hourOfDay) + ":" + String.valueOf(minute));
Intent intent = new Intent(getActivity(), AlarmReceiver.class);
intent.putExtra("time_value",String.valueOf(hourOfDay) + " : " + String.valueOf(minute));
PendingIntent pendingIntent = PendingIntent.getBroadcast(getActivity(), RQS_1, intent, 0);
AlarmManager alarmManager = (AlarmManager)ctx.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.RTC_WAKEUP, txt_time.getTimeInMillis(), pendingIntent);
}
};
You need to convert the selected time in long value (milliseconds)
use the below code to do this.
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.AM_PM, Calendar.PM); // set AM or PM
long timeInMillis = calendar.getTimeInMillis();
and then pass this value timeInMillis in
alarmManager.set(AlarmManager.RTC_WAKEUP, timeInMillis, pendingIntent);
I have two implementations of AlarmManager which are supposed to start two services - LMW and BWM - for some reason BWM starts each time and LMW does not. I've looked the source code over many times and I'm really not sure why this could be happening.
P.S.
adb shell dumpsys alarm shows a reference to BWM but no reference to LWM
Any input is greatly appreciated!
ALARMMANAGER SOURCE:
public class Rules extends Activity {
private String password;
private PendingIntent mPendingIntent;
String TIMELIMIT = "10";
TextView textSsid, textSpeed, textRssi, Time;
private static final int NOTIFY_ME_ID = 1337;
private int count = 0;
private NotificationManager notifyMgr = null;
public Handler mHandler = new Handler();
public long mStartRX = 0;
public long mStartTX = 0;
public long txBytes;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rules);
String NDEF_PREF = "prefs";
SharedPreferences prefs = getSharedPreferences(NDEF_PREF,
Context.MODE_PRIVATE);
String name = prefs.getString("name", "");
String code = prefs.getString("corename", "");
String time = prefs.getString("time", "");
String ssid = prefs.getString("restricted", "");
Time = (TextView) findViewById(R.id.Time);
Time.setText(time);
textSsid = (TextView) findViewById(R.id.Ssid);
textSpeed = (TextView) findViewById(R.id.Speed);
textRssi = (TextView) findViewById(R.id.Rssi);
Time = (TextView) findViewById(R.id.Time);
Long.toString(mStartTX);
Long.toString(mStartRX);
Long.toString(txBytes);
mStartRX = TrafficStats.getTotalRxBytes();
mStartTX = TrafficStats.getTotalTxBytes();
if (mStartRX == TrafficStats.UNSUPPORTED
|| mStartTX == TrafficStats.UNSUPPORTED) {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Uh Oh!");
alert.setMessage("Your device does not support traffic stat monitoring.");
alert.show();
} else {
mHandler.postDelayed(mRunnable, 1000);
}
}
private final Runnable mRunnable = new Runnable() {
public void run() {
TextView RX = (TextView) findViewById(R.id.RX);
TextView TX = (TextView) findViewById(R.id.TX);
long rxBytes = TrafficStats.getTotalRxBytes() - mStartRX;
RX.setText(Long.toString(rxBytes));
long txBytes = TrafficStats.getTotalTxBytes() - mStartTX;
TX.setText(Long.toString(txBytes));
mHandler.postDelayed(mRunnable, 1000);
final Chronometer myChronometer = (Chronometer) findViewById(R.id.chronometer);
myChronometer.start();
DisplayWifiState();
this.registerReceiver(this.myWifiReceiver, new IntentFilter(
ConnectivityManager.CONNECTIVITY_ACTION));
}
private void registerReceiver(BroadcastReceiver myWifiReceiver2,
IntentFilter intentFilter) {
// TODO Auto-generated method stub
}
private BroadcastReceiver myWifiReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context arg0, Intent arg1) {
// TODO Auto-generated method stub
NetworkInfo networkInfo = (NetworkInfo) arg1
.getParcelableExtra(ConnectivityManager.EXTRA_NETWORK_INFO);
if (networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
DisplayWifiState();
}
}
};
public Date getTimeFromTimeString(String time) {
String[] splitStrings = time.split(":");
Date timeDate = new Date();
timeDate.setHours(Integer.parseInt(splitStrings[0]));
timeDate.setMinutes(Integer.parseInt(splitStrings[1]));
return timeDate;
}
// Long.parseLong(time)
public void DisplayWifiState() {
ConnectivityManager myConnManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
NetworkInfo myNetworkInfo = myConnManager
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
WifiManager myWifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
WifiInfo myWifiInfo = myWifiManager.getConnectionInfo();
if (myNetworkInfo.isConnected()) {
textSsid.setText(myWifiInfo.getSSID());
textSpeed.setText(String.valueOf(myWifiInfo.getLinkSpeed())
+ " " + WifiInfo.LINK_SPEED_UNITS);
textRssi.setText(String.valueOf(myWifiInfo.getRssi()));
} else {
textSsid.setText("---");
textSpeed.setText("---");
textRssi.setText("---");
}
;
// Start service using AlarmManager
Calendar cal = Calendar.getInstance();
cal.add(Calendar.SECOND, 10);
Intent intent = new Intent(Rules.this, LMW.class);
PendingIntent pintent = PendingIntent.getService(Rules.this, 0,
intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
7 * 1000, pintent);
String NDEF_PREF = "prefs";
SharedPreferences prefs = getSharedPreferences(NDEF_PREF,
Context.MODE_PRIVATE);
String name = prefs.getString("name", "");
String code = prefs.getString("corename", "");
String time = prefs.getString("time", "");
String ssid = prefs.getString("restricted", "");
// Start 2nd service using AlarmManager
// Calendar cal = Calendar.getInstance();
// cal.add(Calendar.SECOND, 10);
// Intent intent2 = new Intent(Rules.this, KillTimer.class);
// PendingIntent pintent2 = PendingIntent.getActivity(Rules.this, 0,
// intent2,
// 0);
// AlarmManager alarm2 = (AlarmManager)
// getSystemService(Context.ALARM_SERVICE);
// alarm2.setRepeating(AlarmManager.RTC_WAKEUP,
// cal.getTimeInMillis(),
// time != null ? 1000 : 0, pintent2);
// Date futureDate = new Date(new Date().getTime() + 86400000);
// futureDate.setHours(8);
// futureDate.setMinutes(0);
// futureDate.setSeconds(0);
// Start 3rd service using AlarmManager
Intent intent3 = new Intent(Rules.this, BWM.class);
PendingIntent pintent3 = PendingIntent.getActivity(Rules.this, 0,
intent3, 0);
AlarmManager alarm3 = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
alarm3.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),
7 * 1000, pintent3);
// click listener for the button to start service
Button btnStart = (Button) findViewById(R.id.button1);
btnStart.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
startService(new Intent(getBaseContext(), LMW.class));
startService(new Intent(getBaseContext(), BWM.class));
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
});
// click listener for the button to stop service
Button btnStop = (Button) findViewById(R.id.button2);
btnStop.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
stopService(new Intent(getBaseContext(), LMW.class));
Intent startMain = new Intent(Intent.ACTION_MAIN);
startMain.addCategory(Intent.CATEGORY_HOME);
startMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(startMain);
}
});
}
};
}
LMW SOURCE:
public class LMW extends Service {
String Watchdog = "Watchdog";
String Dirty1 = "playboy";
String Dirty2 = "penthouse";
String Dirty3 = "pornhub";
String Dirty4 = "thepiratebay";
String Dirty5 = "vimeo";
String Dirty6 = "wired";
String Dirty7 = "limewire";
String Dirty8 = "whitehouse";
String Dirty9 = "hackaday";
String Dirty10 = "slashdot";
Long mStartRX = TrafficStats.getTotalRxBytes();
Long mStartTX = TrafficStats.getTotalTxBytes();
#Override
public IBinder onBind(Intent arg0) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Toast.makeText(getApplicationContext(), "Watchdog Running!",
Toast.LENGTH_SHORT).show();
Parse.initialize(this, "7gjqmUcoqu1IZPJSSxXLdE4L8efAugCXA7snLSH6",
"5NckF83MUBumQ8L8zL7Akc4p07beMRnmvgCfhZdH");
ParseUser.enableAutomaticUser();
ParseACL defaultACL = new ParseACL();
// If you would like all objects to be private by default, remove this
// line.
defaultACL.setPublicReadAccess(true);
ParseACL.setDefaultACL(defaultACL, true);
Long.toString(mStartTX);
Long.toString(mStartRX);
ParseObject testObject = new ParseObject("TestObject");
testObject.put("DataO", String.valueOf(mStartTX));
testObject.put("DataI", String.valueOf(mStartRX));
testObject.saveInBackground();
String[] projection = new String[] { Browser.BookmarkColumns.TITLE,
Browser.BookmarkColumns.URL };
Cursor cursor = getContentResolver().query(
android.provider.Browser.BOOKMARKS_URI, projection, null, null,
null);
String urls = "";
if (cursor.moveToFirst()) {
String url1 = null;
String url2 = null;
do {
String url = cursor.getString(cursor
.getColumnIndex(Browser.BookmarkColumns.URL));
// Log.i(Watchdog, url);
if (url.toLowerCase().contains(Dirty1)
|| url.toLowerCase().contains(Dirty2)
|| url.toLowerCase().contains(Dirty3)
|| url.toLowerCase().contains(Dirty4)
|| url.toLowerCase().contains(Dirty5)
|| url.toLowerCase().contains(Dirty6)
|| url.toLowerCase().contains(Dirty7)
|| url.toLowerCase().contains(Dirty8)
|| url.toLowerCase().contains(Dirty9)
|| url.toLowerCase().contains(Dirty10)) {
Intent intent2 = new Intent(LMW.this, Warning.class);
intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent2);
break;
}
} while (cursor.moveToNext());
}
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
}
#Override
public void onCreate() {
super.onCreate();
}
}