下面列出了android.support.v4.app.TaskStackBuilder#create ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void sendNotification(String title, String body, String webUrl) {
NotificationCompat.Builder builder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.mipmap.ic_stat_gcm)
.setContentTitle(title)
.setContentText(body);
Intent resultIntent = new Intent(getApplicationContext(), MainActivity.class);
resultIntent.putExtra("web_url", webUrl);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(MainActivity.class);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_CANCEL_CURRENT
);
builder.setContentIntent(resultPendingIntent);
NotificationManager notificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(NOTIFICATION_ID, builder.build());
}
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());
}
public static void showNotification(Context context,Class<?> cls,String title,String content)
{
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
Intent notificationIntent = new Intent(context, cls);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addParentStack(cls);
stackBuilder.addNextIntent(notificationIntent);
PendingIntent pendingIntent = stackBuilder.getPendingIntent(DAILY_REMINDER_REQUEST_CODE, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context,context.getPackageName());
Notification notification = builder.setContentTitle(title)
.setContentText(content)
.setAutoCancel(true)
.setSound(alarmSound)
.setSmallIcon(R.drawable.app_icon_144)
.setContentIntent(pendingIntent).build();
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(DAILY_REMINDER_REQUEST_CODE, notification);
}
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);
}
protected void displayCommunityMapNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
.setSmallIcon(MeasurementService.getNotificationIcon())
.setContentTitle(getString(R.string.notification_goto_community_map_title))
.setContentText(getString(R.string.notification_goto_community_map))
.setAutoCancel(true);
NotificationCompat.BigTextStyle bigTextStyle =
new NotificationCompat.BigTextStyle();
bigTextStyle.setBigContentTitle(getString(R.string.notification_goto_community_map_title));
bigTextStyle.bigText(getString(R.string.notification_goto_community_map));
builder.setStyle(bigTextStyle);
Intent intent = new Intent(Intent.ACTION_VIEW);
intent.setData(Uri.parse("http://noise-planet.org/map_noisecapture"));
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(this);
stackBuilder.addNextIntent(intent);
builder.setContentIntent(stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT));
NotificationManager mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
mNM.notify(NOTIFICATION_MAP, builder.build());
}
/**
* Enables back navigation for activities that are launched from the NavBar. See
* {@code AndroidManifest.xml} to find out the parent activity names for each activity.
*
* @param intent
*/
private void createBackStack(Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
TaskStackBuilder builder = TaskStackBuilder.create(this);
builder.addNextIntentWithParentStack(intent);
builder.startActivities();
} else {
startActivity(intent);
finish();
}
}
public static void showNotification(Context mContext, String info) {
android.support.v4.app.NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(mContext)
.setSmallIcon(R.drawable.inspectorw)
.setContentTitle("Inspeckage")
.setContentText(info);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(mContext);
stackBuilder.addParentStack(MainActivity.class);
NotificationManager mNotificationManager = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
mNotificationManager.notify(0, mBuilder.build());
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
cancelNotification = (TextView) findViewById(R.id.cancelNotification);
cancelNotification.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View arg0) {
cancelNotification();
}
});
Uri alarmSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION); // get default notification sound
long[] vibrate = { 100, 200, 300, 400 }; // get vibration value
NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this);
nBuilder.setSmallIcon(R.drawable.ic_action_chat);
nBuilder.setContentTitle("Sample Notification");
nBuilder.setContentText("Welcome your app is running");
nBuilder.setTicker("Alert!!!");
nBuilder.setNumber(++numMessages);
nBuilder.setSound(alarmSound); // set default notification sound
nBuilder.setVibrate(vibrate); // set vibrate
nBuilder.setAutoCancel(true); // hide/remove notification from notification panel
Intent intentResult = new Intent(this, NotificationView.class);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
stackBuilder.addParentStack(NotificationView.class);
stackBuilder.addNextIntent(intentResult);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
nBuilder.setContentIntent(resultPendingIntent);
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(notificationID, nBuilder.build());
}
/**
* Enables back navigation for activities that are launched from the NavBar. See
* {@code AndroidManifest.xml} to find out the parent activity names for each activity.
*
* @param intent
*/
private void createBackStack(Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
TaskStackBuilder builder = TaskStackBuilder.create(this);
builder.addNextIntentWithParentStack(intent);
builder.startActivities();
} else {
startActivity(intent);
finish();
}
}
public void showNotification() {
remoteViews = new RemoteViews(context.getPackageName(), R.layout.streaming_notification_player);
notifyBuilder = new Notification.Builder(this.context)
.setSmallIcon(android.R.drawable.ic_lock_silent_mode_off) // TODO Use app icon instead
.setContentText("")
.setOngoing(true)
.setContent(remoteViews);
Intent resultIntent = new Intent(this.context, this.clsActivity);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this.context);
stackBuilder.addParentStack(this.clsActivity);
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,
PendingIntent.FLAG_UPDATE_CURRENT);
notifyBuilder.setContentIntent(resultPendingIntent);
remoteViews.setOnClickPendingIntent(R.id.btn_streaming_notification_play, makePendingIntent(BROADCAST_PLAYBACK_PLAY));
remoteViews.setOnClickPendingIntent(R.id.btn_streaming_notification_stop, makePendingIntent(BROADCAST_EXIT));
notifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
if (android.os.Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
NotificationChannel channel =
new NotificationChannel("com.audioStreaming", "Audio Streaming",
NotificationManager.IMPORTANCE_HIGH);
if (notifyManager != null) {
notifyManager.createNotificationChannel(channel);
}
notifyBuilder.setChannelId("com.audioStreaming");
notifyBuilder.setOnlyAlertOnce(true);
}
notifyManager.notify(NOTIFY_ME_ID, notifyBuilder.build());
}
/**
* Requests permissions to be granted to this application.
*
* This method is a wrapper around
* {@link android.support.v4.app.ActivityCompat#requestPermissions(android.app.Activity, String[], int)}
* which works in a similar way, except it can be called from non-activity contexts. When called, it
* displays a notification with a customizable title and text. When the user taps the notification, an
* activity is launched in which the user is prompted to allow or deny the request.
*
* After the user has made a choice,
* {@link android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback#onRequestPermissionsResult(int, String[], int[])}
* is called, reporting whether the permissions were granted or not.
*
* @param context The context from which the request was made. The context supplied must implement
* {@link android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback} and will receive the
* result of the operation.
* @param permissions The requested permissions
* @param requestCode Application specific request code to match with a result reported to
* {@link android.support.v4.app.ActivityCompat.OnRequestPermissionsResultCallback#onRequestPermissionsResult(int, String[], int[])}
* @param notificationTitle The title for the notification
* @param notificationText The text for the notification
* @param notificationIcon Resource identifier for the notification icon
*/
public static <T extends Context & OnRequestPermissionsResultCallback> void requestPermissions(final T context, String[] permissions, int requestCode, String notificationTitle, String notificationText, int notificationIcon) {
ResultReceiver resultReceiver = new ResultReceiver(new Handler(Looper.getMainLooper())) {
@Override
protected void onReceiveResult (int resultCode, Bundle resultData) {
String[] outPermissions = resultData.getStringArray(Const.KEY_PERMISSIONS);
int[] grantResults = resultData.getIntArray(Const.KEY_GRANT_RESULTS);
context.onRequestPermissionsResult(resultCode, outPermissions, grantResults);
}
};
Intent permIntent = new Intent(context, PermissionRequestActivity.class);
permIntent.putExtra(Const.KEY_RESULT_RECEIVER, resultReceiver);
permIntent.putExtra(Const.KEY_PERMISSIONS, permissions);
permIntent.putExtra(Const.KEY_REQUEST_CODE, requestCode);
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
stackBuilder.addNextIntent(permIntent);
PendingIntent permPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setSmallIcon(notificationIcon)
.setContentTitle(notificationTitle)
.setContentText(notificationText)
.setOngoing(true)
//.setCategory(Notification.CATEGORY_STATUS)
.setAutoCancel(true)
.setWhen(0)
.setContentIntent(permPendingIntent)
.setStyle(null);
NotificationManager notificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
notificationManager.notify(requestCode, builder.build());
}
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());
}
/**
* Enables back navigation for activities that are launched from the NavBar. See
* {@code AndroidManifest.xml} to find out the parent activity names for each activity.
* @param intent
*/
private void createBackStack(Intent intent) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
TaskStackBuilder builder = TaskStackBuilder.create(this);
builder.addNextIntentWithParentStack(intent);
builder.startActivities();
} else {
startActivity(intent);
finish();
}
}
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();
}
}
/**
* 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();
}
/**
* 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();
}
public static void sendNotification(Context context, Builder builder)
{
TaskStackBuilder stackBuilder = TaskStackBuilder.create(context);
Intent resultIntent = new Intent(context, MainActivity.class);
resultIntent.putExtra(KlyphBundleExtras.SHOW_NOTIFICATION_MENU, true);
stackBuilder.addNextIntentWithParentStack(resultIntent);
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);
Intent intent = new Intent(context, NotificationGroupDeletedReceiver.class);
builder.setDeleteIntent(PendingIntent.getBroadcast(context.getApplicationContext(), 0, intent, PendingIntent.FLAG_UPDATE_CURRENT));
final NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
final String tag = context.getPackageName() + "_grouped";
final int id = 0;
// pair (tag, id) must be unique
// tag is the unique key
mNotificationManager.notify(tag, id, builder.build());
}
/**
* Enables back navigation for activities that are launched from the NavBar. See
* {@code AndroidManifest.xml} to find out the parent activity names for each activity.
*
* @param intent
*/
private void createBackStack(Intent intent) {
TaskStackBuilder builder = TaskStackBuilder.create(this);
builder.addNextIntentWithParentStack(intent);
builder.startActivities();
}