-1

所以我有一個廣播接收器,工作得很好。問題是,當它被調用時,我不能改變片段,因爲我的類擴展了BroadcastReceiver而不是Activity或Fragment。因此,我無法訪問getFragmentManager()或getSupportFragmentManager()。我不確定如何繼續並得到任何幫助。從broadcastreceiver更改片段

廣播接收器類:

package lucaclock.moticlock; 

import android.app.AlarmManager; 
import android.app.PendingIntent; 
import android.content.BroadcastReceiver; 
import android.content.Context; 
import android.content.Intent; 
import android.widget.Toast; 

public class AlarmManagerBroadcastReceiver extends BroadcastReceiver { 

public static final String numAlarmsPreferences = "numAlarmsPreferences"; 
public static final String numAlarmsKey = "numAlarmsKey"; 
public static final String alarm1Preferences = "alarm1Preferences"; 
public static final String alarm2Preferences = "alarm2Preferences"; 
public static final String alarm3Preferences = "alarm3Preferences"; 
public static final String alarm4Preferences = "alarm4Preferences"; 
public static final String alarmTimeDisplayKey = "alarmTimeDisplayKey"; 
public static final String alarmTimeRequestedKey = "alarmTimeRequestedKey"; 
public static final String alarmNameKey = "alarmNameKey"; 
public static final String alarmOccuranceKey = "alarmOccuranceKey"; 
public static final String alarmActiveKey = "alarmActiveKey"; 
public static final String alarmSoundUriKey = "alarmSoundUriKey"; 
public static final String alarmSoundTitleKey = "alarmSoundTitleKey"; 
public static final String alarmVolumeKey = "alarmVolumeKey"; 
public static final String alarmSnoozeKey = "alarmSnoozeKey"; 
public static final String alarmVisibleKey = "alarmVisibleKey"; 
public static final String alarmRunningKey = "alarmVisibleKey"; 
public boolean alarm1Active; 
public boolean alarm2Active; 
public boolean alarm3Active; 
public boolean alarm4Active; 

public void onReceive(Context context, Intent intent) { 
    WakeLocker.acquire(context); 

    MainActivity mA = new MainActivity(); 
    mA.updateFragment(HomeFragment.class, null); 

    Toast.makeText(context, "ALARM ACTIVE!!!", Toast.LENGTH_LONG).show(); 

    /*---------------THIS CODE IS RUN WHEN THE ALARM IS ACTIVE----------------------// 
    // 
    //------------------------------------------------------------------------------// 
    */ 

    //initialize preferences 
    AppSharedPreferences alarm1Prefs = AppSharedPreferences.getInstance(context, alarm1Preferences); 
    AppSharedPreferences alarm2Prefs = AppSharedPreferences.getInstance(context, alarm2Preferences); 
    AppSharedPreferences alarm3Prefs = AppSharedPreferences.getInstance(context, alarm3Preferences); 
    AppSharedPreferences alarm4Prefs = AppSharedPreferences.getInstance(context, alarm4Preferences); 

    alarm1Active = alarm1Prefs.getBoolean(alarmActiveKey, false); 
    alarm2Active = alarm2Prefs.getBoolean(alarmActiveKey, false); 
    alarm3Active = alarm3Prefs.getBoolean(alarmActiveKey, false); 
    alarm4Active = alarm4Prefs.getBoolean(alarmActiveKey, false); 



} 

public void cancelAlarm(Context context) 
{ 
    Toast.makeText(context, "Alarm canceled successfully", Toast.LENGTH_LONG).show(); 
    Intent intent = new Intent(context, AlarmManagerBroadcastReceiver.class); 
    PendingIntent sender = PendingIntent.getBroadcast(context, 0, intent, 0); 
    AlarmManager alarmManager = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE); 
    alarmManager.cancel(sender); 

    AppSharedPreferences mPref = AppSharedPreferences.getInstance(context, alarm1Preferences); 
    mPref.putBoolean(alarmRunningKey, false); 
    mPref.putBoolean(alarmActiveKey, false); 

    WakeLocker.release(); 
} 
} 

回答

0

做你想做什麼,你只需要註冊BroadcastReceiverActivityonResume()onStop()註銷。請參閱下面的示例,您可以在那裏註冊BroadcastReceiver

