Programmatically Registering Child Class BroadcastReceiver onReceive(context, intent) not getting called in DialogFragment

本小妞迷上赌 提交于 2019-12-08 12:13:30

问题


Is there a specific name i should be using for a custom BroadcastReceiver for it to be registered ?

Here is my DialogFragment class:

public class ApacheLicenseDialog extends DialogFragment implements Handler.Callback{

// Message Constants
private static final int MSG_DO_WORK        = 0;
private static final int MSG_START          = 1;
private static final int MSG_DONE           = 2;
private static final int MSG_SHUTDOWN       = 3;

private static final String BACKGROUND_RECEIVER = "divshark.example.action.GENERATE";

// UI Elements
private TextView m_textApacheLicense        = null;
private Button m_btnOk                      = null;
private ProgressBar m_apacheProgress        = null;

// Background Processing Objects
private BackgroundThread m_bgThread         = null;
protected Handler m_handler                 = null;
private BackgroundReceiver m_bgReceiver     = null;
private IntentFilter m_intentFilter         = null;

// Apache String Object
private String apacheLicense                = null;

// ----------------------------------------------------------------------------
// New Instance Method invokes DialogFragment constructor

public static ApacheLicenseDialog newInstance(int counter) 
{
    // Create the Apache License Dialog
    ApacheLicenseDialog dialog = new ApacheLicenseDialog();

    Bundle data = new Bundle();
    data.putInt("Counter", counter);
    Log.d("COUNTER", "New Instance called: "+ Integer.toString(counter)+" times.");

    // Set the Arguments for the Dialog
    dialog.setArguments(data);

    // Return the Dialog
    return dialog;
}

// ---------------------------------------------------------------------------
// Class Overrides

/* (non-Javadoc)
 * @see android.support.v4.app.DialogFragment#onCreate(android.os.Bundle)
 */
@Override public void onCreate(Bundle savedInstanceState) 
{
    // Perform the Default Behavior
    super.onCreate(savedInstanceState);
    setRetainInstance(true);

    // Create a new Handler, Background thread, and Start the Thread
    m_handler = new Handler(this);
    m_bgThread = new BackgroundThread();
    m_bgThread.start();


    // Instantiate the Receiver
    m_bgReceiver = new BackgroundReceiver();

    if(m_bgReceiver != null){
        Log.d("BG_RECEIVER", "receiver instantiated");
    }

    // Starts the Message Sending 
    init();

}

/*
 * (non-Javadoc)
 * 
 * @see
 * android.support.v4.app.Fragment#onCreateView(android.view.LayoutInflater,
 * android.view.ViewGroup, android.os.Bundle)
 */
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) 
{
    // Set the Layout from XML Resource
    return inflater.inflate(R.layout.apache_dialog_fragment, null);
}

/*
 * (non-Javadoc)
 * 
 * @see
 * android.support.v4.app.DialogFragment#onActivityCreated(android.os.Bundle
 * )
 */
@Override public void onActivityCreated(Bundle savedInstanceState) 
{
    // Perform Default Behavior
    super.onActivityCreated(savedInstanceState);

    // Reference this Dialog and Set its Title
    getDialog().setTitle(getActivity().getResources().getString(R.string.text_Apache_License_Title));


    // Reference the UI Elements
    m_textApacheLicense = (TextView)    getView().findViewById(R.id.textViewApacheLicense);
    m_apacheProgress    = (ProgressBar) getView().findViewById(R.id.apacheProgress);
    m_btnOk             = (Button)      getView().findViewById(R.id.btnOkay);

    // Add a Listener to the Button
    m_btnOk.setOnClickListener(OkListener);

}   

/* (non-Javadoc)
 * @see android.support.v4.app.DialogFragment#onStart()
 */
@Override public void onResume() 
{
    // Peform the Default behavior
    super.onResume();

    m_intentFilter = new IntentFilter();
    m_intentFilter.addAction(BACKGROUND_RECEIVER);

    // Register the Custom Receiver
    getActivity().registerReceiver(m_bgReceiver, m_intentFilter);
    Log.d("Registering_Receiver", "Receiver :"+ m_bgReceiver.toString());
}

/* (non-Javadoc)
 * @see android.support.v4.app.Fragment#onPause()
 */
@Override public void onPause() 
{
    // Perform the Default behavior
    super.onPause();

    // Unregister the Receiver
    getActivity().unregisterReceiver(m_bgReceiver);
}

/* (non-Javadoc)
 * @see android.support.v4.app.DialogFragment#onDismiss(android.content.DialogInterface)
 */
@Override public void onDismiss(DialogInterface dialog) 
{
    m_bgThread.m_workerHandler.obtainMessage(MSG_SHUTDOWN).sendToTarget();

    Log.d("DISMISSING", "Dismissed called on ApacheLicenseDialog");

    try {
        m_bgThread.join();
        Log.d("JOINING_THREAD", "Attempting to join the Thread");
    } catch (InterruptedException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }finally{
        Log.d("JOINED_THREAD", "Thread successfully joined");

        m_bgThread = null;
        m_handler = null;
        apacheLicense = null;
    }

    // Perform the default behavior
    super.onDismiss(dialog);
}

