I'm a student learning programming in Android Studio and I met some difficulties when developing my Alarm clock project. I've done lots of experiments and research in my code but still I couldn't find the solution. I wanted to try to make a normal alarm that is when the alarm is activated, display another full screen activity to remind the user. I don't want my alarm app to just ring and toast notification. I want it to also display a screen.
Here is my main code:
Code:
import java.util.Calendar;
import static android.R.id.message;
import static android.provider.AlarmClock.EXTRA_MESSAGE;
public class MainActivity extends AppCompatActivity
{
TimePicker alarmTimePicker;
PendingIntent pendingIntent;
AlarmManager alarmManager;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
alarmTimePicker = (TimePicker) findViewById(R.id.timePicker);
alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
}
// Toggle button
public void OnToggleClicked(View view)
{
long time;
if (((ToggleButton) view).isChecked())
{
Toast.makeText(MainActivity.this, "Activated", Toast.LENGTH_SHORT).show();
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, alarmTimePicker.getCurrentHour());
calendar.set(Calendar.MINUTE, alarmTimePicker.getCurrentMinute() + 1);
Intent intent = new Intent(this, AlarmReceiver.class);
pendingIntent = PendingIntent.getBroadcast(this, 0, intent, 0);
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);
}
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, time, 120000, pendingIntent);
}
else
{
Toast.makeText(MainActivity.this, "OFF", Toast.LENGTH_SHORT).show();
alarmManager.cancel(pendingIntent);
}
}
}
i will comment my manifest
Related
I'm completely noob.
Here are the sources
http://grepcode.com/file/repository...cFeedback.java#HapticFeedback.0mHapticPattern
Code:
public void init(Context context, boolean enabled) {
mEnabled = enabled;
if (enabled)
{
mVibrator = new SystemVibrator(context);
mHapticPattern = new long[] {0, DURATION, 2 * DURATION, 3 * DURATION};
mSystemSettings = new Settings.System();
mContentResolver = context.getContentResolver();
}
}
I need to change mHapticPattern array to adjust vibration duration on dialpad.
So, I can use that
Code:
findAndHookMethod("com.android.phone.common.HapticFeedback", lpparam.classLoader, "init", new XC_MethodHook()
{
@Override
protected void afterHookedMethod(MethodHookParam param) throws Throwable {
// BUT I don't know what I have to write here to get it working :(
// I know that this method will be called after init method and I don't know how I can change mHapticPattern array :(
}
});
Or I think I can also change value of Duration
private static final long DURATION = 10;
Click to expand...
Click to collapse
But anyway I do not know how...
I will be glad if anyone will try to help me...
Changing DURATION directly will have no effect. This is because the compiler replaces final static variables with their values (so "10" will be directly used instead of "DURATION").
What you could do is replace the init(Context context, boolean enabled) method entirely. Check out the development tutorial (and other wiki pages) for some hints on where to get started.
GermainZ said:
Changing DURATION directly will have no effect. This is because the compiler replaces final static variables with their values (so "10" will be directly used instead of "DURATION").
What you could do is replace the init(Context context, boolean enabled) method entirely. Check out the development tutorial (and other wiki pages) for some hints on where to get started.
Click to expand...
Click to collapse
Thank you for your answer. But I did not see it till now. That's why my respond is so late.
I had one experience with replacing entire method. But it was just a boolean method. I used this example http://forum.xda-developers.com/showpost.php?p=34609860&postcount=4
And also I've tried to replace whole init method but I have a problem with that string:
Code:
mVibrator = new SystemVibrator(context);
I did
import android.os.SystemVibrator;
but this "android.os.SystemVibrator;" is highlighted with red in eclipse
It says "The import android.os.SystemVibrator cannot be resolved" but the file exists...
I have a code but because of that error I can't test it
S0bes said:
It says "The import android.os.SystemVibrator cannot be resolved" but the file exists...
Click to expand...
Click to collapse
It's possible it's not in the SDK. Use XposedHelpers.findClass(...) to get the SystemVibrator class, then XposedHelpers.newInstance(...) to create a new instance.
@GermainZ please help me. This is the last thing I want to implement. Dialpad vibration is heavy and I think it's not good for vibro inside my phone.
This is what I try but Vibration is gone after that:
PHP:
package com.s0bes.fmspeaker;
import android.content.Context;
import android.os.Vibrator;
import de.robv.android.xposed.XC_MethodHook;
import de.robv.android.xposed.XC_MethodReplacement;
import de.robv.android.xposed.XposedBridge;
import de.robv.android.xposed.XposedHelpers;
import static de.robv.android.xposed.XposedHelpers.findClass;
import static de.robv.android.xposed.XposedHelpers.newInstance;
import de.robv.android.xposed.callbacks.XC_LoadPackage.LoadPackageParam;
import android.content.ContentResolver;
import android.provider.Settings;
//import android.os.SystemVibrator;
public class bool1 {
static Context context;
private static Vibrator mVibrator ;
private static Settings.System mSystemSettings;
private static ContentResolver mContentResolver;
private static long[] mHapticPattern;
public static void InitResources(final LoadPackageParam lpparam) throws Throwable {
if (lpparam.packageName.equals("com.android.dialer")) {
XposedHelpers.findAndHookMethod("com.android.phone.common.HapticFeedback", lpparam.classLoader,
"init", Context.class, boolean.class, new XC_MethodHook() {
@Override protected void beforeHookedMethod(final MethodHookParam param) throws Throwable {
XposedBridge.log("HOOOKED init" );
//context=(Context) param.args[0];
}
});
XposedHelpers.findAndHookMethod("com.android.phone.common.HapticFeedback", lpparam.classLoader, "init", Context.class, boolean.class, new XC_MethodReplacement() {
@Override
protected Object replaceHookedMethod(MethodHookParam param) throws Throwable {
context=(Context) param.args[0];
XposedBridge.log("REPLACED init. Enabled="+param.args[1] );
Class Myclass = findClass("android.os.SystemVibrator", lpparam.classLoader);
Object mVibrator = newInstance(Myclass, context);
mHapticPattern = new long[] {0, 10, 2 * 10, 8 * 10};
mSystemSettings = new Settings.System();
mContentResolver = context.getContentResolver();
return true;
}
});
}
}
}
EDIT:
Yeehoooo. I got this working
Your post http://forum.xda-developers.com/showpost.php?p=54951841&postcount=8 very helped me.
Instead replace init method I replaced vibrate();
PHP:
XposedHelpers.findAndHookMethod("com.android.phone.common.HapticFeedback", lpparam.classLoader, "vibrate", new XC_MethodReplacement() {
@Override
protected Object replaceHookedMethod(MethodHookParam param) throws Throwable {
Class Myclass = findClass("android.os.SystemVibrator", lpparam.classLoader);
Object mVibrator = newInstance(Myclass, context);
mHapticPattern = new long[] {0, 10, 1 * 10, 1 * 10};
((Vibrator) mVibrator).vibrate(mHapticPattern, -1);
return true;
}
});
}
So.. I stayed up all night and finally got XSharedPreferences to work with my module. But today when I tried to add other elements such as a Navigation Drawer, and have the preference page only show when tapped, it stopped working.
This is the MainActivity code that has been working just fine.
Working:
Code:
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null)
getFragmentManager().beginTransaction().replace(android.R.id.content, new PrefsFragment()).commit();
}
public static class PrefsFragment extends PreferenceFragment {
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesMode(MODE_WORLD_READABLE);
addPreferencesFromResource(R.xml.prefs);
}
}
}
Below is the code where it stopped working. I tried back tracking and only with the code above does it work.
Not working:
Code:
public class MainActivity extends AppCompatActivity implements NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
private Toolbar mToolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mToolbar);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.fragment_drawer);
// Set up the drawer.
mNavigationDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);
// populate the navigation drawer
mNavigationDrawerFragment.setUserData("John Doe", "[email protected]", BitmapFactory.decodeResource(getResources(), R.drawable.avatar));
}
@Override
public void onNavigationDrawerItemSelected(int position) {
Fragment fragment;
switch (position) {
case 0: //search//todo
break;
case 1: //Minor theme fixes
fragment = getFragmentManager().findFragmentByTag(PrefsFragment.TAG);
if (fragment == null) {
fragment = new PrefsFragment();
}
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment, PrefsFragment.TAG)
.addToBackStack(null)
.commit();
break;
case 2: //Full themed apps
fragment = getFragmentManager().findFragmentByTag(PrefsFragment2.TAG_2);
if (fragment == null) {
fragment = new PrefsFragment2();
}
android.app.FragmentManager fragmentManager1 = getFragmentManager();
fragmentManager1.beginTransaction()
.replace(R.id.container, fragment, PrefsFragment2.TAG_2)
.addToBackStack(null)
.commit();
break;
case 3: //settings //todo
break;
}
}
@Override
public void onBackPressed() {
if (mNavigationDrawerFragment.isDrawerOpen())
mNavigationDrawerFragment.closeDrawer();
else
super.onBackPressed();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
PrefsFragment fragment = new PrefsFragment();
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.addToBackStack(null)
.commit();
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PrefsFragment extends PreferenceFragment {
private final static String TAG = "PrefsFragment";
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesMode(MODE_WORLD_READABLE);
addPreferencesFromResource(R.xml.prefs);
}
}
public static class PrefsFragment2 extends PreferenceFragment {
private final static String TAG_2 = "PrefsFragment2";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs2);
}
}
}
93Akkord said:
So.. I stayed up all night and finally got XSharedPreferences to work with my module. But today when I tried to add other elements such as a Navigation Drawer, and have the preference page only show when tapped, it stopped working.
This is the MainActivity code that has been working just fine.
Working:
Code:
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (savedInstanceState == null)
getFragmentManager().beginTransaction().replace(android.R.id.content, new PrefsFragment()).commit();
}
public static class PrefsFragment extends PreferenceFragment {
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesMode(MODE_WORLD_READABLE);
addPreferencesFromResource(R.xml.prefs);
}
}
}
Below is the code where it stopped working. I tried back tracking and only with the code above does it work.
Not working:
Code:
public class MainActivity extends AppCompatActivity implements NavigationDrawerCallbacks {
/**
* Fragment managing the behaviors, interactions and presentation of the navigation drawer.
*/
private NavigationDrawerFragment mNavigationDrawerFragment;
private Toolbar mToolbar;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mToolbar = (Toolbar) findViewById(R.id.toolbar_actionbar);
setSupportActionBar(mToolbar);
mNavigationDrawerFragment = (NavigationDrawerFragment)
getFragmentManager().findFragmentById(R.id.fragment_drawer);
// Set up the drawer.
mNavigationDrawerFragment.setup(R.id.fragment_drawer, (DrawerLayout) findViewById(R.id.drawer), mToolbar);
// populate the navigation drawer
mNavigationDrawerFragment.setUserData("John Doe", "[email protected]", BitmapFactory.decodeResource(getResources(), R.drawable.avatar));
}
@Override
public void onNavigationDrawerItemSelected(int position) {
Fragment fragment;
switch (position) {
case 0: //search//todo
break;
case 1: //Minor theme fixes
fragment = getFragmentManager().findFragmentByTag(PrefsFragment.TAG);
if (fragment == null) {
fragment = new PrefsFragment();
}
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment, PrefsFragment.TAG)
.addToBackStack(null)
.commit();
break;
case 2: //Full themed apps
fragment = getFragmentManager().findFragmentByTag(PrefsFragment2.TAG_2);
if (fragment == null) {
fragment = new PrefsFragment2();
}
android.app.FragmentManager fragmentManager1 = getFragmentManager();
fragmentManager1.beginTransaction()
.replace(R.id.container, fragment, PrefsFragment2.TAG_2)
.addToBackStack(null)
.commit();
break;
case 3: //settings //todo
break;
}
}
@Override
public void onBackPressed() {
if (mNavigationDrawerFragment.isDrawerOpen())
mNavigationDrawerFragment.closeDrawer();
else
super.onBackPressed();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
if (!mNavigationDrawerFragment.isDrawerOpen()) {
// Only show items in the action bar relevant to this screen
// if the drawer is not showing. Otherwise, let the drawer
// decide what to show in the action bar.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
return super.onCreateOptionsMenu(menu);
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
PrefsFragment fragment = new PrefsFragment();
android.app.FragmentManager fragmentManager = getFragmentManager();
fragmentManager.beginTransaction()
.replace(R.id.container, fragment)
.addToBackStack(null)
.commit();
return true;
}
return super.onOptionsItemSelected(item);
}
public static class PrefsFragment extends PreferenceFragment {
private final static String TAG = "PrefsFragment";
@SuppressWarnings("deprecation")
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getPreferenceManager().setSharedPreferencesMode(MODE_WORLD_READABLE);
addPreferencesFromResource(R.xml.prefs);
}
}
public static class PrefsFragment2 extends PreferenceFragment {
private final static String TAG_2 = "PrefsFragment2";
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.prefs2);
}
}
}
Click to expand...
Click to collapse
Well.. seems like moving the code that worked to its own activity and the following to the mainactivities oncreate has done the trick.
Code:
pref = getSharedPreferences(getPackageName() + "_preferences", MODE_WORLD_READABLE);
I am unable to get XSharedPreferences to work and the standard shared preferences work perfectly. I create a shared preferences file elsewhere in the application. The file is in the shared_pref folder and I can read the file which is perfectly OK.
However, I cannot make the XSharedPreferences work, I. e. I have the opposite problem.
Therefore, can I ask you to provide the code or a guidance how to make the XSharedPreferences work, so I can read the file inside of the Xposed module? In case you do not want to publish anything in this topic, can you please, send a message?
I have a textview that shows your amount of money and i would like the ui to update every second to visually show how much money you have in real time. Would i be able to accomplish this with a timer?, and if so what would it look like.
Hello,
You should do inside your class, outside of any method:
Code:
TextView tv;
String calculatedString;
MyAsyncTask mAsync = null;
Timer timer = null;
TimerTask task = null;
private class MyAsyncTask extends AsyncTask<String, Void, String> {
public MyAsyncTask(){
}
@Override
protected String doInBackground(String... params) {
//Background operation in a separate thread
//Write here your code to run in the background thread
//calculate here whatever you like
calculatedString = ....;
return null;
}
@Override
protected void onPostExecute(String result) {
//Called on Main UI Thread. Executed after the Background operation, allows you to have access to the UI
tv.setText(calculatedString);
}
@Override
protected void onPreExecute() {
//Called on Main UI Thread. Executed before the Background operation, allows you to have access to the UI
}
}
inside the onCreate after super and setContentView:
Code:
tv = (TextView) findViewById(R.id.tv); //your tv id here
final Handler handler = new Handler();
timer = new Timer();
task = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
MyAsyncTask mAsync = new MyAsyncTask();
mAsync.execute();
}
});
}
};
timer.schedule(task, 0, 1000); //Every 1 second
If you still need help, feel free to ask
I have attached 2 screenshots showing the errors i was given after inputting. Any idea how to fix this?
mmdeveloper10 said:
Hello,
You should do inside your class, outside of any method:
Code:
TextView tv;
String calculatedString;
MyAsyncTask mAsync = null;
Timer timer = null;
TimerTask task = null;
private class MyAsyncTask extends AsyncTask<String, Void, String> {
public MyAsyncTask(){
}
@Override
protected String doInBackground(String... params) {
//Background operation in a separate thread
//Write here your code to run in the background thread
//calculate here whatever you like
calculatedString = ....;
return null;
}
@Override
protected void onPostExecute(String result) {
//Called on Main UI Thread. Executed after the Background operation, allows you to have access to the UI
tv.setText(calculatedString);
}
@Override
protected void onPreExecute() {
//Called on Main UI Thread. Executed before the Background operation, allows you to have access to the UI
}
}
inside the onCreate after super and setContentView:
Code:
tv = (TextView) findViewById(R.id.tv); //your tv id here
final Handler handler = new Handler();
timer = new Timer();
task = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
MyAsyncTask mAsync = new MyAsyncTask();
mAsync.execute();
}
});
}
};
timer.schedule(task, 0, 1000); //Every 1 second
If you still need help, feel free to ask
Click to expand...
Click to collapse
Hello,
For the first image:
You have to import the AsyncTask.
add this
Code:
import android.os.AsyncTask;
with the other imports in your java file.
For your second image:
You haven't wrote the line
Code:
setContentView(R.layout.activity_main);
under your super.onCreate(savedInstanceState); and then the code I said above (I said that on my post )
inside onCreate, where activity_main is your xml layout. And you should have inside that layout, a TextView with an id "tv" (or whatever you like)
and then:
Code:
tv = (TextView) findViewById(R.id.tv); //your tv id here
R.id.tv must much the id you have in your layout. Replace it with the actual id of your TextView. If your id is "tv", write R.id.tv, if it is "mytv" write R.id.mytv. ( I said that on my post also)
Can you show your layout file? (XML - your activity_main.xml). You said that you have a TextView Where is your TextView?
Ok I fixed the problems stated and now only have these two errors remaining
mmdeveloper10 said:
Hello,
For the first image:
You have to import the AsyncTask.
add this
Code:
import android.os.AsyncTask;
with the other imports in your java file.
For your second image:
You haven't wrote the line
Code:
setContentView(R.layout.activity_main);
under your super.onCreate(savedInstanceState); and then the code I said above (I said that on my post )
inside onCreate, where activity_main is your xml layout. And you should have inside that layout, a TextView with an id "tv" (or whatever you like)
and then:
Code:
tv = (TextView) findViewById(R.id.tv); //your tv id here
R.id.tv must much the id you have in your layout. Replace it with the actual id of your TextView. If your id is "tv", write R.id.tv, if it is "mytv" write R.id.mytv. ( I said that on my post also)
Can you show your layout file? (XML - your activity_main.xml). You said that you have a TextView Where is your TextView?
Click to expand...
Click to collapse
Have you imported this?
Code:
import java.util.logging.Handler;
If so, change it to
Code:
import android.os.Handler;
Im not at the computer but I think that should solve my issue I will keep you updated
Sent from my HTC6525LVW using XDA Free mobile app
Hey thanks so much its working perfectly now :good:
Hello guys
im trying to find out what im doing wrong in this case
Im trying to have 2 edittext and every time they get tapped to display date picker and time picker and get print of the date on this format "dd/MM/yyyy HH:mm"
instead of this i get "dd/MM/yyyy - HH:mm - HH:mm""
what the heck im doing wrong ?
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import android.os.Bundle;
import android.app.DatePickerDialog;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.text.format.DateFormat;
import android.util.Log;
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 static com.example.neo.myapplication.R.id.currenttext;
public class MainActivity extends FragmentActivity {
static EditText DateEdit;
static EditText DateEdit2;
static TextView DateFinalText;
Button buttoncalc;
Button FinalCalc;
static String DesFinalDate;
static String DVRFinalDate;
@override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TextView tv = (TextView) findViewById(currenttext);
final String datecur = new SimpleDateFormat("dd-MM-yyyy HH:mm").format(Calendar.getInstance().getTime());
tv.setText(datecur);
FinalCalc = (Button) findViewById(R.id.buttoncalc);
FinalCalc.setOnClickListener(new View.OnClickListener(){
@override
public void onClick(View v) {
try {
//Dates to compare
String CurrentDate= "10/4/2017 10:21";
String FinalDate= "11/03/2016 11:21";
Date date1;
Date date2;
SimpleDateFormat dates = new SimpleDateFormat("MM/dd/yyyy HH:mm");
//Setting dates
date1 = dates.parse(CurrentDate);
date2 = dates.parse(FinalDate);
//Comparing dates
long difference = Math.abs(date1.getTime() - date2.getTime());
long differenceDates = difference / (24 * 60 * 60 * 1000);
//Convert long to String
String dayDifference = Long.toString(differenceDates);
Log.e("HERE","HERE: " + dayDifference);
} catch (Exception exception) {
Log.e("DIDN'T WORK", "exception " + exception);
}
}
});
DateEdit = (EditText) findViewById(R.id.editText1);
DateEdit.setOnClickListener(new View.OnClickListener() {
@override
public void onClick(View v) {
showTimePickerDialog(v);
showDatePickerDialog(v);
}
});
DateEdit2 = (EditText) findViewById(R.id.editText2);
DateEdit2.setOnClickListener(
new View.OnClickListener() {
@override
public void onClick(View v) {
showTimePickerDialog1(v);
showDatePickerDialog1(v);
}
});
}
public void showDatePickerDialog(View v) {
DialogFragment newFragment = new DatePickerFragment();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
public void showDatePickerDialog1(View v) {
DialogFragment newFragment = new DatePickerFragment1();
newFragment.show(getSupportFragmentManager(), "datePicker");
}
//DATE PICKER FRAGMENT
public static class DatePickerFragment extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
@override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
DateEdit.setText(day + "/" + (month + 1) + "/" + year);
}
}
//DATE PICKER FRAGMENT 1
public static class DatePickerFragment1 extends DialogFragment implements
DatePickerDialog.OnDateSetListener {
@override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current date as the default date in the picker
final Calendar c = Calendar.getInstance();
int year = c.get(Calendar.YEAR);
int month = c.get(Calendar.MONTH);
int day = c.get(Calendar.DAY_OF_MONTH);
// Create a new instance of DatePickerDialog and return it
return new DatePickerDialog(getActivity(), this, year, month, day);
}
public void onDateSet(DatePicker view, int year, int month, int day) {
// Do something with the date chosen by the user
DateEdit2.setText(day + "/" + (month + 1) + "/" + year);
}
}
//TIME PICKER FRAGMENT
public void showTimePickerDialog(View v) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
public void showTimePickerDialog1(View v) {
DialogFragment newFragment = new TimePickerFragment1();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
public static class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {
@override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
DateEdit.setText(DateEdit.getText() + " -" + hourOfDay + ":" + minute);
DVRFinalDate = DateEdit.toString();
}
}
//TIME PICKER FRAGMENT1
public static class TimePickerFragment1 extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {
@override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
// Do something with the time chosen by the user
DateEdit2.setText(DateEdit2.getText() + " -" + hourOfDay + ":" + minute) ;
DesFinalDate = DateEdit2.toString();
}
}
So I am building a program with a notification that activates 3 hours after the activity is stopped (for testing purposes I am currently using minutes). This is what my main activity looks like...
Code:
Override
public void onStop() {
super.onStop();
Calendar calendar = Calendar.getInstance();
int alarmTime = (calendar.get(Calendar.MINUTE)) + 3;
calendar.set(Calendar.MINUTE,alarmTime);
Intent intent3 = new Intent(getApplicationContext(),timeReceiver.class);
PendingIntent pendingIntent3 = PendingIntent.getBroadcast(getApplicationContext(),100,intent3,PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,calendar.getTimeInMillis(),AlarmManager.INTERVAL_DAY,pendingIntent3);
}
@Override
protected void onRestart() {
super.onRestart();
//this.onCreate(null);
}
This is what my broadcast receiver class looks like...
Code:
public class timeReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
NotificationManager notificationManager =(NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
Intent repeating_intent = new Intent(context, RepeatingActivity.class);
repeating_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(context,100,repeating_intent,PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setContentIntent(pendingIntent);
builder.setSmallIcon(android.R.drawable.arrow_up_float);
builder.setContentTitle("Timer Notification");
builder.setContentText("blaaah blaaah blah");
builder.setAutoCancel(true);
notificationManager.notify(100,builder.build());
}
}
3 minutes after running the stop code the timer is activated the way it's supposed to, however my problem is that if the code is executed a second time within this 3 minute period - then no notification is pushed at all. My hope is that the alarm would reset and trigger 3 minutes after the last execution of the onStop() method, but it doesn't. I don't really understand why it doesn't, if anyone could give me insight/ a possible solution I would be grateful. Also the SDK version is 24.
I've already worked on a alarm scheduler (notification) just yesterday.
So here comes my working code (you can find it in github / binogure-studio):
Code:
public void schedule_local_notification(String title, String content, int delay, int notification_id) {
// delay is after how much time(in millis) from current time you want to schedule the notification
NotificationCompat.Builder builder = new NotificationCompat.Builder(context, activity.getPackageName() + CHANNEL_ID)
.setContentTitle(title)
.setContentText(content)
.setAutoCancel(true)
.setSmallIcon(R.drawable.ic_stat_name)
.setLargeIcon(BitmapFactory.decodeResource(context.getResources(), R.mipmap.ic_launcher))
.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));
Intent intent = new Intent(context, Godot.class);
PendingIntent intentActivity = PendingIntent.getActivity(context, notification_id, intent, PendingIntent.FLAG_CANCEL_CURRENT);
builder.setContentIntent(intentActivity);
Notification notification = builder.build();
Intent notificationIntent = new Intent(context, LocalNotificationReceiver.class);
notificationIntent.putExtra(LocalNotificationReceiver.NOTIFICATION_ID, notification_id);
notificationIntent.putExtra(LocalNotificationReceiver.NOTIFICATION, notification);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, notification_id, notificationIntent, PendingIntent.FLAG_CANCEL_CURRENT);
long futureInMillis = SystemClock.elapsedRealtime() + delay * 1000;
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP, futureInMillis, pendingIntent);
}
public void cancel_local_notification(int notification_id) {
try {
Intent intent = new Intent(context, LocalNotificationReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(context, notification_id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(pendingIntent);
} catch (Exception ex) {
Log.w(TAG, "Cannot show local notification: " + ex.getMessage());
}
}