public class MyActivity extends Activity { 
    // ... 
    private BroadcastReceiver mReceiver; 

    // ... 

    @Override 
    public void onStart() { 
     super.onStart(); 
     IntentFilter filter = new IntentFilter(); 
     filter.addAction("..."); 
     // ... 
     mReceiver = new BroadcastReceiver() { 
      @Override 
      public void onReceive(Context pContext, Intent pIntent) { 
       String action = pIntent.getAction(); 
       // ... 
      } 
     }; 

     registerReceiver(mReceiver, filter); 
    } 

    @Override 
    public void onStop() { 
     super.onStop(); 
     if (mReceiver != null) { 
      unregisterReceiver(mReceiver); 
     } 
    } 
} 

我的更新MainActivity類別:

package lucaclock.moticlock; 

import android.app.AlarmManager; 
import android.app.Fragment; 
import android.app.FragmentManager; 
import android.app.FragmentTransaction; 
import android.app.PendingIntent;  
import android.content.Context; 
import android.content.Intent; 
import android.content.IntentFilter; 
import android.os.Bundle; 
import android.support.design.widget.FloatingActionButton; 
import android.support.v7.app.AppCompatActivity; 
import android.support.v7.widget.Toolbar; 
import android.view.Menu; 
import android.view.MenuInflater; 
import android.view.MenuItem; 
import android.view.View; 
import android.widget.Toast; 


public class MainActivity extends AppCompatActivity { 
//public static int numAlarms = 0; 

public boolean alarm1Active; //means the alarm is set and will go off when specified time is reached 
public boolean alarm1Visible = true; //means the alarm has been added and is now visible on the main screen 
public boolean alarm2Visible = true; 
public boolean alarm2Active; 
public boolean alarm3Visible = true; 
public boolean alarm3Active; 
public boolean alarm4Visible = true; 
public boolean alarm4Active; 
public AlarmManager alarmManager; 
public PendingIntent alarmIntent; 
public static final String numAlarmsPreferences = "numAlarmsPreferences"; 
public static final String numAlarmsKey = "numAlarmsKey"; 
public static final String alarm1Preferences = "alarm1Preferences"; 
public static final String alarm2Preferences = "alarm2Preferences"; 
public static final String alarm3Preferences = "alarm3Preferences"; 
public static final String alarm4Preferences = "alarm4Preferences"; 
public static final String alarmTimeDisplayKey = "alarmTimeDisplayKey"; 
public static final String alarmTimeRequestedKey = "alarmTimeRequestedKey"; 
public static final String alarmDateKey = "alarmDateKey"; 
public static final String alarmNameKey = "alarmNameKey"; 
public static final String alarmOccuranceKey = "alarmOccuranceKey"; 
public static final String alarmActiveKey = "alarmActiveKey"; 
public static final String alarmRunningKey = "alarmRunningKey"; 
public static final String alarmSoundUriKey = "alarmSoundUriKey"; 
public static final String alarmSoundTitleKey = "alarmSoundTitleKey"; 
public static final String alarmVolumeKey = "alarmVolumeKey"; 
public static final String alarmSnoozeKey = "alarmSnoozeKey"; 
public static final String alarmVisibleKey = "alarmVisibleKey"; 
private AlarmManagerBroadcastReceiver alarm; 
private BroadcastReceiver mReceiver; 
public boolean alarm1Running; 
public View view; 
public boolean devMode = true; 
public boolean fragSwitch; 
//private AHBottomNavigation bottomNavigation; 
//private ArrayList<com.aurelhubert.ahbottomnavigation.AHBottomNavigationItem> menuItemsList; 
//public boolean firstRun; 
public int currentFragment; //1 = HomeFragment 2 = AddAlarmFragment 3 = DeleteAlarmFragment 

@Override 
public void onStart() { 
    super.onStart(); 
    IntentFilter filter = new IntentFilter(); 
    filter.addAction("..."); 
    // ... 
    mReceiver = new BroadcastReceiver() { 
     @Override 
     public void onReceive(Context pContext, Intent pIntent) { 
      String action = pIntent.getAction(); 

      Toast.makeText(getApplicationContext(), "We have received the alarm!", Toast.LENGTH_LONG).show(); 
      thirdFragment tFrag = new thirdFragment(); 
      replaceFragment(tFrag); 
     } 
    }; 

    registerReceiver(mReceiver, filter); 
} 

@Override 
public void onStop() { 
    super.onStop(); 
    if (mReceiver != null) { 
     unregisterReceiver(mReceiver); 
    } 
} 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    Context context = this.getApplicationContext(); 

