从broadcastreceiver更改片段

时间:2016-11-21 20:02:36

标签: android android-fragments broadcastreceiver fragmentmanager

所以我有一个工作正常的广播接收器。问题是,当它被调用时,我不能改变片段,因为我的类扩展了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();
}
}

1 个答案:

答案 0 :(得分:0)

要做你想做的事,你只需要在BroadcastReceiver Activity注册你的onResume(),然后在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);
        }
    });
    */
}