Enable and Disable Airplane Mode successively Android - 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.

Related

How to convert a Fragment to a Activity Android?

I have a working app using threads in fragments, the thing is I need to change the layout. It's not gonna be a Fragment anymore but a standard Activity.
My big problem is that I don't know exactly where to place what's in "onViewCreated" and "onCreateView" so it's crashing when I call "connect to device" which's placed on "onCreateView". Probably because it's too early or something.
#Nullable
#Override
public View onCreateView(final LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState){
View view;
view = inflater.inflate(R.layout.fragment_home_2, container, false);
//Linking layout views
connectToDevice = view.findViewById(R.id.connect_to_device);
startRecording = view.findViewById(R.id.start_recording);
stopRecording = view.findViewById(R.id.stop_recording);
connectedToDevice = view.findViewById(R.id.connected_to_device);
mAdapter = new DeviceListAdapter(container.getContext(), activeDevices);
imgEkoDevice = view.findViewById(R.id.img_ekodevice);
//Enable bluetooth and start scanning thread
BluetoothAdapter btAdapter = BluetoothAdapter.getDefaultAdapter();
if (btAdapter != null && !btAdapter.isEnabled()) {
btAdapter.enable();
}
//Layout setup
connectedToDevice.setText(getResources().getString(R.string.welcome_to_scopefy));
//Thread setup to search for device
scanningThread = new Thread(){
#Override
public void run(){
Log.i(AppConstants.TAG, "scanning...");
LibCore.getInstance(ConnectDeviceActivity.this).startScanningForDevices(new EkoDeviceScan() {
#Override
public void foundDevice(BLEDevice bleDevice) {
//Log.i(AppPreferences.log, "foundDevice: " + bleDevice.toString());
if(activeDevices.isEmpty()){
//Adding first device to list
activeDevices.add(bleDevice);
}
else{
int i = 0;
newDevice = true;
//Checks if its already on the list
while(i < activeDevices.size() && newDevice){
if(activeDevices.get(i).getAddress().equals(bleDevice.getAddress())){
newDevice = false;
}
i++;
}
if(newDevice){
activeDevices.add(bleDevice);
}
}
//Show list and dismiss search dialog
if(connect){
showDeviceListDialog();
if(emptyListDialog != null){
emptyListDialog.dismiss();
}
connect = false;
}
}
});
}
};
LocalBroadcastManager.getInstance(ConnectDeviceActivity.this).registerReceiver(mDeviceReceiver, new IntentFilter(Parameters.DEVICE_REFRESH_DATA));
//Starting scanning background to speed up
if(LibCore.getInstance(ConnectDeviceActivity.this).getCurrentConnectedDevice() == null){
scanningThread.start();
LibCore.getInstance(ConnectDeviceActivity.this).setFiltering(true);
connected = false;
} else {
mEkoDevice = LibCore.getInstance(ConnectDeviceActivity.this).getCurrentConnectedDevice();
connected = true;
}
//Broadcast receiver for patientId
LocalBroadcastManager.getInstance(ConnectDeviceActivity.this).registerReceiver(mPatientReceiver, new IntentFilter(Parameters.PATIENT_ID));
//Listeners and receivers for device connection
LibCore.getInstance(ConnectDeviceActivity.this).setBatteryListener(new EkoDeviceBatteryLevel() {
#Override
public void deviceUpdatedBatteryLevel(float v) {
Log.i("HUEBR123", "updateou bat");
LocalBroadcastManager.getInstance(ConnectDeviceActivity.this).sendBroadcast(new Intent(Parameters.DEVICE_REFRESH_DATA).putExtra(Parameters.DEVICE_UPDATED_BATTERY_LEVEL, v));
}
});
LibCore.getInstance(ConnectDeviceActivity.this).setVolumeListener(new EkoDeviceVolume() {
#Override
public void deviceUpdatedVolumeLevel(int i) {
Log.i("HUEBR123", "updateou vol");
LocalBroadcastManager.getInstance(ConnectDeviceActivity.this).sendBroadcast(new Intent(Parameters.DEVICE_REFRESH_DATA).putExtra(Parameters.DEVICE_UPDATED_VOLUME_LEVEL, i));
}
});
//Settings
userSettingsDAO = new UserSettingsDAO(ConnectDeviceActivity.this);
settings = userSettingsDAO.getUserSettings();
//Button's listeners
connectToDevice.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
connect = true;
scanningThread.run();
showDeviceListEmptyDialog();
}
});
startRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Log.i(AppConstants.TAG, "starting recording...");
stopped = false;
startRecording();
//startPlayRecordThroughEko();
startRecording.setVisibility(View.GONE);
stopRecording.setVisibility(View.VISIBLE);
recording = true;
settings = userSettingsDAO.getUserSettings();
settings.getRecordingLength();
Timer timer = new Timer();
TimerTask task = new StopRecordingTask();
timer.schedule(task, settings.getRecordingLength() * 1000);
Log.i(AppConstants.TAG, "#timer starting for " + settings.getRecordingLength() + " seconds");
}
});
stopRecording.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
mEkoOutputAudioByteListener = null;
mAudioFileOutputStream.close();
writeWAVHeader(mCachedAudioRecordingFile, 4000);
//writeWAVHeader(mCachedECGRecordingFile, 500);
stopOutputtingAudioDataPoints();
} catch (Exception e) {
e.printStackTrace();
}
startRecording.setVisibility(View.VISIBLE);
stopRecording.setVisibility(View.GONE);
recording = false;
short[] output;
output = new short[outData.size() * 32];
for(int i=0; i<outData.size(); i++){
for(int j=0; j<32; j++){
output[i] = outData.get(i)[j];
}
}
Intent intent = new Intent(ConnectDeviceActivity.this, AuscultationActivity.class);
intent.putExtra("output", output);
intent.putExtra("patient-id", patientId);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Log.i(AppConstants.TAG, "OUPUTLEN: " + output.length);
if(!stopped) {
stopped = true;
startActivity(intent);
}
}
});
return view;
}
//This overridden method makes DynamicWaveformViews avoid crashing
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
dynamicWaveformView = (DynamicWaveformView) view.findViewById(R.id.dynamic_waveform_view);
dynamicWaveformView.init();
mAudioThread = new HandlerThread("AudioThread");
mAudioThread.start();
mAudioHandler = new Handler(mAudioThread.getLooper());
//updateView again for consistency (mDeviceBroadcast may be too much but still works)
updateView(connected);
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mEkoDevice = new EkoDevice("DUMMY_DEVICE", "0");
buyNow = findViewById(R.id.buyNow);
back = findViewById(R.id.back_icon);
back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(getApplicationContext(), MainActivity.class);
startActivity(intent);
}
});
buyNow.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse("http://www.google.com"));
startActivity(browserIntent);
}
});
changeAudioAmplitudeScaleFactor(8);
mPlayerManager = new PlayerManager();
mPlayerManager.onCreate();
LibCore.getInstance(ConnectDeviceActivity.this).setFiltering(true);
}
trying to place at the bottom of "onCreate" it gives me the following error:
PopupWindow $BadTokenException: Unable to add window — token null is not valid
Regarding you error
PopupWindow $BadTokenException: Unable to add window — token null is
not valid
Maybe add that code in the Activity onResume() lifecykle method instead of onCreate if it need to run more then one time
Move the scanningThread, BluetoothAdapter and LocalBroadcastManager LibCore everything to the 'onCreate()' . The 'onCreateView()' should only have the view = inflater.inflate(R.layout.fragment_home_2, container, false);
The onCreate() only initiate stuff hook up local variables views and set clicklisteners. Like all the one-time-stuff. Going from Fragment to Activity is basically almost the same since they have the same lifecykle methods
Check this nice explanation about the-android-lifecycle-cheat-sheet

