接收器未注册 [英] Receiver not registered

查看:253
本文介绍了接收器未注册的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个异步任务,一个广播接收器发送一个结果code一progamm,将让AsyncTask的知道应用程序正在工作。但它崩溃,在说的接收器unreggistred的主要活动。我registred的主要活动一个接收器,另一个接收器是AsyncTask的活动。因此,这里的code和登录猫。

  @覆盖
保护无效的onCreate(包savedInstanceState){
    super.onCreate(savedInstanceState);
    的setContentView(R.layout.activity_main);

    mFragmentManager = getFragmentManager();
    addFriendsFragment();

    //进料是新鲜,如果它被下载不到2分钟前
    mIsFresh =(System.currentTimeMillis的() -  getFileStreamPath(
            TWEET_FILENAME).lastModified())≤; TWO_MIN;

    ensureData();

}

//添加好友片段活动
私人无效addFriendsFragment(){

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

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

    器transaction.commit();
}

//如果存储的推文是不新鲜,从网络重新载入
//否则,从文件加载它们
私人无效ensureData(){

    日志(以ensureData(),mIsFresh:+ mIsFresh);

    如果(!mIsFresh){

        // 去做:
        //显示Toast通知,告知用户该
        //应用程序的下载从网络推文
        日志(发行吐司消息);
          吐司面包= Toast.makeText(getApplicationContext()
                  下载从网络推文,Toast.LENGTH_LONG);
          toast.show();

        // 去做:
        //开始新的AsyncTask下载从网络推文
          新DownloaderTask(MainActivity.this).execute(MainActivity.URL_LGAGA,MainActivity.URL_RBLACK,MainActivity.URL_TSWIFT);


        //设置一个BroadcastReceiver当下载接收意向
        //完成。
        mRefreshReceiver =新的BroadcastReceiver(){
            @覆盖
            公共无效的onReceive(上下文的背景下,意图意图){

                日志(BroadcastIntent容纳在MainActivity);

                // 去做:
                //检查以确保这是一个有序广播
                //让发送者知道已收到意图
                //设置结果code到RESULT_OK
                sendOrderedBroadcast(新意图(),NULL,NULL,NULL,RESULT_OK,NULL,NULL);

            }
        };

    } 其他 {

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

    }
}

//调用新推文已被下载时,
公共无效setRefreshed(字符串[]供稿){

    mRawFeeds [0] =提要[0];
    mRawFeeds [1] =提要[1];
    mRawFeeds [2] =提要[2];

    parseJSON();
    updateFeed();
    mIsFresh = TRUE;

};

//当一个朋友被点击调用
@覆盖
公共无效onItemSelected(INT位置){

    mFeedSelected =位置;
    mFeedFragment = addFeedFragment();

    如果(mIsFresh){
        updateFeed();
    }
}

//调用FeedFragement.update,传入
//鸣叫当前选定的朋友

无效updateFeed(){

    如果(NULL!= mFeedFragment)

        mFeedFragment.update(mProcessedFeeds [mFeedSelected]);

}

//添加FeedFragment到活动
私人FeedFragment addFeedFragment(){
    FeedFragment feedFragment;
    feedFragment =新FeedFragment();

    FragmentTransaction交易= mFragmentManager.beginTransaction();

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

    器transaction.commit();
    mFragmentManager.executePendingTransactions();
    返回feedFragment;

}

//注册的BroadcastReceiver
@覆盖
保护无效onResume(){
    super.onResume();

    // 去做:
    //注册的BroadcastReceiver接收
    // DATA_REFRESHED_ACTION广播

    IntentFilter的IntentFilter的=新的IntentFilter(DATA_REFRESHED_ACTION);
    registerReceiver(mRefreshReceiver,IntentFilter的);


}

@覆盖
保护无效的onPause(){

    // 去做:
    //注销的BroadcastReceiver
    unregisterReceiver(mRefreshReceiver);



    super.onPause();

}
 

logcat的:

  1月2号至26日:39:58.466:E / AndroidRuntime(943):致命异常:主要
