Save the state of button in Xamarin Android - 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.

Related

Access data from SharedPreferences at boot time

I want to start service at boot time. Its working fine.I now i want to start service only if toggle button is on.I am saving state of toggle button state in SharedPreferences.
PROBLEM
I am getting default value from SharedPreferences that is false in my case
CODE of BroadcastReceiver is as follows
public class MyReceiver extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
SharedPreferences saved_values=context.getApplicationContext().getSharedPreferences( "ServiceLockTest", Context.MODE_PRIVATE);
boolean checkstate = saved_values.getBoolean("tgpref", false); // return false
int pr=saved_values.getInt("progess", 100); //return 100
TheService.SHAKE_THRESHOLD=pr;
if(checkstate)
{
Intent myIntent = new Intent(context, TheService.class);
context.startService(myIntent);
}
else
{
Toast.makeText(context,"yoooooooooooooooooooooo" , Toast.LENGTH_LONG).show();
System.out.println(pr);
System.out.println(checkstate);
}
}
}
code of saving state of toggle button
if (isChecked) {
SharedPreferences.Editor editor = preferences.edit();
editor.putBoolean("tgpref", true); // value to store
editor.commit();
// The toggle is enabled
if (mgr.isAdminActive(cn))
{
Toast.makeText(getBaseContext(),"Service is afor",Toast.LENGTH_LONG).show();
}
else
{
Log.i("Admin", "Not an admin");//mean admin is not active
showAct();//will open new activity
}
}
Please help.thanks

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.

How to change background color or theme of keys dynamically in Custom Keyboard Android

