Alarm Clock app error - android

public void pickTimeHandler(View target) {
Toast.makeText(Alarms1.this, "in PickTimehandler", Toast.LENGTH_LONG).show();
showDialog(0);
where you see Alarm1.this is always an error in all of my code that says
No enclosing instance of the type Alarms1 is accessible in scope

You would write Alarms1.this if that is the name of the enclosing class
What is the name of the class this is in? Use that name.
Example:
public class Alarms1 {
public void pickTimeHandler(View target) {
//code below would work, you could also just write "this" instead of "Alarms1.this"
Toast.makeText(Alarms1.this, "in PickTimehandler", Toast.LENGTH_LONG).show();
showDialog(0);
}
}
You only need to qualify the this value with the name of the class if it is made from an inner class.
Here is an example of when you need to qualify what "this" parameter you are using:
public class Alarms1 {
public void onCreate(Bundle state) {
Button button = (Button) findViewById(R.id.set_alarm);
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Toast.makeText(Alarms1.this, "Button clicked", Toast.LENGTH_LONG).show();
}
});
}
}
The difference is that in the above code in the second example you are creating an anonymous inner class when you put
button.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Perform action on click
}
});
And from within that code if you wrote this the java compiler/runtime would think you were referring to the instance of the inner class (as opposed to the Alarms1).
--- UPDATE ---
Given the code you sent me I came up with this:
package com.example;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.Dialog;
import android.app.PendingIntent;
import android.app.TimePickerDialog;
import android.app.TimePickerDialog.OnTimeSetListener;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TimePicker;
import android.widget.Toast;
public class AlarmActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void pickTimeHandler(View target) {
Toast.makeText(this, "in PickTimehandler",
Toast.LENGTH_LONG).show();
showDialog(0);
}
#Override
protected Dialog onCreateDialog(int id) {
Toast.makeText(this,
"- onCreateDialog(ID_TIMEPICKER) -",
Toast.LENGTH_LONG).show();
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
OnTimeSetListener theTimeSetListener = null;
return new TimePickerDialog(this,
theTimeSetListener,
hour, minute, false);
}
private TimePickerDialog.OnTimeSetListener theTimeSetListener = new TimePickerDialog.OnTimeSetListener() {
#Override
public void onTimeSet(TimePicker view, int hour, int minute) {
String time = "User picked Hour: " + String.valueOf(hour) + "\n"
+ "Minute: " + String.valueOf(minute);
Toast.makeText(AlarmActivity.this, time, Toast.LENGTH_LONG).show();
int theHour = hour;
int theMinute = minute;
Intent alarmIntent = new Intent();
alarmIntent.putExtra("nel.example.alarms1", "My message");
Object pendingAlarmIntent = PendingIntent.getService(AlarmActivity.this, 0,
alarmIntent, 0);
AlarmManager alarmManager = (AlarmManager) getSystemService(ALARM_SERVICE);
Calendar AlarmCal = Calendar.getInstance();
AlarmCal.setTimeInMillis(System.currentTimeMillis());
AlarmCal.set(Calendar.HOUR_OF_DAY, theHour); // set user selection
AlarmCal.set(Calendar.MINUTE, theMinute); // set user selection
AlarmCal.set(Calendar.SECOND, 0);
alarmManager.setRepeating(AlarmManager.RTC_WAKEUP,
AlarmCal.getTimeInMillis(), AlarmManager.INTERVAL_FIFTEEN_MINUTES,
(PendingIntent) pendingAlarmIntent);
}
};
}
The changes I made are:
Renamed class form myMenu to AlarmActivity (The class has nothing to do with a menu, it is an alarm isn't it). Also classs names should start with a capital letter.
PendingIntent.getService need a context. This is EXACTLY the problem I described in my original solution. An Activity is a subclass of Context, which means you can pass an actvity to PendingIntent.getService in the first parameter. However when you created that inner class:
private TimePickerDialog.OnTimeSetListener theTimeSetListener = new TimePickerDialog.OnTimeSetListener(){
The code within that no longer was an Activity, it was a TimePickerDialog.OnTimeSetListener. You need to pass myMenu.this as the first parameter (or in my case, since I renamed your class to AlarmActivity, you would pass AlarmActivity.this). The same thing goes with Toasts that you create within an inner class.
I highly suggest you stop what you are doing and go learn java before continuing android development. Read a book, follow online tutorials, etc. But if you just dive into android without understanding java you will have a load of problems.

Related

Scheduling a task using AlarmManager

I am trying to schedule a task " a toast message" to appear in the time chosen by the user, but nothing is showing after that time and i can't see what is wrong in the code.
That's my code
public class TimePickerFragment extends DialogFragment implements
TimePickerDialog.OnTimeSetListener {
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
final Calendar c = Calendar.getInstance();
int hour = c.get(Calendar.HOUR_OF_DAY);
int minute = c.get(Calendar.MINUTE);
return new TimePickerDialog(getActivity(), this, hour, minute,
DateFormat.is24HourFormat(getActivity()));
}
#Override
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//set The Calendar to to the wanted time!
Calendar calendar = Calendar.getInstance();
calendar.set(Calendar.HOUR_OF_DAY, hourOfDay);
calendar.set(Calendar.MINUTE, minute);
calendar.set(Calendar.SECOND, 0);
calendar.set(Calendar.AM_PM, Calendar.AM);
Intent setMsg = new Intent(MainActivity.this, TaskReceiver.class);
PendingIntent pendingIntent = PendingIntent.getBroadcast(MainActivity.this, 0, setMsg, 0);
AlarmManager manager = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
manager.setExact(AlarmManager.ELAPSED_REALTIME, calendar.getTimeInMillis(), pendingIntent);
}
}
public class TaskReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
Toast.makeText(context, "it is working!", Toast.LENGTH_SHORT).show();
}
}
If there is a better way to schedule such a task please go ahead and introduce it.
import android.app.Activity;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.widget.Toast;
import com.yourcomp.yourapp.R;
import java.lang.ref.WeakReference;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;
public class TestAct extends Activity {
private static class MyHandler extends Handler{
private WeakReference<Activity> activityWr;
public MyHandler(Activity activityMain){
activityWr = new WeakReference<>(activityMain);
}
#Override
public void handleMessage(Message inputMessage) {
if (activityWr.get() != null){
Toast.makeText(activityWr.get(),"Your text",Toast.LENGTH_LONG).show();
}
}
}
private MyHandler mHandler;
private Future<?> mToastTaskRef;
private static int NUMBER_OF_CORES =
Runtime.getRuntime().availableProcessors();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHandler = new MyHandler(this);
/**
* initialize UI & take input from user && call method
*/
}
private void showToastAfterUserSpecifiedDelay(int seconds){
mToastTaskRef = Executors.newScheduledThreadPool(NUMBER_OF_CORES).scheduleAtFixedRate(new Runnable() {
#Override
public void run() {
mHandler.sendMessage(new Message());
}
}, /**initial delay*/60
,/**time*/seconds
,/**time unit*/ TimeUnit.MILLISECONDS);
}
private void stopToastTask(){
if (mToastTaskRef != null && !mToastTaskRef.isCancelled() && !mToastTaskRef.isDone()){
mToastTaskRef.cancel(true); //tru -- >interrupt even if it's running
}
}
}
Use this in your code Instead of manager.setExact method as follows:
manager.setRepeating(AlarmManager.RTC_WAKEUP,System.currentTimeMillis(), interval, pendingIntent);