    Toolbar tb = (Toolbar) findViewById(R.id.my_toolbar); 
    setSupportActionBar(tb); 
    currentFragment = 1; 


    if(devMode = true) { 
     final FloatingActionButton fabClearPref = (FloatingActionButton) findViewById(R.id.fabClearPref); 
     fabClearPref.setOnClickListener(new View.OnClickListener() { 
      @Override 
      public void onClick(View v) { 
       for (int i = 0; i < 5; i++) { 
        HomeFragment hFrag = new HomeFragment(); 
        if (i == 0) { 
         AppSharedPreferences mPref = AppSharedPreferences.getInstance(getApplicationContext(), alarm1Preferences); 
         mPref.clearPref(); 
         hFrag.numAlarmsGlobal = 0; 
        } else if (i == 1) { 
         AppSharedPreferences mPref = AppSharedPreferences.getInstance(getApplicationContext(), alarm2Preferences); 
         mPref.clearPref(); 
         hFrag.numAlarmsGlobal = 0; 
        } else if (i == 2) { 
         AppSharedPreferences mPref = AppSharedPreferences.getInstance(getApplicationContext(), alarm3Preferences); 
         mPref.clearPref(); 
         hFrag.numAlarmsGlobal = 0; 
        } else if (i == 3) { 
         AppSharedPreferences mPref = AppSharedPreferences.getInstance(getApplicationContext(), alarm4Preferences); 
         mPref.clearPref(); 
         hFrag.numAlarmsGlobal = 0; 
        } else if (i == 4) { 
         AppSharedPreferences mPref = AppSharedPreferences.getInstance(getApplicationContext(), numAlarmsPreferences); 
         mPref.clearPref(); 
         hFrag.numAlarmsGlobal = 0; 
        } 
        fabClearPref.setVisibility(View.INVISIBLE); 

       } 

      } 
     }); 
     fabClearPref.setOnLongClickListener(new View.OnLongClickListener() { 
      @Override 
      public boolean onLongClick(View v) 
      { 
       fabClearPref.setVisibility(View.INVISIBLE); 

       return true; 
      } 

     }); 
    } 


    /*---------------THIS IS THE ACTUAL ALARM----------------// 
    //-----------THAT SHOWS UP WHEN THE SET TIME-------------// 
    //---------------AND THE ACTUAL TIME MATCH---------------// 
    */ 
    AppSharedPreferences alarm1Prefs = AppSharedPreferences.getInstance(this.getApplicationContext(), alarm1Preferences); 
    AppSharedPreferences alarm2Prefs = AppSharedPreferences.getInstance(this.getApplicationContext(), alarm2Preferences); 
    AppSharedPreferences alarm3Prefs = AppSharedPreferences.getInstance(this.getApplicationContext(), alarm3Preferences); 
    AppSharedPreferences alarm4Prefs = AppSharedPreferences.getInstance(this.getApplicationContext(), alarm4Preferences); 

    /* 
    alarm1Active = alarm1Prefs.getBoolean(alarmActiveKey, false); 
    alarm2Active = alarm2Prefs.getBoolean(alarmActiveKey, false); 
    alarm3Active = alarm3Prefs.getBoolean(alarmActiveKey, false); 
    alarm4Active = alarm4Prefs.getBoolean(alarmActiveKey, false); 
    */ 

    //alarm1Active = true; 

    Fragment homeFragment = new HomeFragment(); 
    replaceFragment(homeFragment); 
    //fabClearPref.setVisibility(View.INVISIBLE); 
    //initBottomBar(); 

} 

