Set airplanemode at a specific time - android

public class AirPlaneModeActivity extends Activity {
Button b;
TimePicker tp;
Calendar cal;
AlarmManager am ;
PendingIntent pi;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
b = (Button)findViewById(R.id.button1);
tp = (TimePicker)findViewById(R.id.timePicker1);
cal = Calendar.getInstance(Locale.getDefault());
am = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
tp.setIs24HourView(true);
b.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
cal.set(Calendar.HOUR_OF_DAY,tp.getCurrentHour());
cal.set(Calendar.MINUTE,tp.getCurrentMinute());
cal.set(Calendar.SECOND,0);
}
});
pi = PendingIntent.getBroadcast(this, 0, setAPM(), 0);
am.set(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(),pi);
}
public Intent setAPM(){
boolean isEnabled = Settings.System.getInt(
getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) == 1;
// toggle airplane mode
Settings.System.putInt(getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, isEnabled ? 0 : 1);
// Post an intent to reload
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", !isEnabled);
return intent;
}
}
I want to change the airplanemode at the setted time, that I get from a timepicker.
Then I set the time from the timepicker into a calender from witch I get the time for the alarmmanager.set Method but it doesn't do anything.
I watch all over the internet but I didn't found anything. I found this post on stackoverflow but without answer
(Sorry for my bad english)
Thanks for your answers

I found this in My code toggles airplane mode continuously
/** Code snippet in AirplaneModeService*/
#Override
public void onCreate() {
airplaneModeToggler = new AirplaneModeToggler(this);
Thread mThread = new Thread(null, airplaneModeToggleTask, "AirplaneModeToggleTask");
mThread.start();
}
private Runnable airplaneModeToggleTask = new Runnable() {
#Override
public void run() {
airplaneModeToggler.toggle(null);
AirplaneModeService.this.stopSelf();
}
};
I think you need to do an asynchronous task to d that as you can see up here or in the post I linked you.
Edit: I also found here How can one detect airplane mode on Android? in the answer the way to know if it is activated or not (to do something or not ;) )
/**
* Gets the state of Airplane Mode.
*
* #param context
* #return true if enabled.
*/
private static boolean isAirplaneModeOn(Context context) {
return Settings.System.getInt(context.getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) != 0;
}
And finally I found this http://dustinbreese.blogspot.com.es/2009/04/andoid-controlling-airplane-mode.html where I think there is all you need!

Related

if and return statement