why does my service go inside the timertask loop?

I've tried to make an app that opens up a service, that changes the wallpaper on your phone every 5 hours.
For testing purposes I've only changed the timer for 1 minute just to see if it works (because when it's on 5 hours it doesn't work),
and indeed it changes the wallpaper every single minute. Even when I close my app and the service is closed
I have a statement to restart it so that works.
Unfortunately when the phone turns black (timeout for the screen). and I turn it back on it's like it stuck up all the time. It needed to go inside the listener while the phone was suspended, so it goes inside the timerTask like, 10 times in a row immediately (or the times it was offline..and it should have gone inside). In other words if I put the phone on rest for 10 minutes and then turn it back on, it will just change my wallpaper 10 times in a row.
So that's one problem. The other one is that if I change the timer for 5 hours it doesn't change the wallpaper at all.
Can someone help me or know why this is happening to me ?
this is my code >
my service >
package com.greenroad.candidate.mywallpaperchanger;
import android.app.Service;
import android.app.WallpaperManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Handler;
import android.os.IBinder;
import android.preference.PreferenceManager;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.WindowManager;
import android.widget.Toast;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Random;
import java.util.Timer;
import java.util.TimerTask;
/**
* Created by pitsponet on 31/08/2015.
*/
public class myService extends Service {
int oneSecond = 1000;
int oneMinute = oneSecond*60;
int oneHour = oneMinute*60;
int timerDeley = oneMinute;
private Timer timer;
//this is the tast or the reciver the timer will go into every time it has being called
private TimerTask timerTask = new TimerTask() {
#Override
public void run() {
//shows a toast saying timer listener has entered
Handler mainHandler = new Handler(getApplicationContext().getMainLooper());
mainHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "timer listener Entered", Toast.LENGTH_LONG).show();
}
});
//gets the picture modifire to know what picture to choose to change the wallpaper to
// Access the default SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("myGlobalPrefTable", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
Integer pictureModifireInt = pref.getInt("pictureModifire", 0);
//updates teh picture modifire by one
pictureModifireInt++;
/////holds a list with all the images that are avilable to change
int displayPicture = R.drawable.captain;
ArrayList<Integer> pictureNames = new ArrayList<>();
pictureNames.add(R.drawable.captain);
pictureNames.add(R.drawable.flash);
pictureNames.add(R.drawable.superman);
pictureNames.add(R.drawable.thor);
pictureNames.add(R.drawable.wonder);
pictureNames.add(R.drawable.a);
pictureNames.add(R.drawable.b);
pictureNames.add(R.drawable.c);
pictureNames.add(R.drawable.d);
pictureNames.add(R.drawable.e);
pictureNames.add(R.drawable.f);
pictureNames.add(R.drawable.g);
pictureNames.add(R.drawable.h);
pictureNames.add(R.drawable.i);
pictureNames.add(R.drawable.j);
pictureNames.add(R.drawable.k);
pictureNames.add(R.drawable.l);
pictureNames.add(R.drawable.m);
pictureNames.add(R.drawable.n);
pictureNames.add(R.drawable.o);
//logs the stored prefrence and select the correct image at place > picture modifire
Log.d("myLog", "storedPreference: " + pictureModifireInt);
displayPicture = pictureNames.get(pictureModifireInt-1);
//stores the picture modifire back in the shared prefrences or initlizes it if it reached the last image
if(pictureModifireInt > 19){
// Edit the saved preferences
Log.d("myLog", "putting in pictureModifire : : " + 0);
editor.putInt("pictureModifire", 0);
editor.commit();
} else {
Log.d("myLog", "putting in pictureModifire : : " + pictureModifireInt);
editor.putInt("pictureModifire", pictureModifireInt);
editor.commit();
}
//most important part of the code
//gets the dimentions of the phones screen and changes the wallpaper
//it has to get the dimentions so that the wallpaper will be in full screen
//maybe he can't do this part when he is in suspend mode ?
WindowManager wm= (WindowManager) getSystemService(MainActivity.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
Bitmap bmap2 = BitmapFactory.decodeResource(getResources(), displayPicture);
Bitmap bitmap = Bitmap.createScaledBitmap(bmap2, width, height, true);
WallpaperManager wallpaperManager = WallpaperManager.getInstance(getApplicationContext());
try {
wallpaperManager.setBitmap(bitmap);
} catch (IOException e) {
e.printStackTrace();
}
//just shoes a post to let knnow what wallpaper has been changed, and that the walpaper indeed changed
mainHandler = new Handler(getApplicationContext().getMainLooper());
final Integer finalPictureModifireInt = pictureModifireInt-1;
mainHandler.post(new Runnable() {
#Override
public void run() {
Toast.makeText(getApplicationContext(), "wallpaper changed to : "+ finalPictureModifireInt+" and started a new timer", Toast.LENGTH_LONG).show();
}
});
}
};
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
//show a toast to indicae that a new service was created
Toast.makeText(getApplicationContext(), "a new service created",
Toast.LENGTH_LONG).show();
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyLog", "a new service started");
final Handler mainHandler = new Handler(getApplicationContext().getMainLooper());
mainHandler.post(new Runnable() {
#Override
public void run() {
//show a toast to indicae that a new service was started
Toast.makeText(getApplicationContext(), "serviceStarterd", Toast.LENGTH_LONG).show();
// Access the default SharedPreferences
SharedPreferences pref = getApplicationContext().getSharedPreferences("myGlobalPrefTable", MODE_PRIVATE);
SharedPreferences.Editor editor = pref.edit();
//open a boolean to tell if the service is activated for the first time it will say false
boolean serviceStateOn = pref.getBoolean("isServiceActivated", false);
if(serviceStateOn == false){
//if ther serviceStateOn is false then there is no service running and it's fine to run a timer task
Toast.makeText(getApplicationContext(), "a New Timer Started with Delay: "+timerDeley, Toast.LENGTH_LONG).show();
editor.putBoolean("isServiceActivated", true); // getting String
editor.commit();
timer = new Timer();
timer.scheduleAtFixedRate(timerTask, timerDeley, timerDeley);
} else {
//if ther serviceStateOn is true then there is a service runing so just don't do anything
Log.d ("myLog", "Service is on so do nothing");
}
}
});
return START_STICKY;
}
#Override
public void onDestroy() {
super.onDestroy();
Toast.makeText(getApplicationContext(), "service stoped",
Toast.LENGTH_LONG).show();
}
}
my manifest file >
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.greenroad.candidate.mywallpaperchanger" >
<uses-permission android:name="android.permission.SET_WALLPAPER"/>
<application
android:allowBackup="true"
android:icon="#mipmap/ic_launcher"
android:label="#string/app_name"
android:theme="#style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="#string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service
android:name=".myService"
android:exported="false"
/>
</application>
</manifest>
my main acticity >
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import java.io.IOException;
public class MainActivity extends ActionBarActivity implements View.OnClickListener {
#Override
protected void onCreate(Bundle savedInstanceState) {
//declaring all the buttons
Button comixButtonSuperman, comixButtonFlash, comixButtonCaptainAmerica, comixButtonThor, comixButtonWonderWoman;
Button startServiceButton, stopServiceButton;
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//casting and connecting the buttons to the actual buttons
comixButtonSuperman = (Button) findViewById(R.id.BT_wallpaper1);
comixButtonFlash = (Button) findViewById(R.id.BT_wallpaper2);
comixButtonCaptainAmerica = (Button) findViewById(R.id.BT_wallpaper3);
comixButtonThor = (Button) findViewById(R.id.BT_wallpaper4);
comixButtonWonderWoman = (Button) findViewById(R.id.BT_wallpaper5);
startServiceButton = (Button) findViewById(R.id.BT_startService);
stopServiceButton = (Button) findViewById(R.id.BT_stopService);
//adding listeners for all the buttons
comixButtonSuperman.setOnClickListener(this);
comixButtonFlash.setOnClickListener(this);
comixButtonCaptainAmerica.setOnClickListener(this);
comixButtonThor.setOnClickListener(this);
comixButtonWonderWoman.setOnClickListener(this);
startServiceButton.setOnClickListener(this);
stopServiceButton.setOnClickListener(this);
}
#Override
protected void onDestroy() {
super.onDestroy();
Log.d ("myLog", "Application exists here");
// when going to suspend the service is destroyd, so we should change the boolean to indicate this
//also this will make the service statement added in the service possible.
SharedPreferences pref = getApplicationContext().getSharedPreferences("myGlobalPrefTable", MODE_PRIVATE);
SharedPreferences.Editor editor7 = pref.edit();
editor7.putBoolean("isServiceActivated", false); // getting String
editor7.commit();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
//maybe will add options in a later date
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
}
#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) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.BT_wallpaper1: // superman button
//was used for testings
break;
case R.id.BT_wallpaper2: // flash button
//was used for testings
break;
case R.id.BT_wallpaper3: // captain america button
//was used for testings
break;
case R.id.BT_wallpaper4: // thor button
//was used for testings
break;
case R.id.BT_wallpaper5: // wonder woman button
//was used for testings
break;
case R.id.BT_startService: // starts the service
//starts the service up
Intent i= new Intent(this, myService.class);
startService(i);
break;
case R.id.BT_stopService: // stops the service
//stop the service
Intent j= new Intent(this, myService.class);
stopService(j);
//updates ths shared prefrence that there is no service suning any moew
SharedPreferences pref = getApplicationContext().getSharedPreferences("myGlobalPrefTable", MODE_PRIVATE);
SharedPreferences.Editor editor7 = pref.edit();
editor7.putBoolean("isServiceActivated", false); // getting String
editor7.commit();
break;
}
}
}
I believe for this case you should use the AlarmManager instead of timer + handler. It gives you a way to perform time-based operations outside the lifetime of your application.
Here is an example of scheduling using AlarmManager
https://stackoverflow.com/a/8801990/1163224
I decided to add as nipped of code how to use AlarmManager to make my answer more complete
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.PowerManager;
import android.widget.Toast;
public class Alarm extends BroadcastReceiver
{
#Override
public void onReceive(Context context, Intent intent)
{
PowerManager pm = (PowerManager) context.getSystemService(Context.POWER_SERVICE);
PowerManager.WakeLock wl = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "");
wl.acquire();
// Put here YOUR code.
Toast.makeText(context, "Alarm !!!!!!!!!!", Toast.LENGTH_LONG).show(); // For example
wl.release();
}
public void SetAlarm(Context context)
{
AlarmManager am =( AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i = new Intent(context, Alarm.class);
PendingIntent pi = PendingIntent.getBroadcast(context, 0, i, 0);
am.setRepeating(AlarmManager.RTC_WAKEUP, System.currentTimeMillis(), 1000 * 60 * 10, pi); // Millisec * Second * Minute
}
public void CancelAlarm(Context context)
{
Intent intent = new Intent(context, Alarm.class);
PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0);
AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
alarmManager.cancel(sender);
}
}
Add to Manifest.xml:
<uses-permission android:name="android.permission.WAKE_LOCK"></uses-permission>
<receiver android:process=":remote" android:name=".Alarm"></receiver>
Service
public class YourService extends Service
{
Alarm alarm = new Alarm();
#Override
public int onStartCommand(Intent intent, int flags, int startId)
{
alarm.SetAlarm(this);
return START_STICKY;
}
....
}
In the Link above is a full code of how to create a service and start a service on boot
Hope you find my answer useful. :)