public void readPreferences(View view) 
{ 
    //dialogBuilder("VERIFICATION 0x12", "Reading Preferences!"); 

    AppSharedPreferences alarm1Pref = AppSharedPreferences.getInstance(getApplicationContext(), alarm1Preferences); 
    AppSharedPreferences alarm2Pref = AppSharedPreferences.getInstance(getApplicationContext(), alarm2Preferences); 
    AppSharedPreferences alarm3Pref = AppSharedPreferences.getInstance(getApplicationContext(), alarm3Preferences); 
    AppSharedPreferences alarm4Pref = AppSharedPreferences.getInstance(getApplicationContext(), alarm4Preferences); 

    alarm1Active = alarm1Pref.getBoolean(alarmActiveKey, false); 
    alarm1Running = alarm1Pref.getBoolean(alarmRunningKey, false); 
    //TODO: Add alarm2 booleans when alarm1 booleans confirmed working 

} 

public void replaceFragment(Fragment fragment) 
{ 
    FragmentManager fragmentManager = getFragmentManager(); 
    FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction(); 
    //fragmentTransaction.setCustomAnimations(enterTransition, exitTransition); 
    fragmentTransaction.replace(R.id.frame_container, fragment); 
    //fragmentTransaction.addToBackStack(fragment.toString()); 
    fragmentTransaction.commit(); 
} 

public void updateFragment(Class<?> clazz, Bundle args) { 
    String tag = clazz.getName(); 
    FragmentManager fragmentManager = getFragmentManager(); 
    Fragment fragment = fragmentManager.findFragmentByTag(tag); 
    if (fragment == null) { 
     fragment = Fragment.instantiate(this, tag, args); 
     fragment.setRetainInstance(true); 
    } 
    FragmentTransaction transaction = fragmentManager.beginTransaction(); 
    transaction.addToBackStack(tag); 
    transaction.replace(R.id.frame_container, fragment, tag); 
    transaction.commit(); 
} 

public void onBackPressed() 
{ 
    FragmentManager fm = getFragmentManager(); 
    DialogView dv = new DialogView(); 
    dv.show(fm, "Fragment"); 
} 

@Override 
public boolean onCreateOptionsMenu(Menu menu) { 
    // Inflate the menu items for use in the action bar 
    MenuInflater inflater = getMenuInflater(); 
    inflater.inflate(R.menu.options_menu, menu); 
    return super.onCreateOptionsMenu(menu); 
} 

@Override 
public boolean onOptionsItemSelected(MenuItem item) { 
    // Handle item selection 
    switch (item.getItemId()) { 
     case R.id.menu_home: 
      HomeFragment homeFragment = new HomeFragment(); 
      replaceFragment(homeFragment); 

      return false; 
     case R.id.menu_alarm: 
       thirdFragment alarmFragment = new thirdFragment(); 
       replaceFragment(alarmFragment); 
       currentFragment = 2; 

      return true; 
     /*case R.id.menu_deletealarm: 
       thirdFragment deleteAlarmFragment = new thirdFragment(); 
       replaceFragment(deleteAlarmFragment); 
       currentFragment = 3; 

      return true;*/ 
     case R.id.menu_settings: 
      fourthFragment settingsFragment = new fourthFragment(); 
      replaceFragment(settingsFragment); 
      return true; 
     default: 
      return super.onOptionsItemSelected(item); 
    } 
    } 
    /* 
    FloatingActionButton fabAddAlarm = (FloatingActionButton)  findViewById(R.id.fabAddAlarm); 
    fabAddAlarm.setOnClickListener(new View.OnClickListener() 
    { 
     @Override 
     public void onClick(View v) 
     { 

      setContentView(R.layout.activity_addalarm); 
     } 
    }); 
    */ 
} 
+0

謝謝!然而,我有一個問題可以調整。因爲這包括onReceive(),這是否意味着我將不得不改變我的清單指向這個活動作爲接收器? – 2JZIgnition

+0

否,因爲您只爲活動的生命週期註冊它。我認爲廣播將由Manifest註冊的接收器發送,對嗎? – Toochka

+0

我按照你的建議,用我的MainActivity類更新了我的帖子。我的BroadcastReceiver類似乎運行良好,因爲我所示的Toast在被調用時正在運行,但是我的onReceive在我的活動中似乎沒有調用。有可能我有2個onReceive方法,應該只有一個? – 2JZIgnition