2014-10-21 5 views
0

Я написал код to ON/OFF AirPlane/Flight mode программно, и до сих пор я использую two другого buttons контролировать, что один в ON режим самолета и второй в OFF режим полета, используя ниже код :Выключить Самолет/режим полета автоматически, если ON

@SuppressWarnings("deprecation") 
    public void airPlanemodeON(View v) { 
     boolean isEnabled = Settings.System.getInt(this.getContentResolver(), 
       Settings.System.AIRPLANE_MODE_ON, 0) == 1; 
     if (isEnabled == false) { // means this is the request to turn OFF AIRPLANE mode 
      modifyAirplanemode(true); // ON 
      Toast.makeText(getApplicationContext(), "Airplane Mode ON", 
        Toast.LENGTH_LONG).show(); 
     } 
    } 

    @SuppressWarnings("deprecation") 
    public void airPlanemodeOFF(View v) { 
     boolean isEnabled = Settings.System.getInt(this.getContentResolver(), 
       Settings.System.AIRPLANE_MODE_ON, 0) == 1; 
     if (isEnabled == true) // means this is the request to turn ON AIRPLANE mode 
     { 
      modifyAirplanemode(false); // OFF 
      Toast.makeText(getApplicationContext(), "Airplane Mode OFF", 
        Toast.LENGTH_LONG).show(); 
     } 
    } 

    @SuppressWarnings("deprecation") 
    public void modifyAirplanemode(boolean mode) { 
     Settings.System.putInt(getContentResolver(), 
       Settings.System.AIRPLANE_MODE_ON, mode ? 1 : 0);// Turning ON/OFF Airplane mode. 

     Intent intent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);// creating intent and Specifying action for AIRPLANE mode. 
     intent.putExtra("state", !mode);// indicate the "state" of airplane mode is changed to ON/OFF 
     sendBroadcast(intent);// Broadcasting and Intent 

    } 

Но теперь я хочу знать status из режимасамолета в каждом 2 seconds для этого я написал таймер кода, и если режим полета включен я хочуон автоматически:

@Override 
    public void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     startTimer(); 
    } 

@Override 
    protected void onResume() { 
     super.onResume(); 

     //onResume we start our timer so it can start when the app comes from the background 
     startTimer(); 
    } 

    public void startTimer() { 
     //set a new Timer 
     timer = new Timer(); 

     //initialize the TimerTask's job 
     initializeTimerTask(); 

     //schedule the timer, after the first 1000ms the TimerTask will run every 2000ms 
     timer.schedule(timerTask, 1000, 2000); // 
    } 

    public void stoptimertask(View v) { 
     //stop the timer, if it's not already null 
     if (timer != null) { 
      timer.cancel(); 
      timer = null; 
     } 
    } 

    public void initializeTimerTask() { 

     timerTask = new TimerTask() { 
      public void run() { 

       //use a handler to run a toast that shows the current timestamp 
       handler.post(new Runnable() { 
        public void run() { 

        } 
       }); 
      } 
     }; 
    } 

    /** Called when another activity is taking focus. */ 
    @Override 
    protected void onPause() { 
     super.onPause(); 
      //stop the timer, if it's not already null 
      if (timer != null) { 
       timer.cancel(); 
       timer = null; 
      } 
    } 

    /** Called when the activity is no longer visible. */ 
    @Override 
    protected void onStop() { 
     super.onStop(); 

    } 

    /** Called just before the activity is destroyed. */ 
    @Override 
    public void onDestroy() { 
     super.onDestroy(); 

    } 

Так что я должен сделать, чтобы включить off самолетный режим without нажав на button?

+0

У вас есть ответ? – Amy

+0

возьмите логическую переменную, которая будет действительной, когда включен режим самолета и отключите режим полета самолета при его отсутствии. (Получите разницу в двух частях предложения), а затем в функции, когда переменная истинна, делает ее ложной. (Так что режим самолета выключен) – therealprashant

ответ

2

Просто позвоните вашей функции airPlanemodeOFF в методе выполнения вашего TimerTask.

Вам не нужно предоставлять ему представление. Метод не использует его, вы можете передать null в качестве параметра. Я предполагаю, что вы связали кнопку с функцией xml, представление является параметром, потому что вы можете связать одну и ту же функцию с несколькими кнопками и проверить, какой из них называется.

+0

спасибо +1 за самый простой способ – Sophie

1

Попробуйте эту функцию она возвращает логическое значение, является ли режим полета включен или выключен

private static boolean isAirplaneModeOn(Context context) { 

    return Settings.System.getInt(context.getContentResolver(), 
      Settings.System.AIRPLANE_MODE_ON, 0) != 0; 

} 
0

Вам не нужно иметь TimerTask для проверки состояния каждые 2 секунды, вы можете добавить широковещательный приемник и прослушать действие «android.intent.action.AIRPLANE_MODE».

<receiver android:name="com.appname.AirplaneModeChangeReceiver"> 
<intent-filter> 
    <action android:name="android.intent.action.AIRPLANE_MODE"/> 
</intent-filter> 
</receiver> 


public class AirplaneModeChangeReceiver extends BroadcastReceiver { 
     public void onReceive(Context context, Intent intent) { 

     //check status, and turn it on/off here 
    }  
} 
Смежные вопросы