how can i check a time more than one time

I have a class that takes a time from a user by time picker ,the time picker action should be compared with current phone time ,when current phone time is same with which user set ,the app should trigger a media player called mediaplayer like an alarm .now the problem is I cant check the timepicker time with the current phone time more than one time .
import java.util.Calendar;
import android.app.Activity;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.os.Handler;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TimePicker;
import android.widget.Toast;
public class Sabah2 extends Activity {
Button btn;
Intent i;
int hour,min;
static TimePicker picker;
private Handler hh;
private Runnable rr;
Calendar c = Calendar.getInstance();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sabah2);
final MediaPlayer mp = MediaPlayer.create(Sabah2.this, R.raw.salam);
picker = (TimePicker) findViewById(R.id.timePicker1);
btn = (Button) findViewById(R.id.sabah_save);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
hour=picker.getCurrentHour();
min=picker.getCurrentMinute();
Toast.makeText(getApplicationContext(), "The Alarm has been
Activated At "+hour+":"+min, Toast.LENGTH_SHORT).show();
}
});
if(hour==c.get(Calendar.HOUR)&&min==c.get(Calendar.MINUTE))
{
mp.start();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.sabah2, menu);
return true;
}
}
You have to set the alarmanager for the time in the timepicker.If the time matches with current time it will trigger the alarm and play the mediaplayer .something like this
AlarmManager alarmanager=(AlarmManager) getSystemService(Context.ALARM_SERVICE);
TimePicker ti = (TimePicker) findViewById(R.id.time_alarm);
ti.setOnTimeChangedListener(new OnTimeChangedListener() {
public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
// TODO Auto-generated method stub
selectedhour = hourOfDay;
selectedminute = minute;
count = 2;
}
});
now convert the selectedhour and selectedminute into millisecond and set it to alarmanager
alarmanager.set(AlarmManager.RTC_WAKEUP, time in millisec,pndingIntent) ;
You have to use a service to check for the time.In this service check your time with current time.This will be in background and thus will try to check the instance of time even when your ap is not running.