why is recreate is looping infinity?

I have a simple program that changes the background of activity A from activity B.
When you change the background you need to refresh activity A in order for the background to change, after looking around stackoverflow the easiest way was just to call recreate().
I'm not sure if im calling it wrong or in the wrong area but what ends up happening is it will loop the following error when the app is run and eventually crash-
02-01 13:23:53.358 17302-17302/com.package.www.randomapp E/ViewRootImpl: sendUserActionEvent() mView == null
Here's the code for activity A
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_mainmenu);
backgroundChanger();
recreate();
}
public void backgroundChanger(){
SharedPreferences sharedGradients = getSharedPreferences("gradientInfo", Context.MODE_PRIVATE);
int backgroundGrad = sharedGradients.getInt("backgroundGradient", 0);
if (backgroundGrad == 0){
MMBackground.setBackgroundResource(R.drawable.blackgreengradiant);
}
if (backgroundGrad == 1){
MMBackground.setBackgroundResource(R.drawable.blueblackgradiant);
}
if (backgroundGrad == 2){
MMBackground.setBackgroundResource(R.drawable.goldblackgradiant);
}
and for Activity B
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_options_menu);
variableHandler();
}
public void variableHandler() {
MainMenuBackgroundBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(final View v) {
final SharedPreferences[] sharedGradients = {getSharedPreferences("gradientInfo", Context.MODE_PRIVATE)};
final SharedPreferences.Editor[] editor1 = {sharedGradients[0].edit()};
final SharedPreferences[] sharedBoolean = {getSharedPreferences("binaryPoint", Context.MODE_PRIVATE)};
final SharedPreferences.Editor[] editorBinary = {sharedBoolean[0].edit()};
final PopupMenu popup = new PopupMenu(getApplicationContext(), v);
popup.inflate(R.menu.menu_background_gradiant_setter);
popup.show();
popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
#Override
public boolean onMenuItemClick(MenuItem item) {
switch (item.getItemId()) {
case R.id.item1:
Toast.makeText(OptionsMenu.this, "Blue and black gradient", Toast.LENGTH_SHORT).show();
editorBinary[0] = sharedBoolean[0].edit();
editorBinary[0].putInt("binaryPoint", 1);
editor1[0] = sharedGradients[0].edit();
editor1[0].putInt("backgroundGradient", 1);
editor1[0].apply();
return true;
case R.id.item2:
Toast.makeText(OptionsMenu.this, "Gold and black gradient", Toast.LENGTH_SHORT).show();
editorBinary[0] = sharedBoolean[0].edit();
editorBinary[0].putInt("binaryPoint", 1);
editor1[0] = sharedGradients[0].edit();
editor1[0].putInt("backgroundGradient", 2);
editor1[0].apply();
return true;
}
}
The problem is that you are calling recreate() in the onCreate() method of the Activity without any condition which will create an infinite loop. Keep a variable to track whether the activity is recreated or not.
private static boolean alreadyRecreated = false;
//You can add some extra conditions here if you want.
if(!alreadyRecreated){
recreate();
alreadyRecreated = true;
}
recreate(); will cause your activity to be recreated.
i.e, onCreate gets called. Since, you added recreate(); in onCreate method, it is running into infinite loop and crashing.

Android Calculator Backspace button

Any idea how to illustrate backspace funtion in this code? I try to make some changes but it can't work the backspace function. So, i would like to help me, with the backspace button.
enter code here
public class MainActivity extends AppCompatActivity implements OnClickListener {
private TextView mCalculatorDisplay;
private Boolean userIsInTheMiddleOfTypingANumber = false;
private CalculatorBrain mCalculatorBrain;
private static final String DIGITS = "0123456789.";
DecimalFormat df = new DecimalFormat("############");
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
// hide the window title.
requestWindowFeature(Window.FEATURE_NO_TITLE);
// hide the status bar and other OS-level chrome
getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCalculatorBrain = new CalculatorBrain();
mCalculatorDisplay = (TextView) findViewById(R.id.textView1);
df.setMinimumFractionDigits(0);
df.setMinimumIntegerDigits(1);
df.setMaximumIntegerDigits(8);
findViewById(R.id.button0).setOnClickListener(this);
findViewById(R.id.button1).setOnClickListener(this);
findViewById(R.id.button2).setOnClickListener(this);
findViewById(R.id.button3).setOnClickListener(this);
findViewById(R.id.button4).setOnClickListener(this);
findViewById(R.id.button5).setOnClickListener(this);
findViewById(R.id.button6).setOnClickListener(this);
findViewById(R.id.button7).setOnClickListener(this);
findViewById(R.id.button8).setOnClickListener(this);
findViewById(R.id.button9).setOnClickListener(this);
findViewById(R.id.buttonBackspace).setOnClickListener(this);
findViewById(R.id.buttonAdd).setOnClickListener(this);
findViewById(R.id.buttonSubtract).setOnClickListener(this);
findViewById(R.id.buttonMultiply).setOnClickListener(this);
findViewById(R.id.buttonDivide).setOnClickListener(this);
findViewById(R.id.buttonToggleSign).setOnClickListener(this);
findViewById(R.id.buttonDecimalPoint).setOnClickListener(this);
findViewById(R.id.buttonEquals).setOnClickListener(this);
findViewById(R.id.buttonClear).setOnClickListener(this);
// The following buttons only exist in layout-land (Landscape mode) and require extra attention.
// The messier option is to place the buttons in the regular layout too and set android:visibility="invisible".
if (findViewById(R.id.buttonSquareRoot) != null) {
findViewById(R.id.buttonSquareRoot).setOnClickListener(this);
}
if (findViewById(R.id.buttonSquared) != null) {
findViewById(R.id.buttonSquared).setOnClickListener(this);
}
if (findViewById(R.id.buttonInvert) != null) {
findViewById(R.id.buttonInvert).setOnClickListener(this);
}
if (findViewById(R.id.buttonSine) != null) {
findViewById(R.id.buttonSine).setOnClickListener(this);
}
if (findViewById(R.id.buttonCosine) != null) {
findViewById(R.id.buttonCosine).setOnClickListener(this);
}
if (findViewById(R.id.buttonTangent) != null) {
findViewById(R.id.buttonTangent).setOnClickListener(this);
}
}
#Override
public void onClick (View v) {
String buttonPressed = ((Button) v).getText().toString();
if (DIGITS.contains(buttonPressed)) {
// digit was pressed
if (userIsInTheMiddleOfTypingANumber) {
if (buttonPressed.equals(".") && mCalculatorDisplay.getText().toString().contains(".")) {
// ERROR PREVENTION
// Eliminate entering multiple decimals
} else {
mCalculatorDisplay.append(buttonPressed);
}
} else {
if (buttonPressed.equals(".")) {
// ERROR PREVENTION
// This will avoid error if only the decimal is hit before an operator, by placing a leading zero
// before the decimal
mCalculatorDisplay.setText(0 + buttonPressed);
} else {
mCalculatorDisplay.setText(buttonPressed);
}
}
userIsInTheMiddleOfTypingANumber = true;
}else{
// operation was pressed
if (userIsInTheMiddleOfTypingANumber) {
mCalculatorBrain.setOperand(Double.parseDouble(mCalculatorDisplay.getText().toString()));
userIsInTheMiddleOfTypingANumber = false;
}
mCalculatorBrain.performOperation(buttonPressed);
if (new Double(mCalculatorBrain.getResult()).equals(0.0)) {
mCalculatorDisplay.setText("" + 0);
} else {
mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));
}
}
}
#Override
protected void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
// Save variables on screen orientation change
outState.putDouble("OPERAND", mCalculatorBrain.getResult());
outState.putDouble("MEMORY", mCalculatorBrain.getMemory());
}
#Override
protected void onRestoreInstanceState(Bundle savedInstanceState){
super.onRestoreInstanceState(savedInstanceState);
// Restore variables on screen orientation change
mCalculatorBrain.setOperand(savedInstanceState.getDouble("OPERAND"));
mCalculatorBrain.setMemory(savedInstanceState.getDouble("MEMORY"));
if (new Double(mCalculatorBrain.getResult()).equals(0.0)){
mCalculatorDisplay.setText("" + 0);
} else {
mCalculatorDisplay.setText(df.format(mCalculatorBrain.getResult()));
}
}
}
In your layout you can add a onClick attribute to each button, say onClick="function", and in your activity you just need to implement a method like this:
public void function(View v) {
switch(v.getId()) {
case R.id.buttonBackspace:
// handle the backspace button
break;
case R.id.xxx:
// handle the button
break;
...
}
}
And for digits, I suggest assign a tag to each digit button in the layout, and do your logic in java based on the tag, instead of the text on the button. Because the text is just a UI, it might change in the future due to other possible requirements.

