收件人未注册

时间:2014-02-26 19:38:34

标签: android broadcastreceiver illegalargumentexception

我有一个带有异步任务的程序和一个广播接收器来发送结果代码,这样Asynctask就会知道应用程序正在运行。但它崩溃了,说接收器在主要活动中没有被注册。我在主要活动中注册了一个接收器,另一个接收器在AsyncTask Activity中。所以这里是代码和日志猫。

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mFragmentManager = getFragmentManager();
    addFriendsFragment();

    // The feed is fresh if it was downloaded less than 2 minutes ago
    mIsFresh = (System.currentTimeMillis() - getFileStreamPath(
            TWEET_FILENAME).lastModified()) < TWO_MIN;

    ensureData();

}

// Add Friends Fragment to Activity
private void addFriendsFragment() {

    mFriendsFragment = new FriendsFragment();
    mFriendsFragment.setArguments(getIntent().getExtras());

    FragmentTransaction transaction = mFragmentManager.beginTransaction();
    transaction.add(R.id.fragment_container, mFriendsFragment);

    transaction.commit();
}

// If stored Tweets are not fresh, reload them from network
// Otherwise, load them from file
private void ensureData() {

    log("In ensureData(), mIsFresh:" + mIsFresh);

    if (!mIsFresh) {

        // TODO:
        // Show a Toast Notification to inform user that 
        // the app is "Downloading Tweets from Network"
        log ("Issuing Toast Message");
          Toast toast = Toast.makeText(getApplicationContext(), 
                  "Downloading Tweets from Network",Toast.LENGTH_LONG);
          toast.show();

        // TODO:
        // Start new AsyncTask to download Tweets from network
          new DownloaderTask(MainActivity.this).execute(MainActivity.URL_LGAGA, MainActivity.URL_RBLACK, MainActivity.URL_TSWIFT);


        // Set up a BroadcastReceiver to receive an Intent when download
        // finishes. 
        mRefreshReceiver = new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {

                log("BroadcastIntent received in MainActivity");

                // TODO:                
                // Check to make sure this is an ordered broadcast
                // Let sender know that the Intent was received
                // by setting result code to RESULT_OK
                sendOrderedBroadcast(new Intent(), null, null, null, RESULT_OK, null, null );

            }
        };

    } else {

        loadTweetsFromFile();
        parseJSON();
        updateFeed();

    }
}

// Called when new Tweets have been downloaded 
public void setRefreshed(String[] feeds) {

    mRawFeeds[0] = feeds[0];
    mRawFeeds[1] = feeds[1];
    mRawFeeds[2] = feeds[2];

    parseJSON();
    updateFeed();
    mIsFresh = true;

};

// Called when a Friend is clicked on
@Override
public void onItemSelected(int position) {

    mFeedSelected = position;
    mFeedFragment = addFeedFragment();

    if (mIsFresh) {
        updateFeed();
    }
}

// Calls FeedFragement.update, passing in the 
// the tweets for the currently selected friend

void updateFeed() {

    if (null != mFeedFragment)

        mFeedFragment.update(mProcessedFeeds[mFeedSelected]);

}

// Add FeedFragment to Activity
private FeedFragment addFeedFragment() {
    FeedFragment feedFragment;
    feedFragment = new FeedFragment();

    FragmentTransaction transaction = mFragmentManager.beginTransaction();

    transaction.replace(R.id.fragment_container, feedFragment);
    transaction.addToBackStack(null);

    transaction.commit();
    mFragmentManager.executePendingTransactions();
    return feedFragment;

}

// Register the BroadcastReceiver
@Override
protected void onResume() {
    super.onResume();

    // TODO:
    // Register the BroadcastReceiver to receive a 
    // DATA_REFRESHED_ACTION broadcast

    IntentFilter intentFilter = new IntentFilter(DATA_REFRESHED_ACTION);
    registerReceiver(mRefreshReceiver, intentFilter);


}

@Override
protected void onPause() {

    // TODO:
    // Unregister the BroadcastReceiver
    unregisterReceiver(mRefreshReceiver);



    super.onPause();

}

logcat的:

