Pass information from CustomDialog to main Activity - android

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.

Related

App is crashing when I click the button - two intents in a button - using Enum

I need help with my code. Let me try to explain the problem:
At the first activity I have two fields where I'll set values from an Enum, for this I made a button for each field that basically shows me another activity, calls the value and brings it to the main activity. Still in the first activity I have a button that starts another activity and (at the same time) take all the values from the enum end sends to another activity. The point is, everything is working, but this last button no, when I click it the app crashes. What is happening and how can I solve it?
Here goes the code of the first activity:
public class MenuInicial extends AppCompatActivity {
public static final int CONSTANTE_BANZO = 1;
Button escolherM;
Button escolherB;
Button next;
TextView campoM;
TextView campoB;
Intent intent1;
Intent intent2;
Intent intentBundle;
Intent intentNext;
Bundle bundle;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_menu_inicial);
intent1 = new Intent(MenuInicial.this, Montante.class);
campoM = (TextView) findViewById(R.id.fieldM);
escolherM = (Button) findViewById(R.id.chooseM);
String perfilM = getIntent().getExtras().getString("nameM");
campoM.setText(perfilM);
escolherM.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
startActivity(intent1);
}
});
intent2 = new Intent(MenuInicial.this, Banzo.class);
campoB = (TextView) findViewById(R.id.fieldB);
escolherB = (Button) findViewById(R.id.chooseB);
escolherB.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v){
startActivityForResult(intent2, CONSTANTE_BANZO);
}
});
next = (Button) findViewById(R.id.prosseguir);
intentBundle = new Intent(MenuInicial.this, ConferenciaDosDados.class);
intentNext = new Intent(MenuInicial.this, Dados.class);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String perfilM = getIntent().getExtras().getString("nameM");
Float baseMt = getIntent().getExtras().getFloat("baseM");
Float alturaMt = getIntent().getExtras().getFloat("alturaM");
String perfilB = getIntent().getExtras().getString("nameB");
Float baseBz = getIntent().getExtras().getFloat("baseB");
Float alturaBz = getIntent().getExtras().getFloat("alturaB");
bundle.putString("nomeM",perfilM);
bundle.putFloat("baseM",baseMt);
bundle.putFloat("alturaM",alturaMt);
bundle.putString("nomeB",perfilB);
bundle.putFloat("baseB",baseBz);
bundle.putFloat("alturaB",alturaBz);
intentBundle.putExtras(bundle);
startActivity(intentBundle);
startActivity(intentNext);
}
});
}
protected void onActivityResult(int codigo, int resultado, Intent intent){
if(codigo == CONSTANTE_BANZO){
Bundle bundleB = intent.getExtras();
if(bundleB != null){
String perfilB = bundleB.getString("nameB");
campoB.setText(perfilB);
}
}
}
}
next = (Button) findViewById(R.id.prosseguir);
intentBundle = new Intent(MenuInicial.this, ConferenciaDosDados.class);
intentNext = new Intent(MenuInicial.this, Dados.class);
next.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
String perfilM = getIntent().getExtras().getString("nameM");
Float baseMt = getIntent().getExtras().getFloat("baseM");
Float alturaMt = getIntent().getExtras().getFloat("alturaM");
String perfilB = getIntent().getExtras().getString("nameB");
Float baseBz = getIntent().getExtras().getFloat("baseB");
Float alturaBz = getIntent().getExtras().getFloat("alturaB");
bundle.putString("nomeM",perfilM);
bundle.putFloat("baseM",baseMt);
bundle.putFloat("alturaM",alturaMt);
bundle.putString("nomeB",perfilB);
bundle.putFloat("baseB",baseBz);
bundle.putFloat("alturaB",alturaBz);
intentBundle.putExtras(bundle);
startActivity(intentBundle);
startActivity(intentNext);
}
});
Which activity do you want to go to? choose one. When you do, you can get those extras then when you need to goto the other activity, you can put those extras there too.
A better way to do it is to create a model (constructor with setters and getters) and put these in a list. At that point you can loop through the list and take what you need. It all depends on what you are doing though as the list will not be instantiated like intent extras would be.
Or, you can use SharedPref which is similar to a HashMap (which is also similar to the Intent Extras). SharedPref will store the key and value on the phones cache and then you can pull from that when you need it. Again, keep in mind that if the user clears the cache on the app, then it'll delete those shared pref.
Finally, you can also use a database such as Parse Server or Firebase.

Add a note counter to android notebook project using shared preferences