I am new to Android programming, and now I'm working on an application to remind me of the schedule of my lectures. For example, a lecture starts at 12:30 and ends at 1:30 pm. The application will notify me at the date, and turn my phone into the silent mode. My application now works well, but the problem is that after the end of the lecture the app should turn back the phone into Normal mode .
my main_activity Code:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ring(12,21,0);
ring(12,30,1);
}
public void ring (int h,int m,int mode){
/** This intent invokes the activity DemoActivity, which in turn opens the AlertDialog window */
Intent i = new Intent("in.wptrafficanalyzer.servicealarmdemo.demoactivity");
i.putExtra("mode",mode);
/** Creating a Pending Intent */
PendingIntent operation = PendingIntent.getActivity(getBaseContext(), 0, i, Intent.FLAG_ACTIVITY_NEW_TASK);
/** Getting a reference to the System Service ALARM_SERVICE */
AlarmManager alarmManager = (AlarmManager) getBaseContext().getSystemService(ALARM_SERVICE);
int year = Calendar.getInstance().get(Calendar.YEAR);
int month = Calendar.getInstance().get(Calendar.MONTH);
int day = Calendar.getInstance().get(Calendar.DAY_OF_MONTH);
int hour = h;
int minute = m;
/** Creating a calendar object corresponding to the date and time set by the user */
GregorianCalendar calendar = new GregorianCalendar(year,month,day, hour, minute);
/** Converting the date and time in to milliseconds elapsed since epoch */
long alarm_time = calendar.getTimeInMillis();
/** Setting an alarm, which invokes the operation at alart_time */
alarmManager.set(AlarmManager.RTC_WAKEUP , alarm_time , operation);
/** Alert is set successfully */
Toast.makeText(getBaseContext(), "Alarm is set successfully",Toast.LENGTH_SHORT).show();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
my DemoActivity code :
public class DemoActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/** Creating an Alert Dialog Window */
AlertDemo alert = new AlertDemo();
/** Opening the Alert Dialog Window */
alert.show(getSupportFragmentManager(), "AlertDemo");
}
}
my problem is in AlertDemo code:
public Dialog onCreateDialog(Bundle savedInstanceState) {
am = (AudioManager) getActivity().getBaseContext().getSystemService(Context.AUDIO_SERVICE);
Intent i = this.getActivity().getIntent();
int info = this.getActivity().getIntent().getIntExtra("mode", 0);
if (info == 0) {
/** Turn Screen On and Unlock the keypad when this alert dialog is displayed */
getActivity().getWindow().addFlags(LayoutParams.FLAG_TURN_SCREEN_ON | LayoutParams.FLAG_DISMISS_KEYGUARD);
/** Creating a alert dialog builder */
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
/** Setting title for the alert dialog */
builder.setTitle("Alarm");
/** Setting the content for the alert dialog */
builder.setMessage("An Alarm by AlarmManager");
Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
final Ringtone ringtone = RingtoneManager.getRingtone(getContext(), uri);
ringtone.play();
handler.postDelayed(new Runnable() {
#Override
public void run() {
am.setRingerMode(AudioManager.RINGER_MODE_SILENT);
}
}, 300000);
/** Defining an OK button event listener */
builder.setPositiveButton("OK", new OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
/** Exit application on click OK */
getActivity().finish();
ringtone.stop();
}
});
/** Creating the alert dialog window */
return builder.create();
}
else
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
the problem is missing return statement when i add the statement "return null"
This error appears(Application stopped):
java.lang.RuntimeException: Unable to start activity ComponentInfo{in.wptrafficanalyzer.servicealarmdemo/in.wptrafficanalyzer.servicealarmdemo.DemoActivity}: java.lang.NullPointerException
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:1970)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:1995)
at android.app.ActivityThread.access$600(ActivityThread.java:128)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1161)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:4517)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:993)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:760)
at dalvik.system.NativeStart.main(Native Method)
In case you return null, your alert object is null. Then you go ahead and ask to perform the "show" method on this object, hence the null pointer exception. Since you do it in the "onCreate" method if DemoActivity, your activity fails to start. Try to make the decision of whether to show the dialog or not beforehand, previously to creating the alert itself. Then just create (and show) the alert only when the mode is suitable (by the way, Java has booleans, why are you using integers?).
Don't do decision making in onCreateDialog method. Remove if-else block out of onCreateDialog
public class DemoActivity extends FragmentActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
am = (AudioManager) getActivity().getBaseContext().getSystemService(Context.AUDIO_SERVICE);
Intent i = this.getActivity().getIntent();
int info = this.getActivity().getIntent().getIntExtra("mode", 0);
if (info == 0) {
AlertDemo alert = new AlertDemo();
/** Opening the Alert Dialog Window */
alert.show(getSupportFragmentManager(), "AlertDemo");
} else
am.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
}
}

Save the state of button in Xamarin Android

