Android初学第93天
Android初学第93天
29_BroadcastIntents
代码
PhotoGallery
NotificationReceiver.java
package com.bignerdranch.android.photogallery;
import android.app.Activity;
import android.app.Notification;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.support.v4.app.NotificationManagerCompat;
import android.util.Log;
public class NotificationReceiver extends BroadcastReceiver {
private static final String TAG = "NotificationReceiver";
@Override
public void onReceive(Context c, Intent i) {
Log.i(TAG, "received result: " + getResultCode());
if (getResultCode() != Activity.RESULT_OK) {
// A foreground activity cancelled the broadcast
return;
}
int requestCode = i.getIntExtra(PollService.REQUEST_CODE, 0);
Notification notification = (Notification)
i.getParcelableExtra(PollService.NOTIFICATION);
NotificationManagerCompat notificationManager =
NotificationManagerCompat.from(c);
notificationManager.notify(requestCode, notification);
}
}
VisibleFragment.java
package com.bignerdranch.android.photogallery;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.widget.Toast;
public abstract class VisibleFragment extends Fragment {
private static final String TAG = "VisibleFragment";
private BroadcastReceiver mOnShowNotification = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
// If we receive this, we're visible, so cancel
// the notification
Log.i(TAG, "canceling notification");
setResultCode(Activity.RESULT_CANCELED);
}
};
@Override
public void onStart() {
super.onStart();
IntentFilter filter = new IntentFilter(PollService.ACTION_SHOW_NOTIFICATION);
getActivity().registerReceiver(mOnShowNotification, filter,
PollService.PERM_PRIVATE, null);
}
@Override
public void onStop() {
super.onStop();
getActivity().unregisterReceiver(mOnShowNotification);
}
}