2014-10-31 12 views
8

Ho inserito un widget interruttore in Attività principale, ho anche una seconda attività che estende BroadcastReceiver. Voglio ottenere lo stato booleano del widget switch in seconda attività.Come ottenere il valore di commutazione in Android?

Se scriv

Switch s = (Switch) findViewById(R.id.switch1); 

si dice findViewById non è definito per il tipo SecondActivity. Il problema è che Android non mi consente di ottenere il valore di switch in una classe che estende Broadcast Receiver.

Desidero conoscere lo stato dell'interruttore, cioè se l'interruttore è acceso o spento, ma in seconda attività. Come posso ottenerlo?

+0

Eventuali duplicati: http://stackoverflow.com/a/10577852/2777098 –

+0

@IsabelHM Ho già detto che Android doesn' t riconosce findViewById in una classe che estende il ricevitore Broadcast. Ho letto quella domanda, che è completamente diversa. –

+2

Il BroadcastReceiver non ha un'interfaccia utente (e quindi nessun interruttore), quindi ha senso che non ti permetta di trovare findById() '. –

risposta

10

La chiamata a findViewById() da un'attività può accedere solo alle viste che fanno parte del layout di tale attività. Non è possibile utilizzarlo per cercare il layout di qualsiasi altra attività.

A seconda del disegno app, è possibile utilizzare uno di questi:

1) Invia il valore del Passa a SecondActivity tramite un intento più

in attività:

Intent mIntent = new Intent(this, SecondActivity.class); 
mIntent.putExtra("switch", s.isChecked()); 
startActivity(mIntent); 

In SecondAttività:

boolean isChecked = getIntent().getBooleanExtra("switch", false); 

2) Salvare il valore di una preferenza sul cambiamento, e leggere le preferenze in SecondActivity

in attività:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); 
SharedPreferences.Editor e = settings.edit(); 
e.putBoolean("switch", s.isChecked()); 
e.commit(); 

In SecondActivity:

SharedPreferences settings = PreferenceManager.getDefaultSharedPreferences(this); 
boolean isChecked = settings.getBoolean("switch", false); 
+0

Come posso aggiungere il valore booleano alle preferenze e recuperare in SecondActivity. Puoi per favore postare il codice? –

+0

Ricevo un errore in SecondActivity. Questo è l'errore: - "Il metodo getDefaultSharedPreferences (Context) nel tipo PreferenceManager non è applicabile per gli argomenti (SecondActivity)". –

+0

Attualmente sto creando un'app che blocca le chiamate in arrivo quando l'interruttore è attivo. Ho pubblicato una domanda con il codice completo. Si prega di dare un'occhiata: - http://stackoverflow.com/questions/26673533/how-to-block-incoming-call-when-switch-widget-is-on –

1

Per accedere al valore di swi tch, è necessario effettuare le seguenti operazioni:

((Switch) findViewById(R.id.switch_id)).isChecked(); 

MA in un contesto di un BroadcastReceiver, non dovete realmente accedere a un layout, quindi non è possibile accedere allo switch. È necessario eseguire questa operazione SOLO all'interno dell'attività che aumenta il layout con lo switch.

È possibile che un BroadcastReceiver registrato a livello di programmazione in un'attività, questo è l'unico modo in cui vedo questa combinazione di concetti di lavoro.

+0

Attualmente sto creando un'app che blocca la chiamata in arrivo quando l'interruttore è attivo. Ho pubblicato una domanda con il codice completo. Si prega di dare un'occhiata: - http://stackoverflow.com/questions/26673533/how-to-block-incoming-call-when-switch-widget-is-on –

0

È possibile salvare il valore in Preferenze. Sotto classe sarà rendono facile per voi per salvare i dati e retrive da Preferenze

public class SessionManager { 

    private SharedPreferences pref; 
    private static SessionManager sessionManager; 




    public static SessionManager getInstance(Context context) { 
     if(sessionManager == null){ 
      sessionManager = new SessionManager(context); 
     } 
     return sessionManager; 
    } 


    public SessionManager(Context context) { 
     String PREF_NAME = context.getResources().getString(R.string.app_name); 
     this.pref = context.getSharedPreferences(PREF_NAME,Context.MODE_PRIVATE); 

    } 


    /** 
    * Getting value for key from shared Preferences 
    * 
    * @param key   key for which we need to get Value 
    * @param defaultValue default value to be returned if key is not exits 
    * @return It will return value of key if exist and defaultValue otherwise 
    */ 
    public String getValueFromKey(String key, String defaultValue) { 
     if (pref.containsKey(key)) { 
      return pref.getString(key, defaultValue); 
     } else { 
      return defaultValue; 
     } 
    } 


    /** 
    * Setting value for key from shared Preferences 
    * 
    * @param key key for which we need to get Value 
    * @param value value for the key 
    */ 
    public void setValueFromKey(String key, String value) { 
     pref.putString(key, value).apply(); 
    } 


    /** 
    * Setting value for key from shared Preferences 
    * 
    * @param key key for which we need to get Value 
    * @param value value for the key 
    */ 
    public void setFlagFromKey(String key, boolean value) { 
     pref.putBoolean(key, value).apply(); 
    } 


    /** 
    * To get Flag from sharedPreferences 
    * 
    * @param key key of flag to get 
    * @return flag value for key if exist. false if not key not exist. 
    */ 
    public boolean getFlagFromKey(String key) { 
     return pref.containsKey(key) && pref.getBoolean(key, false); 
    } 

} 
Problemi correlati