// ----------------------------------------------------------
// Handler.Callback Interface

@Override public boolean handleMessage(Message msg) 
{
    switch(msg.what)
    {
    case MSG_START:
        // Set the ProgressBar View to Visible
        m_apacheProgress.setVisibility(View.VISIBLE);
        break;
    case MSG_DONE:
        updateUI(msg);
        break;
    }
    // return true
    return true;
}

// ---------------------------------------------------------------------------
// Private Class Method

private void init()
{   
    // Send the Message to this Classes Handler
    //m_bgThread.m_workerHandler.obtainMessage(MSG_DO_WORK).sendToTarget();
    Intent broadCastIntent = new Intent(BACKGROUND_RECEIVER);

    // Send the Broadcast to the Receiver & Log the newIntent Object
    getActivity().sendBroadcast(broadCastIntent);
    Log.d("Registered_Receiver", "Receiver :"+ new Intent(BACKGROUND_RECEIVER).toString());

}

private void updateUI(Message msg) 
{
    // Set the ProgressBar View to Invisible
    m_apacheProgress.setVisibility(View.INVISIBLE);
    // Update the UI
    m_textApacheLicense.setText(msg.obj.toString());
}

private void obtainApacheLicense()
{   
    // Send message that the operation is Starting
    m_bgThread.m_workerHandler.obtainMessage(MSG_START).sendToTarget();

    // Fetch the ApacheLicense
    apacheLicense = GooglePlayServicesUtil.getOpenSourceSoftwareLicenseInfo(getActivity());

    // Send Message the the operation is Done
    m_handler.obtainMessage(MSG_DONE, apacheLicense).sendToTarget();
}

// ---------------------------------------------------------------------------
// Listeners

private OnClickListener OkListener = new OnClickListener()
{
    @Override public void onClick(View v) 
    {   
        // Dismiss the Dialog
        dismiss();

    }

};

private class BackgroundReceiver extends BroadcastReceiver {

    public BackgroundReceiver(){
        Log.d("BG_RECEIVER", "Background is in constructor.");
    }

    @Override public void onReceive(Context context, Intent intent) 
    {
        // Send the Message to this Classes Handler
        Log.d("onReceive()", "executing on receive");
        Message startMessage = m_bgThread.m_workerHandler.obtainMessage(MSG_DO_WORK);
        startMessage.sendToTarget();
    }

}

// ---------------------------------------------------------------------------
// BackgroundThread Class used to Fetch the Apache License from GooglePlayServicesUtil Class

private class BackgroundThread extends Thread implements Handler.Callback{

    // Looper and Handler for the Background Thread
    private Looper      m_workerLooper;
    protected Handler   m_workerHandler;

    @Override public void run()
    {
        // Do background Processing
        Looper.prepare();
        m_workerLooper = Looper.myLooper();
        m_workerHandler = new Handler(m_workerLooper, BackgroundThread.this);
        Looper.loop();
    }

    @Override public boolean handleMessage(Message msg) 
    {
        switch(msg.what)
        {
        case MSG_DO_WORK:
            // Run the obtainApacheLicenseFunction in this Thread
            obtainApacheLicense();
            Log.d("DO_WORK","Doing Work in background");
            break;
        case MSG_SHUTDOWN:
            // Clean up the Looper by calling quit() on it
            m_workerLooper.quit();
            Log.d("BACKGROUND_THREAD","Looper is shut down");
            break;
        }
        // Return true
        return true;
    }

}
}

I am a little confused as to why this is not working. I would like to programmatically register this receiver but for some reason onReceive() is not being called, and thus my Handler's cannot communicate any messages to display content in the DialogFragment.

Please help!!

Update

I have narrowed down my Issue to realize that when i register my receiver, my IntentFilter object is null.

How can i make sure my Intent Filter is not null?

Does this have something to do with the package name and reference to the broadcast receiver since it is an inner class?

how do i fix this?


回答1:


Okay for those of you reading this, I have managed to offset the work to my BroadcastReceiver which queues up messages to a background thread and coordinates them with my DialogFragment by changing the BACKGROUND_RECEIVER String to

private static final String BACKGROUND_RECEIVER = BackgroundReceiver.class.getName();

Then instead of calling init() from my onActivityCreated(Bundle savedInstanceState) method i now call it in onResume() like this:

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

    m_intentFilter = new IntentFilter(BACKGROUND_RECEIVER);

    getActivity().getApplicationContext().registerReceiver(m_bgReceiver,m_intentFilter);

    // Important because i was calling this before onResume() meaning i had
    // not registered my BroadCastReceiver before sending a Broadcast
    init();

}


来源:https://stackoverflow.com/questions/22690509/programmatically-registering-child-class-broadcastreceiver-onreceivecontext-in

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!