I have a notebook sample project and I want to add a "note counter" to it using shared preferences and each time the user adds a note increment the counter in createNote() method. I also added a TextView to show the counter, but the counter is always zero and doesnt increment by creating a new note! ! Help me please!
public class MainActivity extends ListActivity {
private static final int EDITOR_ACTIVITY_REQUEST = 1001;
private static final int MENU_DELETE_ID = 1002;
private int currentNoteId;
private NotesDataSource datasource;
List<NoteItem> notesList;
int count = 0;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
datasource = new NotesDataSource(this);
refreshDisplay();
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(""+count);
}
private void refreshDisplay() {
notesList = datasource.findAll();
ArrayAdapter<NoteItem> adapter =
new ArrayAdapter<NoteItem>(this, R.layout.list_item_layout, notesList);
setListAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId() == R.id.action_create) {
createNote(null);
}
return super.onOptionsItemSelected(item);
}
public void createNote(View v) {
NoteItem note = NoteItem.getNew();
Intent intent = new Intent(this, NoteEditorActivity.class);
intent.putExtra(NoteItem.KEY, note.getKey());
intent.putExtra(NoteItem.TEXT, note.getText());
startActivityForResult(intent, EDITOR_ACTIVITY_REQUEST);
int defaultValue = getPreferences(MODE_PRIVATE).getInt("count_key", count);
++defaultValue;
getPreferences(MODE_PRIVATE).edit().putInt("count_key", defaultValue).commit();
count = getPreferences(MODE_PRIVATE).getInt("count_key", count);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
NoteItem note = notesList.get(position);
Intent intent = new Intent(this, NoteEditorActivity.class);
intent.putExtra(NoteItem.KEY, note.getKey());
intent.putExtra(NoteItem.TEXT, note.getText());
startActivityForResult(intent, EDITOR_ACTIVITY_REQUEST);
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == EDITOR_ACTIVITY_REQUEST && resultCode == RESULT_OK) {
NoteItem note = new NoteItem();
note.setKey(data.getStringExtra(NoteItem.KEY));
note.setText(data.getStringExtra(NoteItem.TEXT));
datasource.update(note);
refreshDisplay();
}
}
}
Your help is appreciated. Thanks!
Based on discussion and answer given by #Rahul Tiwari...do the following modifications in your code.....
First create the instance TextView variable
//your instance variables
int count;
TextView tv;
#Override
protected void onCreate(Bundle savedInstanceState) {
//your code...
tv = (TextView) findViewById(R.id.textView1);
count = getSharedPreferences("NAME_FOR_SHARED_PREFERENCES", Context.MODE_PRIVATE).getInt("count_key", 0);
updateTextView();
}
void updateTextView(){
tv.setText(""+count);
}
//your code till here....
public void createNote(View v) {
NoteItem note = NoteItem.getNew();
SharedPreferences sharedPref = getSharedPreferences("NAME_FOR_SHARED_PREFERENCES", Context.MODE_PRIVATE);
sharedPref.edit().putInt("count_key", ++count).commit();
updateTextView()
/*for intial testing commenting this code block
Intent intent = new Intent(this, NoteEditorActivity.class);
intent.putExtra(NoteItem.KEY, note.getKey());
intent.putExtra(NoteItem.TEXT, note.getText());
startActivityForResult(intent, EDITOR_ACTIVITY_REQUEST);
*/
}
//your code.
Then you can start app multiple times and check want is the count value.
Note: When naming your shared preference files, you should use a name
that's uniquely identifiable to your app, such as
"com.example.myapp.PREFERENCE_FILE_KEY" for more detail refer
your counter is not being refreshed as you are not changing text in your text view after changing the count.
you need to use
TextView tv = (TextView) findViewById(R.id.textView1);
tv.setText(""+count);
at the end of your createNote function
use getDefaultSharedPreferences to access your shared preference across activities in your app. refer this answer for example.

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.

Set dynamically created TextView on frame layout

