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...