What would I use to grab a TextView from the MainActivity within a DialogFragment?

I'm writing a simple app that opens up a time picker dialog, asks for input, checks it against the system time, and tells you whether or not it is correct. However, I need to grab the TextView that displays whether it is true or false, and change it within the TimePickerFragment which is a DialogFragment. What should I do?
TimePickerFragment.java
package com.example.timechecker;
import java.util.Calendar;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.text.format.DateFormat;
import android.widget.TimePicker;
public class TimePickerFragment extends DialogFragment
implements TimePickerDialog.OnTimeSetListener {
int hour;
int minutes;
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Use the current time as the default values for the picker
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minutes = c.get(Calendar.MINUTE);
// Create a new instance of TimePickerDialog and return it
return new TimePickerDialog(getActivity(), this, 12, 00,
DateFormat.is24HourFormat(getActivity()));
}
public void onTimeSet(TimePicker view, int hourOfDay, int minute) {
//Grab the Text View from the Main Activity
// MainActivity m = new MainActivity();
// m.grabText text = new m.grabText();
//Check if given Picker value is == to the system time, display whether or not it is so
if (hourOfDay == hour && minutes == minute) {
text.setText("You are correct!");
} else {
text.setText("You are incorrect!");
}
}
}
MainActivity.java
package com.example.timechecker;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.View;
import android.widget.TextView;
public class MainActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//Creates the dialog with the Time Picker
public void checkTime(View view) {
DialogFragment newFragment = new TimePickerFragment();
newFragment.show(getSupportFragmentManager(), "timePicker");
}
//Class to grab the Text View for the Dialog Fragment
public class grabText {
TextView text = (TextView) findViewById(R.id.whatTime);
//Uses a method to set the Text View text
public void setText(String string) {
text.setText(string);
}
}
}
When you call findViewById in any activity then i searches in activity layout only. therefore to get the TextView from a dialog you need a reference to that dialog and then you call dialog.findViewById(id_of_field) and this will give you desired TextView.
Hope this Helps
I recently did this, I was able to do this by making MainActivity.java the parent of my DialogFragment.
MainActivity.Java
Add this to MainActivity:
#Override
protected void onCreate(Bundle savedInstanceState) {
mActivity = this;
After, make it global here:
public class MainActivity extends Activity {
MainActivity mActivity;
DialogFragment
Add this to DialogFragment:
public void setParent(MainActivity parent) {
mParent = parent;
}
After, make it global here:
public class ClearDialogModern extends DialogFragment {
MainActivity mParent;
EDIT: Here's where you setParent. Put this in your MainActivity.java onCreate:
newDialogFragment = new DialogFragment();
newDialogFragment.setParent(mActivity);
How to use:
You can now use mParent to reference the MainActivity.java.

Trying to access functions from MainActivity

I am trying to access MainActivity function to my another java class. But i am not able to use these function. Please tell me what else need to be added to get it access.
My code:
Where i am trying to access my MainActivity
package com.example.musicplayer;
**import com.example.musicplayer.MainActivity;**
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
public class current_song extends Activity implements OnClickListener{
MainActivity ma = new MainActivity();
protected void onCreate(Bundle icicle) {
Bundle extra = getIntent().getExtras();
super.onCreate(icicle);
setContentView(R.layout.songplay_page);
if(extra != null){
String song_name = extra.getString("song_name");
TextView textchange = (TextView)findViewById(R.id.current_song_name);
textchange.setText(song_name);
textchange.setSelected(true);
}
Button btn_pause = (Button)findViewById(R.id.pause_btn);
btn_pause.setOnClickListener(this);
Button btn_next = (Button)findViewById(R.id.next_btn);
btn_next.setOnClickListener(this);
Button btn_prv = (Button)findViewById(R.id.prv_btn);
btn_prv.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "In Onclick ()", Toast.LENGTH_SHORT).show();
switch(v.getId())
{
case R.id.pause_btn:
Toast.makeText(getApplicationContext(), "pause", Toast.LENGTH_SHORT).show();
ma.pause();
break;
case R.id.next_btn:
ma.next();
break;
case R.id.prv_btn:
ma.prv();
break;
}
}
}
Make sure that MainActivity has a zero argument constructor and the access specifier for pause , next and prv function is public.
In response to "i have some methods defined by me stop(), next(), pri() i am trying to access these methods when i click on each button. If you think that "creating a separate common class for sharing all methods" can you please show me 1 example bec i don't know how to access a method from 1 activity to another. "
public class myController{
private MyActivity m;
public myController(MyActivity m){
this.m = m;
}
public void stop(){
m.stop;
}
}
In other classes you initialize in the main activity and pass it the controller object so it can call the stop method

Categories

Resources