Animation in Oncreate() not stopping in android

Want to Do : i want to have an Internet check on Start of An app and if it doesn't finds then on clicking Positive button it should go to setting of wifi & if User ON the wifi then on coming back to App i want the dialog box to be dismiss and Animation start else it again show how the Internet Dialog Box .
What i have done : I have placed the Internet Check Dialog in OnResume() and animation code in OnCreate .
Issue is : on start of my App, when it check Wifi connection ,But it also run all the animation code in Oncreate() in continuity instead of running it only after Internet Connection
OnCreate Code :
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
overridePendingTransition(R.anim.grow_from_middle, R.anim.shrink_to_middle);
setContentView(R.layout.activity_csplogin);
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_ADJUST_PAN);
mobileEdit = (EditText) findViewById(R.id.mobileText);
nameEdit = (EditText) findViewById(R.id.nameText);
employerEdit = (EditText) findViewById(R.id.employerText);
noEmployerCheckbox = (CheckBox) findViewById(R.id.noEmployercheckboxid);
employerSpinner = (Spinner) findViewById(R.id.employer_spinner_id);
noEmployerLayout = (LinearLayout) findViewById(R.id.linearlayoutCheckbox);
init();
if (myPrefs.getOrgValidated() == false) {
new OrganisationValidationTask(CSPLoginActivity.this).execute();
}
isdeviceValidated = myPrefs.getIsDeviceValidated();
isLoggedIn = myPrefs.getIsLogIn();
if (isdeviceValidated) {
startLoginActivity();
}
final RelativeLayout LoginBox = (RelativeLayout) findViewById(R.id.LoginBox);
LoginBox.setVisibility(View.GONE);
Animation animTranslate = AnimationUtils.loadAnimation(CSPLoginActivity.this, R.anim.translate);
animTranslate.setAnimationListener(new AnimationListener() {
#Override
public void onAnimationStart(Animation arg0) {
}
#Override
public void onAnimationRepeat(Animation arg0) {
}
#Override
public void onAnimationEnd(Animation arg0) {
LoginBox.setVisibility(View.VISIBLE);
Animation animFade = AnimationUtils.loadAnimation(CSPLoginActivity.this, R.anim.fade);
LoginBox.startAnimation(animFade);
showSingleChoice();
}
});
ImageView imgLogo = (ImageView) findViewById(R.id.imageView1);
imgLogo.startAnimation(animTranslate);
isdeviceValidated = myPrefs.getIsDeviceValidated();
isLoggedIn = myPrefs.getIsLogIn();
if (!isLoggedIn) {
// display login screen
if (Utils.isNetworkConnected(this)) {
if (isdeviceValidated) {
// to display user details
// displayUserDetails();
if (!isMyServiceRunning()) {
Utils.startLocationPollerAndWakeupService(this);
}
}
}
} else if (isLoggedIn && isdeviceValidated) {
// skip login screen
if (!isMyServiceRunning()) {
Utils.startLocationPollerAndWakeupService(this);
}
startLoginActivity();
}
}
OnResume
#Override
protected void onResume() {
super.onResume();
if(Utils.isNetworkConnected(this)) {
}else{
showWifiAlert();
}
}
Checking Internet Connection Dialog Box:
private void showWifiAlert(){
new MaterialDialog.Builder(CSPLoginActivity.this)
.content("Unable to validate device as Internet not available")
.title("Alert !")
.positiveText("OK")
.negativeText("Cancel")
.callback(new MaterialDialog.ButtonCallback() {
#Override
public void onNegative(MaterialDialog dialog) {
finish();
}
#Override
public void onPositive(MaterialDialog dialog) {
dialog.dismiss();
startActivity(new Intent(android.provider.Settings.ACTION_WIFI_SETTINGS));
}
})
.cancelable(false)
.show();
}
Please Help , How to achieve what i want to do .
try replacing the onResume method code as following:
#Override
protected void onResume() {
super.onResume();
if(Utils.isNetworkConnected(this)) {
imgLogo.startAnimation(animTranslate);
}else{
showWifiAlert();
}
}
Let me know if this works for you.

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