02-26 01:39:58.466: E/AndroidRuntime(943): FATAL EXCEPTION: main
02-26 01:39:58.466: E/AndroidRuntime(943): java.lang.RuntimeException: Unable to pause activity {course.labs.notificationslab/course.labs.notificationslab.MainActivity}: java.lang.IllegalArgumentException: Receiver not registered: null
02-26 01:39:58.466: E/AndroidRuntime(943):  at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3064)
02-26 01:39:58.466: E/AndroidRuntime(943):  at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3019)
02-26 01:39:58.466: E/AndroidRuntime(943):  at android.app.ActivityThread.handlePauseActivity(ActivityThread.java:2997)
02-26 01:39:58.466: E/AndroidRuntime(943):  at android.app.ActivityThread.access$800(ActivityThread.java:141)
02-26 01:39:58.466: E/AndroidRuntime(943):  at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1273)
02-26 01:39:58.466: E/AndroidRuntime(943):  at android.os.Handler.dispatchMessage(Handler.java:99)
02-26 01:39:58.466: E/AndroidRuntime(943):  at android.os.Looper.loop(Looper.java:137)
02-26 01:39:58.466: E/AndroidRuntime(943):  at android.app.ActivityThread.main(ActivityThread.java:5103)
02-26 01:39:58.466: E/AndroidRuntime(943):  at java.lang.reflect.Method.invokeNative(Native Method)
02-26 01:39:58.466: E/AndroidRuntime(943):  at java.lang.reflect.Method.invoke(Method.java:525)
02-26 01:39:58.466: E/AndroidRuntime(943):  at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
02-26 01:39:58.466: E/AndroidRuntime(943):  at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
02-26 01:39:58.466: E/AndroidRuntime(943):  at dalvik.system.NativeStart.main(Native Method)
02-26 01:39:58.466: E/AndroidRuntime(943): Caused by: java.lang.IllegalArgumentException: Receiver not registered: null
02-26 01:39:58.466: E/AndroidRuntime(943):  at android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:662)
02-26 01:39:58.466: E/AndroidRuntime(943):  at android.app.ContextImpl.unregisterReceiver(ContextImpl.java:1372)
02-26 01:39:58.466: E/AndroidRuntime(943):  at android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:468)
02-26 01:39:58.466: E/AndroidRuntime(943):  at course.labs.notificationslab.MainActivity.onPause(MainActivity.java:195)
02-26 01:39:58.466: E/AndroidRuntime(943):  at android.app.Activity.performPause(Activity.java:5235)
02-26 01:39:58.466: E/AndroidRuntime(943):  at android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1233)
02-26 01:39:58.466: E/AndroidRuntime(943):  at android.app.ActivityThread.performPauseActivity(ActivityThread.java:3050)
02-26 01:39:58.466: E/AndroidRuntime(943):  ... 12 more

这是AsyncTask的代码,但LogCat表示错误是主要的。

mApplicationContext.sendOrderedBroadcast(
            new Intent(MainActivity.DATA_REFRESHED_ACTION), 
            null,
            new BroadcastReceiver() {

                final String failMsg = "Download has failed. Please retry Later.";
                final String successMsg = "Download completed successfully.";

                @Override
                public void onReceive(Context context, Intent intent) {

                    log("Entered result receiver's onReceive() method");

                    // TODO: Check whether the result code is RESULT_OK

                    if (getResultCode() == Activity.RESULT_OK) {

                        // TODO:  If so, create a PendingIntent using the
                        // restartMainActivityIntent and set its flags
                        // to FLAG_UPDATE_CURRENT

                        final PendingIntent pendingIntent = PendingIntent.getActivity(mApplicationContext, 
                                0, restartMainActivtyIntent, PendingIntent.FLAG_UPDATE_CURRENT);



                        // Uses R.layout.custom_notification for the
                        // layout of the notification View. The xml 
                        // file is in res/layout/custom_notification.xml

                        RemoteViews mContentView = new RemoteViews(
                                mApplicationContext.getPackageName(),
                                R.layout.custom_notification);

                        // TODO: Set the notification View's text to
                        // reflect whether or the download completed
                        // successfully

                         if (success){                          
                        mContentView.setTextViewText(MY_NOTIFICATION_ID, successMsg);
                         }else{
                             mContentView.setTextViewText(MY_NOTIFICATION_ID, failMsg);
                         }

                        // TODO: Use the Notification.Builder class to
                        // create the Notification. You will have to set
                        // several pieces of information. You can use
                        // android.R.drawable.stat_sys_warning
                        // for the small icon. You should also setAutoCancel(true). 



                        // TODO: Send the notification

                        Notification notification = new Notification.Builder(mApplicationContext)
                        .setContentIntent(pendingIntent)
                        .setSmallIcon(android.R.drawable.stat_sys_warning)
                        .setAutoCancel(true)
                        .build();               

                        NotificationManager notificationManager =
                                (NotificationManager)mApplicationContext.getSystemService(Context.NOTIFICATION_SERVICE);
                        notificationManager.notify(MY_NOTIFICATION_ID, notification);

                        log("Notification Area Notification sent");
                    }
                }
            }, 
            null, 
            0, 
            null, 
            null);
}

2 个答案:

答案 0 :(得分:2)

尝试如下......

    mRefreshReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {

            log("BroadcastIntent received in MainActivity");

        }
    }

onResume() ...

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

    IntentFilter filter = new IntentFilter(DATA_REFRESHED_ACTION);    
    registerReceiver(mRefreshReceiver, filter);

}

AsyncTask ....

    Intent intent = new Intent(DATA_REFRESHED_ACTION);
    sendOrderedBroadcast(intent, null, new BroadcastReceiver() {

        @SuppressLint("NewApi")
        @Override
        public void onReceive(Context context, Intent intent) {

            log("BroadcastIntent received in MainActivity");

        }
    }, null, Activity.RESULT_OK, null, null);
}

您可以按照以下链接...

Android sendOrderedBroadcast Example

答案 1 :(得分:0)

因为您的广播接收器仅在(!mIsFresh)时创建 因此,在某些情况下,由于mIsFresh,您的广播接收器不是实例 因此,onResume注册广播接收器的空值 当onPause尝试取消注册时,会发生错误。