I'm disabling buttons once they are pressed. I want it to activate automatically
the next day at 12AM. I really have no idea how to do this. Somehow I tried and written the code below.
The code disables the buttons after a click. But it is looses his state once the app is closed. Please help me how can I do this?
public class MainActivity : Activity
{
Button button1;
Button button2;
protected override void OnCreate (Bundle savedInstanceState)
{
base.OnCreate (savedInstanceState);
// Set our view from the "main" layout resource
SetContentView (Resource.Layout.Main);
mybroadcast myrec = new mybroadcast ();
Database sqldb1 = ((GlobalClass)this.Application).sqldb;//This will contain "Hello World"
string stringFromApplicationClass = ((GlobalClass)this.Application).myString;//This will contain "Hello World"
var now = DateTime.Now;
string dataFormatada = string.Format("{0:00}/{1:00}/{2:0000}", now.Month, now.Day, now.Year);
string currentTime = (string.Format ("Current Time: {0}", now.Hour));
// Get our button from the layout resource,
// and attach an event to it
button1 = FindViewById<Button> (Resource.Id.Button1);
button2 = FindViewById<Button> (Resource.Id.Button2);
button1.Click += delegate {
sqldb1.AddRecord (1);
};
button2.Click += delegate {
sqldb1.AddRecord (0);
};
}
public void start()
{
Intent myIntent = new Intent (this,typeof( mybroadcast));
AlarmManager alarmMgr = (AlarmManager) this.GetSystemService(Context.AlarmService);
PendingIntent pendingIntent = PendingIntent.GetService(this, 0, myIntent, 0);
Calendar calendar = Calendar.GetInstance (Java.Util.TimeZone.Default);
calendar.Set(CalendarField.HourOfDay, 12);
calendar.Set(CalendarField.Millisecond, 00);
calendar.Set(CalendarField.Second, 00);
alarmMgr.SetRepeating(AlarmType.Rtc,0, 10, pendingIntent); //Repeat every 24 hours
}
public class mybroadcast:BroadcastReceiver
{
public override void OnReceive(Context context, Intent myIntent)
{
((MainActivity)context).enablebutton();
}
}
public override bool OnCreateOptionsMenu(IMenu menu)
{
base.OnCreateOptionsMenu (menu);
MenuInflater inflater = this.MenuInflater;
inflater.Inflate (Resource.Menu.items, menu);
return base.OnCreateOptionsMenu(menu);
}
public override bool OnOptionsItemSelected (IMenuItem item)
{
base.OnOptionsItemSelected (item);
switch (item.ItemId)
{
case Resource.Id.week:
StartActivity(typeof(SecondActivity));
break;
case Resource.Id.month:
{
StartActivity(typeof(ThirdActivity));
break;
}
default:
break;
}
return true;
}
public void disablebutton()
{
button1.Enabled = false;
button2.Enabled = false;
}
public void enablebutton()
{
button1.Enabled = true;
button2.Enabled = true;
}
}
Even though this code is in java, the concept will be the same. Once the alarm goes off, the Broadcastreceiver's onReceive is called, where you can edit the sharedpreference to enable/disable views. If you don't know about sharedpreferences, see these links: How do I use SharedPreferences in Xamarin.Android? , SharedPreferences Example in Xamarin Android
BroadCastReceiver:
public class ReminderActivity extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
//Use sharepreference and set the button state disabled or enabled.
SharedPreferences mSharedPreferences = getSharedPreferences("MyPref", 0);
mSharedPreferences..edit().putBoolean("btn_enable", true).commit();
}
}
So once you open the app, check for sharedpreference value and enable or disable the button state accordingly.
Hope this helps.

Enable and Disable Airplane Mode successively Android