I want to pass some data from one activity to another and set it in dynamically created TextView over frame layout of that activity..I'm using intent for that but at second activity the data is not getting extracted..Can any one tell me the simple way for this..
Following is my code..
Hidden.java
public class Hidden extends Activity implements OnClickListener {
Button btnnameadd, btnnameremove, btnmobileadd, btnmobileremove, btndone;
EditText etname, etmobile;
ImageView ivlogo;
private AlertDialog dialog;
private Uri mImageCaptureUri;
Intent jump;
//options for image selection
private static final int PICK_FROM_CAMERA = 1;
private static final int CROP_FROM_CAMERA = 2;
private static final int PICK_FROM_FILE = 3;
LinearLayout llname, llmobile, llimage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.hidden);
captureImageInitialization();
init();
}
private void init() {
etname=(EditText)findViewById(R.id.editTextname);
etmobile=(EditText)findViewById(R.id.editTextmobile);
btnnameadd=(Button)findViewById(R.id.buttonnameadd);
btnnameremove=(Button)findViewById(R.id.buttonnameremove);
btnmobileadd=(Button)findViewById(R.id.buttonmobileadd);
btnmobileremove=(Button)findViewById(R.id.buttonmobileremove);
btndone=(Button)findViewById(R.id.buttondone);
llname=(LinearLayout)findViewById(R.id.name);
llmobile=(LinearLayout)findViewById(R.id.mobile);
btnnameadd.setOnClickListener(this);
btnnameadd.setOnClickListener(this);
btnnameremove.setOnClickListener(this);
btnmobileadd.setOnClickListener(this);
btnmobileremove.setOnClickListener(this);
btndone.setOnClickListener(this);
}
#Override
public void onClick(View v) {
jump=new Intent(Hidden.this,Framelayout.class);
if(v.getId()==R.id.buttonnameadd)
{
String strname=etname.getText().toString();
Log.d("Log",strname);
jump.putExtra("Name",strname);
}else if(v.getId()==R.id.buttonnameremove)
{
btnnameremove.setEnabled(false);
llname.removeView(findViewById(R.id.editTextname));
}else if(v.getId()==R.id.buttonmobileadd)
{
String strmobile=etmobile.getText().toString();
Log.d("Log",strmobile);
jump.putExtra("Mobile",strmobile);
Log.d("LOG",jump.putExtra("Mobile",strmobile).toString());
}else if(v.getId()==R.id.buttonmobileremove)
{
llmobile.removeView(findViewById(R.id.editTextmobile));
}else if(v.getId()==R.id.buttondone)
{
Log.d("LOG","1");
startActivity(jump);
}
}
}
FrameLayout.java
public class Framelayout extends Activity implements OnClickListener {
FrameLayout frameLayout;
Button b2,b3;
//private ProgressDialog pDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_framelayout);
frameLayout = (FrameLayout)findViewById(R.id.f1);
b2=(Button)findViewById(R.id.button2);
b3=(Button)findViewById(R.id.buttonload);
b2.setOnClickListener(this);
b3.setOnClickListener(this);
}
public void onClick(View v) {
if(v.getId()==R.id.button2){
Intent i=new Intent(Framelayout.this,Hidden.class);
startActivity(i);
}else if(v.getId()==R.id.buttonload){
Log.d("Log",getIntent().getStringExtra("Name"));
editframelayout();
}
}
private void editframelayout() {
String name=getIntent().getExtras().getString("Name");
String mobile=getIntent().getExtras().getString("Mobile");
TextView tvname=new TextView(this);
tvname.setText(name);
tvname.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tvname.setGravity(Gravity.CENTER);
TextView tvmobile=new TextView(this);
tvmobile.setText(mobile);
tvmobile.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tvmobile.setGravity(Gravity.CENTER);
frameLayout.addView(tvname);
frameLayout.addView(tvmobile);
}
}
You must use one of putExtra() overloaded methods of the intent instance you created to add your data.
Here is a sample:
Intent intent = new Intent(this, SignoutActivity.class); // # this parameter is the context of the caller
intent.putExtra("PARAM_TEXTBOX_TEXT", textboxText);
startActivity(intent);
Edit for the code you added, your design is very poor and doesn't accomplish what is intended.
Every time you click a Button a new instance of Intent is created. you are calling startActivity() only in single case:
else if(v.getId()==R.id.buttondone)
{
Log.d("LOG","1");
startActivity(jump);
}
Now you assume that the parameters added in previous button clicks are still there, but they aren't. When you click buttondone you create a new instance of Intent with no extras at all.
You can work this around as follows:
...
else if(v.getId()==R.id.buttondone)
{
String strname = etname.getText().toString();
if (strname != null && !strname.equals(""))
{
jump.putExtra("Name",strname);
}
String strmobile = etmobile.getText().toString();
if (strmobile != null && !strmobile.equals(""))
{
jump.putExtra("Mobile",strmobile);
}
startActivity(jump);
}
It still isn't well structured, but might do the trick for you
Use getIntent().getStringExtra("Name") instead of getIntent().getExtras().getString("Name");
getIntent().getStringExtra("Name")

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