I am working on Custom keyboard app I need to set or change background theme or color of keyboard .their setting.xml view in my app where user can select different background theme and different color for key rows.
during first time launch of application it is working fine but next time when custom keyboard is displaying theme is not changed.
I am using this code:
public class SoftKeyboard extends InputMethodService
implements KeyboardView.OnKeyboardActionListener {
static final boolean DEBUG = false;
/**
* This boolean indicates the optional example code for performing
* processing of hard keys in addition to regular text generation
* from on-screen interaction. It would be used for input methods that
* perform language translations (such as converting text entered on
* a QWERTY keyboard to Chinese), but may not be used for input methods
* that are primarily intended to be used for on-screen text entry.
*/
static final boolean PROCESS_HARD_KEYS = true;
private static final int SELECT_PICTURE = 101;
private KeyboardView mInputView;
private CandidateView mCandidateView;
private CompletionInfo[] mCompletions;
private Context context = SoftKeyboard.this;
private StringBuilder mComposing = new StringBuilder();
private boolean mPredictionOn;
private boolean mCompletionOn;
private int mLastDisplayWidth;
private boolean mCapsLock;
private long mLastShiftTime;
private long mMetaState;
private LatinKeyboard mSymbolsKeyboard;
private LatinKeyboard mSymbolsShiftedKeyboard;
private LatinKeyboard mQwertyKeyboard;
private LatinKeyboard mSmilyKeyboard;
private LatinKeyboard mSmilyKeyboard1;
private LatinKeyboard mCurKeyboard;
private String mWordSeparators;
/**
* Main initialization of the input method component. Be sure to call
* to super class.
*/
#Override
public void onCreate() {
super.onCreate();
mWordSeparators = getResources().getString(R.string.word_separators);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
String name = preferences.getString("Name","");
Log.e("SoftKeyboard - ",""+name+"OnCreate Method Called--");
if(!name.equalsIgnoreCase(""))
{
name = name+" Sethi"; /* Edit the value here*/
}
}
And This is my Setting Class where i am setting or selecting color or theme:
public class Setting extends Activity implements OnClickListener {
LinearLayout roar, edge, burst, impact, blue_theme, orange_theme,
green_theme, black_brigthness, white_brightness;
Bundle bundle;
public static boolean isblackBrightness = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.setting);
// ----------UI intilisation---------------------
uiInitilisation();
}
public void uiInitilisation() {
roar = (LinearLayout) findViewById(R.id.ror_LL);
edge = (LinearLayout) findViewById(R.id.edge_LL);
burst = (LinearLayout) findViewById(R.id.burst_LL);
impact = (LinearLayout) findViewById(R.id.impact_LL);
// -------------Themes------------------------------
blue_theme = (LinearLayout) findViewById(R.id.blue_theme_LL);
orange_theme = (LinearLayout) findViewById(R.id.orange_theme_LL);
green_theme = (LinearLayout) findViewById(R.id.green_theme_LL);
// ------------Brightness----------------------------
black_brigthness = (LinearLayout) findViewById(R.id.black_brigthness_LL);
white_brightness = (LinearLayout) findViewById(R.id.white_brigthness_LL);
// --------------On Click Events-------------------
roar.setOnClickListener(this);
edge.setOnClickListener(this);
burst.setOnClickListener(this);
impact.setOnClickListener(this);
// -----------Theme-------------------------------------
blue_theme.setOnClickListener(this);
orange_theme.setOnClickListener(this);
green_theme.setOnClickListener(this);
// ------------------Brightness--------------------------
black_brigthness.setOnClickListener(this);
white_brightness.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch (v.getId()) {
case R.id.ror_LL:
startActivity(new Intent(Setting.this, MainActivity.class));
break;
case R.id.edge_LL:
startActivity(new Intent(Setting.this, MainActivity.class));
break;
case R.id.burst_LL:
startActivity(new Intent(Setting.this, MainActivity.class));
break;
case R.id.impact_LL:
startActivity(new Intent(Setting.this, MainActivity.class));
break;
case R.id.blue_theme_LL:
Intent i = new Intent(Setting.this,
MainActivity.class);
i.putExtra("color", "blue");
startActivity(i);
break;
case R.id.orange_theme_LL:
Intent i2 = new Intent(Setting.this,
MainActivity.class);
i2.putExtra("color", "orange");
startActivity(i2);
break;
case R.id.green_theme_LL:
Intent i3 = new Intent(Setting.this,
MainActivity.class);
i3.putExtra("color", "green");
startActivity(i3);
break;
case R.id.black_brigthness_LL:
Intent black_britness = new Intent(Setting.this,
MainActivity.class);
black_britness.putExtra("bright", "black");
startActivity(black_britness);
SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor = preferences.edit();
editor.putString("Name","Harneet");
editor.commit();
isblackBrightness = true ;
Log.e("Black--","Black=="+isblackBrightness);
break;
case R.id.white_brigthness_LL:
Intent white_britness = new Intent(Setting.this,
MainActivity.class);
white_britness.putExtra("bright", "white");
startActivity(white_britness);
isblackBrightness = false;
Log.e("white--","White=="+isblackBrightness);
SharedPreferences preferences1 = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor editor1 = preferences1.edit();
editor1.putString("Name","Arun");
editor1.commit();
break;
}
}
}
I am not getting how to do this whether I have to set widget.
When the keyboard is shown, the framework calls onStartInputView. You can program that function to look at the values of the shared preferences and set the colors/themes appropriately on the keyboard view.
Get solution to change the layout of custom keyboard.
When keyboard first time load onCreateInputView() is called. After that when keyboard open onStartInputView(EditorInfo attribute, boolean restarting) called every time.
So, now layout of keyboard(Theme) have to define in onCreateInputView() Like This
public KeyboardView mInputView;
public View onCreateInputView() {
SharedPreferences pre = getSharedPreferences("test", 1);
int theme = pre.getInt("theme", 1);
if(theme == 1)
{
this.mInputView = (KeyboardView) this.getLayoutInflater().inflate(R.layout.input, null);
}else
{
this.mInputView = (KeyboardView) this.getLayoutInflater().inflate(R.layout.input_2, null);
}
this.mInputView.setOnKeyboardActionListener(this);
this.mInputView.setKeyboard(this.mQwertyKeyboard);
return this.mInputView;
}
and do this in onStartInputView
public void onStartInputView(EditorInfo attribute, boolean restarting) {
super.onStartInputView(attribute, restarting);
setInputView(onCreateInputView());
}

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.

Set airplanemode at a specific time

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!

Categories

Resources