I am just a starter in Android. I have an Android code which has a Button. On click of the button, it should Invoke AirPlane mode and then again back to normal mode. Here is my code :
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// load controls
tvStatus = (TextView)findViewById(R.id.tvStatus);
togState = (Button)findViewById(R.id.togState);
// set click event for button
togState.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// check current state first
boolean state = isAirplaneMode();
// toggle the state
toggleAirplaneMode(state);
state = isAirplaneMode();
// toggle the state
toggleAirplaneMode(state);
}
});
}
public void toggleAirplaneMode(boolean state) {
// toggle airplane mode
Settings.System.putInt(this.getContentResolver(),Settings.System.AIRPLANE_MODE_ON, state ? 0 : 1);
// broadcast an intent to inform
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", !state);
sendBroadcast(intent);
}
public boolean isAirplaneMode() {
return Settings.System.getInt(this.getContentResolver(), Settings.System.AIRPLANE_MODE_ON, 0) == 1;
}
}
The problem here is, my phone will go in AirPlane mode and it toggles back also. But this process I cannot stop. Is the problem with the way I handled the OnClick Listener by calling same method (toggleAirplaneMode) twice?
Regards,
This answer contains code necessary to do this. Also make sure you have the WRITE_SETTINGS permission.
Adapted from Controlling Airplane Mode:
// read the airplane mode setting
boolean isEnabled = Settings.System.getInt(
getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, 0) == 1;
// toggle airplane mode
Settings.System.putInt(
getContentResolver(),
Settings.System.AIRPLANE_MODE_ON, isEnabled ? 0 : 1);
// Post an intent to reload
Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
intent.putExtra("state", !isEnabled);
sendBroadcast(intent);
Replace the onClick method with this:
public void onClick(View v) {
// check current state first
boolean state = isAirplaneMode();
// toggle the state
final Handler handler = new Handler(){
#Override
public void handleMessage(Message msg) {
toggleAirplaneMode(!state);
super.handleMessage(msg);
}
};
Thread th = new Thread() {
#Override
public void run() {
toggleAirplaneMode(!state);
handler.sendEmptyMessage(0);
};
};
th.start();
}
Every time you will click the button, it will toggle the airplaneMode.
If it doesn't work, try removing !
Check this out... This might help..
public class MainActivity extends Activity {
Context context;
private void changeRadioComponentEnabled(Context paramContext, String paramString, boolean paramBoolean1, boolean paramBoolean2)
{
boolean bool = false;
ContentResolver localContentResolver = paramContext.getContentResolver();
int i;
if (!paramBoolean1)
i = 1;
else
i = 0;
Settings.System.putInt(localContentResolver, "airplane_mode_on", i);
Settings.System.putString(paramContext.getContentResolver(), "airplane_mode_radios", paramString);
Intent localIntent = new Intent("android.intent.action.AIRPLANE_MODE");
if (!paramBoolean1)
bool = true;
localIntent.putExtra("state", bool);
paramContext.sendBroadcast(localIntent);
if (!paramBoolean2)
{
if (paramString.indexOf("cell") == 0)
Settings.System.putString(paramContext.getContentResolver(), "airplane_mode_radios", "cell");
}
else
Settings.System.putString(paramContext.getContentResolver(), "airplane_mode_radios", "cell,bluetooth,wifi,nfc");
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.context = this;
((Button)findViewById(R.id.button1)).setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
MainActivity.this.changeRadioComponentEnabled(MainActivity.this.context, "cell", false, false);
}
});
((Button)findViewById(R.id.button2)).setOnClickListener(new View.OnClickListener()
{
public void onClick(View paramAnonymousView)
{
MainActivity.this.changeRadioComponentEnabled(MainActivity.this.context, "cell", true, false);
}
});
}
I got it finally
I used this in my code
public void onClick(View v) {
// check current state first
boolean state = isAirplaneMode();
// toggle the state
toggleAirplaneMode(state);
state = isAirplaneMode();
// toggle the state
toggleAirplaneMode(state);
ser = new ServiceState();
ser.setState(STATE_IN_SERVICE);
}
And I have declared final int STATE_IN_SERVICE = 0; before OnCreate. And ser is the instance of ServiceState.
Thank you for your replies.

Two layouts for same same activity

I have the following code in my activity:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!isPreviouslyLoggedIn()) {
setContentView(R.layout.splash);
final TextView revolution=(TextView) findViewById(R.id.textView1);
final Button login=(Button) findViewById(R.id.loginButton);
final Button signUp=(Button) findViewById(R.id.signUpButton);
login.setOnClickListener(loginListener);
signUp.setOnClickListener(signUpListener);
}
else {
setContentView(R.layout.home);
Intent intent = new Intent(getApplicationContext(), PickUpActivity.class);
startActivity(intent);
}
}
When the if statements are executed, the layout is set to splash. However, in cases when the else statement is executed the layout is not set to home and the intent is directly started. Why is this happening and how can I prevent this?
Try this way..
protected boolean active = true;
protected int time = 5000;
Thread thread = new Thread() {
#Override
public void run() {
try {
int waited = 0;
while (active && (waited < time)) {
sleep(100);
if (active) {
waited += 100;
}
}
} catch (InterruptedException e) {
} finally {
finish();
Intent Go_Activity = new Intent(Screen.this, otherActivity.class);
startActivity(Go_Activity);
stop();
}
}
};
thread.start();
It help you.
Thanks.
Set Any Time or Thread to wait some time to go next activity. When else statement executed then layout set but for few time. for this reason you do not able to show it.
Thanks
You know what are you trying to ask ?? After setting content view straightly you are starting the another activity so it will show the new(started)activity layout... what is wrong then ?

Pass information from CustomDialog to main Activity