1月2日至26日:39:58.466:E / AndroidRuntime(943):java.lang.RuntimeException的:无法暂停活动{course.labs.notificationslab / course.labs.notificationslab.MainActivity}:java.lang.IllegalArgumentException:如果接收器不注册:空
1月2日至26日:39:58.466:E / AndroidRuntime(943):在android.app.ActivityThread.performPauseActivity(ActivityThread.java:3064)
1月2日至26日:39:58.466:E / AndroidRuntime(943):在android.app.ActivityThread.performPauseActivity(ActivityThread.java:3019)
1月2日至26日:39:58.466:E / AndroidRuntime(943):在android.app.ActivityThread.handlePauseActivity(ActivityThread.java:2997)
1月2日至26日:39:58.466:E / AndroidRuntime(943):在android.app.ActivityThread.access $ 800(ActivityThread.java:141)
1月2日至26日:39:58.466:E / AndroidRuntime(943):在android.app.ActivityThread $ H.handleMessage(ActivityThread.java:1273)
1月2日至26日:39:58.466:E / AndroidRuntime(943):在android.os.Handler.dispatchMessage(Handler.java:99)
1月2日至26日:39:58.466:E / AndroidRuntime(943):在android.os.Looper.loop(Looper.java:137)
1月2日至26日:39:58.466:E / AndroidRuntime(943):在android.app.ActivityThread.main(ActivityThread.java:5103)
1月2日至26日:39:58.466:E / AndroidRuntime(943):在java.lang.reflect.Method.invokeNative(本机方法)
1月2日至26日:39:58.466:E / AndroidRuntime(943):在java.lang.reflect.Method.invoke(Method.java:525)
1月2日至26日:39:58.466:E / AndroidRuntime(943):在com.android.internal.os.ZygoteInit $ MethodAndArgsCaller.run(ZygoteInit.java:737)
1月2日至26日:39:58.466:E / AndroidRuntime(943):在com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
1月2日至26日:39:58.466:E / AndroidRuntime(943):在dalvik.system.NativeStart.main(本机方法)
1月2日至26日:39:58.466:E / AndroidRuntime(943):java.lang.IllegalArgumentException异常:由接收器造成未注册日期null
1月2日至26日:39:58.466:E / AndroidRuntime(943):在android.app.LoadedApk.forgetReceiverDispatcher(LoadedApk.java:662)
1月2日至26日:39:58.466:E / AndroidRuntime(943):在android.app.ContextImpl.unregisterReceiver(ContextImpl.java:1372)
1月2日至26日:39:58.466:E / AndroidRuntime(943):在android.content.ContextWrapper.unregisterReceiver(ContextWrapper.java:468)
1月2日至26日:39:58.466:E / AndroidRuntime(943):在course.labs.notificationslab.MainActivity.onPause(MainActivity.java:195)
1月2日至26日:39:58.466:E / AndroidRuntime(943):在android.app.Activity.performPause(Activity.java:5235)
1月2日至26日:39:58.466:E / AndroidRuntime(943):在android.app.Instrumentation.callActivityOnPause(Instrumentation.java:1233)
1月2日至26日:39:58.466:E / AndroidRuntime(943):在android.app.ActivityThread.performPauseActivity(ActivityThread.java:3050)
1月2日至26日:39:58.466:E / AndroidRuntime(943):12 ...更多
 

下面是$ C $下的AsyncTask,但LogCat中说,错误是主要的。

  mApplicationContext.sendOrderedBroadcast(
            新的意图(MainActivity.DATA_REFRESHED_ACTION)
            空值,
            新的BroadcastReceiver(){

                最后弦乐failMsg =下载失败请重试之后。
                最后弦乐successMsg =下载成功完成。

                @覆盖
                公共无效的onReceive(上下文的背景下,意图意图){

                    日志(输入结果接收机的onReceive()方法);

                    // TODO:检查结果code是否RESULT_OK

                    如果(的getResult code()== Activity.RESULT_OK){

                        // TODO:如果是这样,创建使用PendingIntent的
                        // restartMainActivityIntent并设置其标志
                        //为FLAG_UPDATE_CURRENT

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



                        //使用R.layout.custom_notification为
                        //通知视图的布局。在XML
                        //文件在RES /布局/ custom_notification.xml

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

                        // TODO:设置通知视图的文本
                        //反映下载是否完成
                        //成功

                         如果(成功){
                        mContentView.setTextViewText(MY_NOTIFICATION_ID,successMsg);
                         }其他{
                             mContentView.setTextViewText(MY_NOTIFICATION_ID,failMsg);
                         }

                        // TODO:使用Notification.Builder类
                        //创建的通知。你将不得不设置
                        //几条信息。您可以使用
                        // android.R.drawable.stat_sys_warning
                        //为小图标。你也应该setAutoCancel(真)。



                        // TODO:发送通知

                        通知通知=新Notification.Builder(mApplicationContext)
                        .setContentIntent(pendingIntent)
                        .setSmallIcon(android.R.drawable.stat_sys_warning)
                        .setAutoCancel(真)
                        。建立();

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

                        日志(通知区域发送通知);
                    }
                }
            },
            空值,
            0,
            空值,
            空值);
}
 

解决方案

尝试如下...

  mRefreshReceiver =新的BroadcastReceiver(){

        @覆盖
        公共无效的onReceive(上下文的背景下,意图意图){

            日志(BroadcastIntent容纳在MainActivity);

        }
    }
 

onResume() ...

  @覆盖
保护无效onResume(){
    super.onResume();

    IntentFilter的过滤器=新的IntentFilter(DATA_REFRESHED_ACTION);
    registerReceiver(mRefreshReceiver,过滤器);

}
 

的AsyncTask ...

 意向意图=新的意图(DATA_REFRESHED_ACTION);
    sendOrderedBroadcast(意向,空,新的BroadcastReceiver(){

        @燮pressLint(NewApi)
        @覆盖
        公共无效的onReceive(上下文的背景下,意图意图){

            日志(BroadcastIntent容纳在MainActivity);

        }
    },空,Activity.RESULT_OK,NULL,NULL);
}
 

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

的Andr​​oid sendOrderedBroadcast例

I have a progamm with async task and a broadcast receiver to send a result code, so that Asynctask will know that app is working. But it crashes, sayin the receiver is unreggistred in main activity. I've registred one receiver in main activity, another receiver is in AsyncTask Activity. So here the code and log cat.

    @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

Here is code for AsyncTask, but LogCat says an error is in main.

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);
}

解决方案

Try as follows...

    mRefreshReceiver = new BroadcastReceiver() {

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

            log("BroadcastIntent received in MainActivity");

        }
    }

In onResume()...

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

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

}

In 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);
}

You can follow the below link...

Android sendOrderedBroadcast Example

这篇关于接收器未注册的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