如何在创建和加载活动后发送广播

时间:2017-03-06 05:55:39

标签: java android arraylist

我正在创建一个音乐应用。我想从主要活动发送广播。接收者也是主要活动。这个广播访问创建并显示为片段的Arraylist。每个片段都在视图寻呼机中。 view pager是主要活动。

现在的问题是我发送广播来访问arraylist和接收者接收(从主类的oncreate方法发送广播)但是仍然没有创建arraylist所以没有数据存在,所以它显示错误。 在生成arraylist并创建了片段之后,有什么方法可以发送广播吗?

public class MainActivity extends AppCompatActivity implements           SeekBar.OnSeekBarChangeListener{

private static int songEnded = 0;
View view;
Intent intent;
int a = 0, b = 0;
int x=0;
String[] path = Kaibee.getInstance().path;
ArrayList<collection> collections;
ArrayList<collection> songlist = Kaibee.getInstance().collections;
ArrayList<collection> fav = fav_collection.getInstance().fav;
TextView bsongname,starttime,endtime;
collectionAdapter collectionadapter=new favorite().mAdapter;
ImageView bsongimage;
int seekProgress;
ImageButton greenplay,favourite;
RelativeLayout songinfo, rl;
LinearLayout bottomll;
View bottomSheet;
FloatingActionButton fb;
MediaPlayer mediaPlayer;
ImageView bnext,bprev,playlist;
favlistdb mydb;
bottomsheetdb bdb;
playerservice ps;
favorite f=new favorite();
private BottomSheetBehavior mBottomSheetBehavior;
private SeekBar seekBar;
private int seekMax;
private Toolbar toolbar;
ActionBarDrawerToggle actionBarDrawerToggle;
DrawerLayout drawerLayout;

private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent serviceIntent) {
        updateUI(serviceIntent);
    }
};
private IntentFilter bfilter = new IntentFilter("songclick");
private IntentFilter filter = new IntentFilter("songc");
//   private IntentFilter pfilter = new IntentFilter("bottomsheetbutton");
@Override
protected void onRestart() {
    super.onRestart();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
    LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(bBroadcastReceiver, bfilter);
    LocalBroadcastManager.getInstance(getApplicationContext()).registerReceiver(broadcastReceiver, filter);
    ps= new playerservice();

    bdb = new bottomsheetdb(this);
 Cursor result=bdb.getdata();
    if (result != null) {
        int pos=0;
        String listname = null;
        if (result.moveToFirst() ) {

            do{
            listname =  result.getString(result.getColumnIndex(bottomsheetdb.COL_2)) ;
                pos =(result.getInt(result.getColumnIndex(String.valueOf(bottomsheetdb.COL_3))));
                System.out.println("bottomsheet data "+listname+" "+pos);
                Intent minten = new Intent("songclick");
                minten.addFlags(Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
                minten.putExtra("position",pos);
                minten.putExtra("pause","play");
                minten.putExtra("collect",listname);
                LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(minten);
                ps.setupHandler();

            }while(result.moveToNext());

        }
    }
    else{bottomSheet.setVisibility(View.GONE);}




    // Create an adapter that knows which fragment should be shown on each page
    category_adapter adapter = new category_adapter(this, getSupportFragmentManager());

    // Set the adapter onto the view pager
    viewPager.setAdapter(adapter);
    TabLayout tabLayout = (TabLayout) findViewById(R.id.tabs);

    // Connect the tab layout with the view pager. This will
    //   1. Update the tab layout when the view pager is swiped
    //   2. Update the view pager when a tab is selected
    //   3. Set the tab layout's tab names with the view pager's adapter's titles
    //      by calling onPageTitle()
    tabLayout.setupWithViewPager(viewPager);

    //setting data inside bottom sheet
    try {
        Intent serviceIntent = new Intent(this, playerservice.class);

        // --- set up seekbar intent for broadcasting new position to service ---
        intent = new Intent("seek_update");
        seekBar.setOnSeekBarChangeListener(this);
    }
    catch (Exception e) {
        e.printStackTrace();
        Toast.makeText(getApplicationContext(),
                e.getClass().getName() + " " + e.getMessage(),
                Toast.LENGTH_LONG).show();
    }

}



public BroadcastReceiver bBroadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context c, Intent i) {
        x=0;
        String ss=i.getExtras().getString("collect");
        if(ss.equals("song_list_fragment")){collections=Kaibee.getInstance().collections;}
        else if(ss.equals("album")){collections=song_album_fetch.getInstance().albumsong;}
        else if(ss.equals("artist")){collections=artist_songs_fetch.getInstance().artistsong;}
        else if(ss.equals("genres")){collections=genres_songs_fetch.getInstance().genresong;
        }
        else{collections=fav_collection.getInstance().fav;}
        a = i.getExtras().getInt("position");
        collectionadapter=new collectionAdapter(getApplicationContext(),fav);
    //    collectionadapter=f.mAdapter;
        String s = i.getExtras().getString("pause");
        String play = "play", pause = "pause";
        if (s.equals(play)) {
            greenplay.setImageResource(R.drawable.ic_play_circle_filled);
            fb.setImageResource(R.drawable.ic_play_arrow);
        } else {
            greenplay.setImageResource(R.drawable.ic_pause_circle_outline);
            fb.setImageResource(R.drawable.ic_pause);
        }

        bottomSheet.setVisibility(View.VISIBLE);

    }
};






/**
 * Dispatch onResume() to fragments.  Note that for better inter-operation
 * with older versions of the platform, at the point of this call the
 * fragments attached to the activity are <em>not</em> resumed.  This means
 * that in some cases the previous state may still be saved, not allowing
 * fragment transactions that modify the state.  To correctly interact
 * with fragments in their proper state, you should instead override
 * {@link #onResumeFragments()}.
 */
@Override
protected void onResume() {
    super.onResume();

}

@Override
protected void onDestroy() {
    super.onDestroy();
    LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(bBroadcastReceiver);
    LocalBroadcastManager.getInstance(getApplicationContext()).unregisterReceiver(broadcastReceiver);
}

}

3 个答案:

答案 0 :(得分:0)

注册广播接收器的方法:

private MyReceiver mMyReceiver;

private class mMyReceiver extends BroadcastReceiver {
    Context mContext;
    public mMyReceiver(Context context){
        mContext = context;
    }

    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(YOUR_ACTION)) {
            // get data from intent
        }
    }
}

private void registerReceiver() {
    if (mMyReceiver== null) {
        mMyReceiver= new MyReceiver(this);
    }

    IntentFilter intentFilter = new IntentFilter(YOUR_ACTION);
    registerReceiver(mMyReceiver, intentFilter);
}

在onCreate和onDestroy中:

@Override
protected void onCreate(Bundle savedInstanceState) {
    // others
    registerReceiver();
}

@Override
protected void onDestroy() {
   if(mMyReceiver != null){
        unregisterReceiver(mMyReceiver );
    }
    super.onDestroy();
}

注意:如果活动相同,请考虑其他方式

答案 1 :(得分:0)

使用以下代码来实现目标......

 registerReceiver(myReceiver, new IntentFilter("INTENT_NAME"));



 private BroadcastReceiver myReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {

    }
};

---------------- 使用发送 --------------- ------------------

Intent intent = new Intent("INTENT_NAME");
sendBroadcast(intent);

答案 2 :(得分:0)

发送广播时,对接收方的呼叫将发布在主线程工作队列的末尾。如果您注册接收器并在onCreate中发送广播,则在onCreate返回后的某个时间才会调用接收器。其他活动生命周期方法可能已经在队列中,因此他们还必须在调用接收者之前运行并返回。