I'm writting an app which manages alarms and events as in a calendar app. I ran into a problem when I tried to get all the info about the event that was reported in a custom dialog. I tried many things. The last one thing to that I saw on internet uses intents. However latheough the Dialog can send the info, I dont know how to receive it. I try something with broadcast recevier but it didn't work...
-->Here is the code for the dialog:
public class AddingEventMenu extends Dialog implements OnClickListener {
Event event = new Event();
private Button b;
Context context;
public AddingEventMenu(Context context) {
super(context);
this.context = context;
this.setContentView(R.layout.addbuttonlayout);
this.setTitle("Adding Event");
this.setCancelable(true);
this.b = (Button) findViewById(R.id.addEventButton);
this.b.setOnClickListener(this);
}
public void onClick(View v) {
String color;
DatePicker DP = (DatePicker) findViewById(R.id.datePicker);
TimePicker TP = (TimePicker) findViewById(R.id.timePicker);
EditText ET = (EditText) findViewById(R.id.eventText);
Spinner SC = (Spinner) findViewById(R.id.colorSelector);
Intent intent = new Intent();
intent.setAction("New Event");
color = SC.getSelectedItem().toString();
if (color == "Red") event.eventColor = Color.RED;
if (color == "Green") event.eventColor = Color.GREEN;
if (color == "Blue") event.eventColor = Color.BLUE;
if (color == "Magenta") event.eventColor = Color.MAGENTA;
intent.putExtra("Text", ET.getText().toString());
intent.putExtra("Day", DP.getDayOfMonth());
intent.putExtra("Month", DP.getMonth());
intent.putExtra("Year", DP.getYear());
intent.putExtra("Hour", TP.getCurrentHour() * 100 + TP.getCurrentMinute());
intent.putExtra("Color", color);
context.sendBroadcast(intent);
Log.d("State", "Es un primer paso");
this.dismiss();
}
-->Here the main menu code:
public class Timetable extends Activity {
public static List<Event> eventList;
EventManager eventManager;
LinearLayout eventListLayout;
ImageView addButton;
EventDatabaseManager db;
BroadcastReceiver BR;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
this.requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.layout_timetable);
BR = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() == "New event"){
Bundle extras = new Bundle();
Event event = new Event();
extras = intent.getExtras();
event.eventText = extras.getString("Text");
event.eventDay = extras.getInt("Day");
event.eventMonth = extras.getInt("Month");
event.eventYear = extras.getInt("Year");
event.eventHour = extras.getInt("Hour");
event.eventColor = extras.getInt("Color");
Log.d("State", "Esta funcionando");
saveNewEvent(event);
}
}
};
db = new EventDatabaseManager(this);
eventListLayout = (LinearLayout) findViewById(R.id.eventListLayout);
eventManager = new EventManager(this);
eventList = eventManager.getEvents();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.layout_timetable, menu);
return true;
}
public void onAddButton(View button) {
AddingEventMenu aEM = new AddingEventMenu(this);
aEM.show();
}
public void saveNewEvent(Event event) {
eventList.add(event);
db.addEvent(event);
}
In the main Activity I defined the broadcastreceiver, but I think that it's wrong, because it doesn't anything there.
I hope someone can help me. Thanks for your time.
EHave you registered your broadcast receiver. You can do it like this:
IntentFilter filter = new IntentFilter();
filter.addAction( "New Event" );
registerReceiver( BR, observerFilter );
You should put this code in your onCreate method. Don't forget to unregister receiver using
unregisterReceiver( BR );
in onDestroy method
And also you use
intent.setAction("New Event");
in your onClick method but in your onReceive method you use
if( intent.getAction() == "New event" )
Change it to
if( intent.getAction() == "New Event" )
In order to be future compatible you should consider using DialogFragment instead of
Dialog.
When using the DialogFragment you can add a custom listener to the DialogFragment class like this one:
public interface EventAddedListener {
public void onEventAdded(Event event);
}
and then add it to your DialogFragment.
After an event has been chosen you call listener.onEventAdded(event); and handle the result within your Activity.
But you can also work with the more complicated IntentFilter solution provided by sinisha, even when using a DialogFragment.

Categories

Resources