下面列出了android.support.v4.app.TaskStackBuilder#getPendingIntent ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private PendingIntent getBrowserPendingIntent(int type) {
Intent browserIntent = PrefManager.getWebViewIntent(context);
browserIntent.setAction(WebReviewActivity.OPEN_ACTION);
switch (type) {
case BROWSER_TYPE_LESSONS:
browserIntent.setData(Uri.parse(Browser.LESSON_URL));
break;
case BROWSER_TYPE_REVIEWS:
browserIntent.setData(Uri.parse(Browser.REVIEW_URL));
break;
}
TaskStackBuilder browserStackBuilder = TaskStackBuilder.create(context);
browserStackBuilder.addParentStack(
PrefManager.getHWAccel() ? WebReviewActivity.class : SWWebReviewActivity.class);
browserStackBuilder.addNextIntent(browserIntent);
return browserStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
}
public void myStartForeground() {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("计步器")
.setContentText("正在运行");
Intent notificationIntent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
startForeground(1, mBuilder.build());
}
protected void notifyWifiDisabled() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(getContext())
.setSmallIcon (R.drawable.wifiac_small)//(android.R.drawable.presence_offline)
.setContentTitle(getResourceString(R.string.notif_wifi_disabled_title))
.setContentText(authHost + " - " + getResourceString(R.string.notif_wifi_disabled_text));
Intent resultIntent = makeIntent(MainActivity.class);
if (prefs.getReenableWifiQuiet())
resultIntent.setAction(getResourceString(R.string.action_reenable_wifi));
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(getContext());
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
builder.setContentIntent(resultPendingIntent);
Notification n = builder.build();
debug("posting notification that wifi was disabled (" + n.toString() + ")");
NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
nm.notify(0, n);
}
/**
* Displays a notification with the location results.
*/
void showNotification() {
Intent notificationIntent = new Intent(mContext, MainActivity.class);
// Construct a task stack.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
// Add the main Activity to the task stack as the parent.
stackBuilder.addParentStack(MainActivity.class);
// Push the content Intent onto the stack.
stackBuilder.addNextIntent(notificationIntent);
// Get a PendingIntent containing the entire back stack.
PendingIntent notificationPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
Notification.Builder notificationBuilder = new Notification.Builder(mContext,
PRIMARY_CHANNEL)
.setContentTitle(getLocationResultTitle())
.setContentText(getLocationResultText())
.setSmallIcon(R.mipmap.ic_launcher)
.setAutoCancel(true)
.setContentIntent(notificationPendingIntent);
getNotificationManager().notify(0, notificationBuilder.build());
}
/**
* The '@JavascriptInterface is required to make the method accessible from the Javascript
* layer
*
* The code in this method is based on the documentation here:
*
* http://developer.android.com/training/notify-user/build-notification.html
*
* @param message The message displayed in the notification
*/
@JavascriptInterface
public void showNotification(String message) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(mContext)
.setSmallIcon(R.drawable.notification_icon)
.setContentTitle(mContext.getString(R.string.notification_title))
.setContentText(message)
.setAutoCancel(true);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(mContext, MainActivity.class);
resultIntent.putExtra(MainFragment.EXTRA_FROM_NOTIFICATION, true);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(-1, mBuilder.build());
}
public static PendingIntent getTransferPendingIntent(Context context, String notificationId) {
Intent intent = new Intent(context, AccountHistoryActivity.class);
Bundle bundle = new Bundle();
String username = HaprampPreferenceManager.getInstance().getCurrentSteemUsername();
bundle.putString(EXTRA_USERNAME, username);
bundle.putString(Constants.EXTRAA_KEY_NOTIFICATION_ID, notificationId);
intent.putExtras(bundle);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntentWithParentStack(intent);
return stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
}
public void createNotification(String text, Context context) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Test notification")
.setContentText(text);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, MainNormalActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainNormalActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(676, mBuilder.build());
}
private void showDisconnectionNotification(String title, String message) {
String channel = Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? "error" : "";
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this, channel)
.setPriority(PRIORITY_MAX)
.setSmallIcon(android.R.drawable.stat_notify_error)
.setContentTitle(title)
.setContentText(message)
.setTicker(message)
.setVibrate(new long[]{1000, 1000, 1000, 1000, 1000});
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(USB_DISCONNECT_NOFICATION_ID, mBuilder.build());
}
private Notification notification(CrashViewModel crashViewModel) {
Intent crashActivityIntent = new Intent(context, CrashActivity.class);
crashActivityIntent.putExtra(CrashActivity.CRASH_ID, crashViewModel.getIdentifier());
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(CrashActivity.class);
stackBuilder.addNextIntent(crashActivityIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(221, FLAG_UPDATE_CURRENT);
Notification.Builder notificationBuilder = new Notification.Builder(context)
.setContentTitle(crashViewModel.getPlace())
.setContentText(crashViewModel.getDate())
.setSmallIcon(R.mipmap.ic_stat_sherlock_logo)
.setContentIntent(pendingIntent)
.setAutoCancel(true);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
notificationBuilder.setColor(ContextCompat.getColor(context, R.color.sherlock_colorAccent));
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
notificationBuilder.setChannelId(CHANNEL_ID);
}
return notificationBuilder.build();
}
private void sendNotification(String notificationDetails) {
// Create an explicit content Intent that starts the main Activity.
Intent notificationIntent = new Intent(getApplicationContext(), MainActivity.class);
// Construct a task stack.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Add the main Activity to the task stack as the parent.
stackBuilder.addParentStack(MainActivity.class);
// Push the content Intent onto the stack.
stackBuilder.addNextIntent(notificationIntent);
// Get a PendingIntent containing the entire back stack.
PendingIntent notificationPendingIntent =
stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// Get a notification builder that's compatible with platform versions >= 4
NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
// Define the notification settings.
builder.setColor(Color.RED)
.setContentTitle(notificationDetails)
.setContentText("Click notification to return to App")
.setContentIntent(notificationPendingIntent);
// Dismiss notification once the user touches it.
builder.setAutoCancel(true);
// Get an instance of the Notification manager
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// Issue the notification
mNotificationManager.notify(0, builder.build());
}
public static PendingIntent getClementineRemotePendingIntent(Context context) {
// Set the result intent
Intent resultIntent = new Intent(context, MainActivity.class);
resultIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
resultIntent.putExtra(ClementineMediaSessionNotification.EXTRA_NOTIFICATION_ID, -1);
// Create a TaskStack, so the app navigates correctly backwards
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
return stackBuilder.getPendingIntent(9912, PendingIntent.FLAG_UPDATE_CURRENT);
}
public void createNotification(String text, Context context) {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(context)
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("Test notification")
.setContentText(text);
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(context, MainServiceActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainServiceActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(676, mBuilder.build());
}
public static PendingIntent getPendingIntent(@NonNull Context context, @NonNull CharacterVO character, int id) {
Intent intent = new Intent(context, CharacterActivity.class);
intent.setAction(Integer.toString(id)); // Used to update all PendingIntent extras data for each widget
intent.putExtra(EXTRA_CHARACTER, character);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntentWithParentStack(intent); // Return to MainActivity
return stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
}
private void init() {
final List<String> applys = new ArrayList<>();
final List<String> plugins = new ArrayList<>();
CPUVoltage.storeVoltageTable(this);
if (Screen.isScreenAutoHBMActive(this) && Screen.hasScreenHBM()) {
startService(new Intent(this, AutoHighBrightnessModeService.class));
}
Class[] classes = {BatteryFragment.class, CPUFragment.class, CPUHotplugFragment.class,
CPUVoltageFragment.class, EntropyFragment.class, GPUFragment.class, IOFragment.class,
KSMFragment.class, LMKFragment.class, MiscFragment.class,
ScreenFragment.class, SoundFragment.class, ThermalFragment.class, WakeLockFragment.class,
VMFragment.class, WakeFragment.class, CoreControl.class
};
for (Class mClass : classes)
if (Utils.getBoolean(mClass.getSimpleName() + "onboot", false, this)) {
log("Applying on boot for " + mClass.getSimpleName());
applys.addAll(Utils.getApplys(mClass));
}
String plugs;
if (!(plugs = Utils.getString("plugins", "", this)).isEmpty()) {
String[] ps = plugs.split("wefewfewwgwe");
for (String plug : ps)
if (Utils.getBoolean(plug + "onboot", false, this)) plugins.add(plug);
}
if (applys.size() > 0 || plugins.size() > 0) {
final int delay = Utils.getInt("applyonbootdelay", 5, this);
mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
mBuilder = new NotificationCompat.Builder(this);
mBuilder.setContentTitle(getString(R.string.apply_on_boot))
.setContentText(getString(R.string.apply_on_boot_time, delay))
.setSmallIcon(R.drawable.ic_launcher_preview);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(new Intent(this, MainActivity.class));
PendingIntent pendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pendingIntent);
new Thread(new Runnable() {
@Override
public void run() {
boolean notification = Utils.getBoolean("applyonbootnotification", true, BootService.this);
for (int i = delay; i >= 0; i--)
try {
Thread.sleep(1000);
String note = getString(R.string.apply_on_boot_time, i);
if (notification) {
mBuilder.setContentText(note).setProgress(delay, delay - i, false);
mNotifyManager.notify(id, mBuilder.build());
} else if ((i % 10 == 0 || i == delay) && i != 0) toast(note);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (notification) {
mBuilder.setContentText(getString(R.string.apply_on_boot_finished)).setProgress(0, 0, false);
mNotifyManager.notify(id, mBuilder.build());
}
apply(applys, plugins);
stopSelf();
}
}).start();
} else stopSelf();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
prefUnitType = mSharedPreferences.getBoolean(Const.KEY_PREF_UNIT_TYPE, prefUnitType);
prefKnots = mSharedPreferences.getBoolean(Const.KEY_PREF_KNOTS, prefKnots);
prefCoord = Integer.valueOf(mSharedPreferences.getString(Const.KEY_PREF_COORD, Integer.toString(prefCoord)));
mNotifyFix = mSharedPreferences.getBoolean(Const.KEY_PREF_NOTIFY_FIX, mNotifyFix);
mNotifySearch = mSharedPreferences.getBoolean(Const.KEY_PREF_NOTIFY_SEARCH, mNotifySearch);
if (mLocationManager.getAllProviders().indexOf(LocationManager.PASSIVE_PROVIDER) >= 0) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)
requestLocationUpdates();
else
Log.w("PasvLocListenerService", "ACCESS_FINE_LOCATION permission not granted. Data display will not be available.");
} else {
Log.w("PasvLocListenerService", "No passive location provider found. Data display will not be available.");
}
mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_stat_notify_location)
.setContentTitle(getString(R.string.value_none))
.setContentText(getString(R.string.value_none))
.setWhen(0)
.setVisibility(Notification.VISIBILITY_PUBLIC);
Intent mainIntent = new Intent(this, MainActivity.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(mainIntent);
PendingIntent mainPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(mainPendingIntent);
// if we were started through a broadcast, mGpsStatusReceiver had
// no way of picking it up, so we need to forward it manually
mGpsStatusReceiver.onReceive(this, intent);
return START_STICKY;
}
private void onRequestSuccess(List<GraphObject> list)
{
Log.d("FriendRequestService", "Num friend request : " + list.size());
Log.d("FriendRequestService", "Service : " + service.get());
if (service.get() == null)
return;
Service s = service.get();
if (list.size() > 0)
{
FriendRequest fq = (FriendRequest) list.get(0);
KlyphPreferences.setFriendRequestServiceOffset(fq.getTime());
final Builder builder = KlyphNotification.getBuilder(s, true);
builder.setContentTitle(fq.getUid_from_name()).setContentText(
s.getString(R.string.notification_friendrequest_message, fq.getUid_from_name()));
if (KlyphPreferences.mustGroupNotifications() && list.size() > 1)
{
sendNotification(list);
}
else
{
boolean isFirst = true;
for (GraphObject graphObject : list)
{
FriendRequest fr = (FriendRequest) graphObject;
TaskStackBuilder stackBuilder = TaskStackBuilder.create(service.get());
Intent intent = Klyph.getIntentForGraphObject(service.get(), fr);
// stackBuilder.addParentStack(UserActivity.class);
Intent mainIntent = new Intent(service.get(), MainActivity.class);
mainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP
| Intent.FLAG_ACTIVITY_REORDER_TO_FRONT | Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET
| Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
stackBuilder.addNextIntent(mainIntent);
stackBuilder.addNextIntent(intent);
int intentCode = (int) Math.round(Math.random() * 1000000);
// Gets a PendingIntent containing the entire back stack
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(intentCode, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
builder.setContentTitle(fr.getUid_from_name());
builder.setContentText(s.getString(R.string.notification_friendrequest_message, fr.getUid_from_name()));
builder.setTicker(s.getString(R.string.notification_friendrequest_message, fr.getUid_from_name()));
if (isFirst == false)
{
KlyphNotification.setNoSound(builder);
KlyphNotification.setNoVibration(builder);
}
KlyphNotification.sendNotification(s, builder);
isFirst = false;
}
}
service.get().stopSelf();
}
else
{
s.stopSelf();
}
}
private void notifyWeather() {
Context context = getContext();
//checking the last update and notify if it' the first of the day
SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
String displayNotificationsKey = context.getString(R.string.pref_enable_notifications_key);
boolean displayNotifications = prefs.getBoolean(displayNotificationsKey,
Boolean.parseBoolean(context.getString(R.string.pref_enable_notifications_default)));
if ( displayNotifications ) {
String lastNotificationKey = context.getString(R.string.pref_last_notification);
long lastSync = prefs.getLong(lastNotificationKey, 0);
if (System.currentTimeMillis() - lastSync >= DAY_IN_MILLIS) {
// Last sync was more than 1 day ago, let's send a notification with the weather.
String locationQuery = Utility.getPreferredLocation(context);
Uri weatherUri = WeatherContract.WeatherEntry.buildWeatherLocationWithDate(locationQuery, System.currentTimeMillis());
// we'll query our contentProvider, as always
Cursor cursor = context.getContentResolver().query(weatherUri, NOTIFY_WEATHER_PROJECTION, null, null, null);
if (cursor.moveToFirst()) {
int weatherId = cursor.getInt(INDEX_WEATHER_ID);
double high = cursor.getDouble(INDEX_MAX_TEMP);
double low = cursor.getDouble(INDEX_MIN_TEMP);
String desc = cursor.getString(INDEX_SHORT_DESC);
int iconId = Utility.getIconResourceForWeatherCondition(weatherId);
Resources resources = context.getResources();
Bitmap largeIcon = BitmapFactory.decodeResource(resources,
Utility.getArtResourceForWeatherCondition(weatherId));
String title = context.getString(R.string.app_name);
// Define the text of the forecast.
String contentText = String.format(context.getString(R.string.format_notification),
desc,
Utility.formatTemperature(context, high),
Utility.formatTemperature(context, low));
// NotificationCompatBuilder is a very convenient way to build backward-compatible
// notifications. Just throw in some data.
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(getContext())
.setColor(resources.getColor(R.color.sunshine_light_blue))
.setSmallIcon(iconId)
.setLargeIcon(largeIcon)
.setContentTitle(title)
.setContentText(contentText);
// Make something interesting happen when the user clicks on the notification.
// In this case, opening the app is sufficient.
Intent resultIntent = new Intent(context, MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getContext().getSystemService(Context.NOTIFICATION_SERVICE);
// WEATHER_NOTIFICATION_ID allows you to update the notification later on.
mNotificationManager.notify(WEATHER_NOTIFICATION_ID, mBuilder.build());
//refreshing last sync
SharedPreferences.Editor editor = prefs.edit();
editor.putLong(lastNotificationKey, System.currentTimeMillis());
editor.commit();
}
cursor.close();
}
}
}
/**
* Constructs and displays a notification for the newly updated weather for today.
*
* @param context Context used to query our ContentProvider and use various Utility methods
*/
public static void notifyUserOfNewWeather(Context context) {
/* Build the URI for today's weather in order to show up to date data in notification */
Uri todaysWeatherUri = WeatherContract.WeatherEntry
.buildWeatherUriWithDate(SunshineDateUtils.normalizeDate(System.currentTimeMillis()));
/*
* The MAIN_FORECAST_PROJECTION array passed in as the second parameter is defined in our WeatherContract
* class and is used to limit the columns returned in our cursor.
*/
Cursor todayWeatherCursor = context.getContentResolver().query(
todaysWeatherUri,
WEATHER_NOTIFICATION_PROJECTION,
null,
null,
null);
/*
* If todayWeatherCursor is empty, moveToFirst will return false. If our cursor is not
* empty, we want to show the notification.
*/
if (todayWeatherCursor.moveToFirst()) {
/* Weather ID as returned by API, used to identify the icon to be used */
int weatherId = todayWeatherCursor.getInt(INDEX_WEATHER_ID);
double high = todayWeatherCursor.getDouble(INDEX_MAX_TEMP);
double low = todayWeatherCursor.getDouble(INDEX_MIN_TEMP);
Resources resources = context.getResources();
int largeArtResourceId = SunshineWeatherUtils
.getLargeArtResourceIdForWeatherCondition(weatherId);
Bitmap largeIcon = BitmapFactory.decodeResource(
resources,
largeArtResourceId);
String notificationTitle = context.getString(R.string.app_name);
String notificationText = getNotificationText(context, weatherId, high, low);
/* getSmallArtResourceIdForWeatherCondition returns the proper art to show given an ID */
int smallArtResourceId = SunshineWeatherUtils
.getSmallArtResourceIdForWeatherCondition(weatherId);
// COMPLETED (2) Use NotificationCompat.Builder to begin building the notification
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
.setColor(ContextCompat.getColor(context, R.color.colorPrimary))
.setSmallIcon(smallArtResourceId)
.setLargeIcon(largeIcon)
.setContentTitle(notificationTitle)
.setContentText(notificationText)
.setAutoCancel(true);
// COMPLETED (3) Create an Intent with the proper URI to start the DetailActivity
/*
* This Intent will be triggered when the user clicks the notification. In our case,
* we want to open Sunshine to the DetailActivity to display the newly updated weather.
*/
Intent detailIntentForToday = new Intent(context, DetailActivity.class);
detailIntentForToday.setData(todaysWeatherUri);
// COMPLETED (4) Use TaskStackBuilder to create the proper PendingINtent
TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
taskStackBuilder.addNextIntentWithParentStack(detailIntentForToday);
PendingIntent resultPendingIntent = taskStackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
// COMPLETED (5) Set the content Intent of the NotificationBuilder
notificationBuilder.setContentIntent(resultPendingIntent);
// COMPLETED (6) Get a reference to the NotificationManager
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
// COMPLETED (7) Notify the user with the ID WEATHER_NOTIFICATION_ID
/* WEATHER_NOTIFICATION_ID allows you to update or cancel the notification later on */
notificationManager.notify(WEATHER_NOTIFICATION_ID, notificationBuilder.build());
// COMPLETED (8) Save the time at which the notification occurred using SunshinePreferences
/*
* Since we just showed a notification, save the current time. That way, we can check
* next time the weather is refreshed if we should show another notification.
*/
SunshinePreferences.saveLastNotificationTime(context, System.currentTimeMillis());
}
/* Always close your cursor when you're done with it to avoid wasting resources. */
todayWeatherCursor.close();
}
/**
* Constructs and displays a notification for the newly updated weather for today.
*
* @param context Context used to query our ContentProvider and use various Utility methods
*/
public static void notifyUserOfNewWeather(Context context) {
/* Build the URI for today's weather in order to show up to date data in notification */
Uri todaysWeatherUri = WeatherContract.WeatherEntry
.buildWeatherUriWithDate(SunshineDateUtils.normalizeDate(System.currentTimeMillis()));
/*
* The MAIN_FORECAST_PROJECTION array passed in as the second parameter is defined in our WeatherContract
* class and is used to limit the columns returned in our cursor.
*/
Cursor todayWeatherCursor = context.getContentResolver().query(
todaysWeatherUri,
WEATHER_NOTIFICATION_PROJECTION,
null,
null,
null);
/*
* If todayWeatherCursor is empty, moveToFirst will return false. If our cursor is not
* empty, we want to show the notification.
*/
if (todayWeatherCursor.moveToFirst()) {
/* Weather ID as returned by API, used to identify the icon to be used */
int weatherId = todayWeatherCursor.getInt(INDEX_WEATHER_ID);
double high = todayWeatherCursor.getDouble(INDEX_MAX_TEMP);
double low = todayWeatherCursor.getDouble(INDEX_MIN_TEMP);
Resources resources = context.getResources();
int largeArtResourceId = SunshineWeatherUtils
.getLargeArtResourceIdForWeatherCondition(weatherId);
Bitmap largeIcon = BitmapFactory.decodeResource(
resources,
largeArtResourceId);
String notificationTitle = context.getString(R.string.app_name);
String notificationText = getNotificationText(context, weatherId, high, low);
/* getSmallArtResourceIdForWeatherCondition returns the proper art to show given an ID */
int smallArtResourceId = SunshineWeatherUtils
.getSmallArtResourceIdForWeatherCondition(weatherId);
/*
* NotificationCompat Builder is a very convenient way to build backward-compatible
* notifications. In order to use it, we provide a context and specify a color for the
* notification, a couple of different icons, the title for the notification, and
* finally the text of the notification, which in our case in a summary of today's
* forecast.
*/
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
.setColor(ContextCompat.getColor(context,R.color.colorPrimary))
.setSmallIcon(smallArtResourceId)
.setLargeIcon(largeIcon)
.setContentTitle(notificationTitle)
.setContentText(notificationText)
.setAutoCancel(true);
/*
* This Intent will be triggered when the user clicks the notification. In our case,
* we want to open Sunshine to the DetailActivity to display the newly updated weather.
*/
Intent detailIntentForToday = new Intent(context, DetailActivity.class);
detailIntentForToday.setData(todaysWeatherUri);
TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
taskStackBuilder.addNextIntentWithParentStack(detailIntentForToday);
PendingIntent resultPendingIntent = taskStackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(resultPendingIntent);
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
/* WEATHER_NOTIFICATION_ID allows you to update or cancel the notification later on */
notificationManager.notify(WEATHER_NOTIFICATION_ID, notificationBuilder.build());
/*
* Since we just showed a notification, save the current time. That way, we can check
* next time the weather is refreshed if we should show another notification.
*/
SunshinePreferences.saveLastNotificationTime(context, System.currentTimeMillis());
}
/* Always close your cursor when you're done with it to avoid wasting resources. */
todayWeatherCursor.close();
}
/**
* Constructs and displays a notification for the newly updated weather for today.
*
* @param context Context used to query our ContentProvider and use various Utility methods
*/
public static void notifyUserOfNewWeather(Context context) {
/* Build the URI for today's weather in order to show up to date data in notification */
Uri todaysWeatherUri = WeatherContract.WeatherEntry
.buildWeatherUriWithDate(SunshineDateUtils.normalizeDate(System.currentTimeMillis()));
/*
* The MAIN_FORECAST_PROJECTION array passed in as the second parameter is defined in our WeatherContract
* class and is used to limit the columns returned in our cursor.
*/
Cursor todayWeatherCursor = context.getContentResolver().query(
todaysWeatherUri,
WEATHER_NOTIFICATION_PROJECTION,
null,
null,
null);
/*
* If todayWeatherCursor is empty, moveToFirst will return false. If our cursor is not
* empty, we want to show the notification.
*/
if (todayWeatherCursor.moveToFirst()) {
/* Weather ID as returned by API, used to identify the icon to be used */
int weatherId = todayWeatherCursor.getInt(INDEX_WEATHER_ID);
double high = todayWeatherCursor.getDouble(INDEX_MAX_TEMP);
double low = todayWeatherCursor.getDouble(INDEX_MIN_TEMP);
Resources resources = context.getResources();
int largeArtResourceId = SunshineWeatherUtils
.getLargeArtResourceIdForWeatherCondition(weatherId);
Bitmap largeIcon = BitmapFactory.decodeResource(
resources,
largeArtResourceId);
String notificationTitle = context.getString(R.string.app_name);
String notificationText = getNotificationText(context, weatherId, high, low);
/* getSmallArtResourceIdForWeatherCondition returns the proper art to show given an ID */
int smallArtResourceId = SunshineWeatherUtils
.getSmallArtResourceIdForWeatherCondition(weatherId);
/*
* NotificationCompat Builder is a very convenient way to build backward-compatible
* notifications. In order to use it, we provide a context and specify a color for the
* notification, a couple of different icons, the title for the notification, and
* finally the text of the notification, which in our case in a summary of today's
* forecast.
*/
NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(context)
.setColor(ContextCompat.getColor(context,R.color.colorPrimary))
.setSmallIcon(smallArtResourceId)
.setLargeIcon(largeIcon)
.setContentTitle(notificationTitle)
.setContentText(notificationText)
.setAutoCancel(true);
/*
* This Intent will be triggered when the user clicks the notification. In our case,
* we want to open Sunshine to the DetailActivity to display the newly updated weather.
*/
Intent detailIntentForToday = new Intent(context, DetailActivity.class);
detailIntentForToday.setData(todaysWeatherUri);
TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(context);
taskStackBuilder.addNextIntentWithParentStack(detailIntentForToday);
PendingIntent resultPendingIntent = taskStackBuilder
.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
notificationBuilder.setContentIntent(resultPendingIntent);
NotificationManager notificationManager = (NotificationManager)
context.getSystemService(Context.NOTIFICATION_SERVICE);
/* WEATHER_NOTIFICATION_ID allows you to update or cancel the notification later on */
notificationManager.notify(WEATHER_NOTIFICATION_ID, notificationBuilder.build());
/*
* Since we just showed a notification, save the current time. That way, we can check
* next time the weather is refreshed if we should show another notification.
*/
SunshinePreferences.saveLastNotificationTime(context, System.currentTimeMillis());
}
/* Always close your cursor when you're done with it to avoid wasting resources. */
todayWeatherCursor.close();
}