下面列出了android.app.Notification#FLAG_ONGOING_EVENT 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
@Override
public Notification build() {
Notification notification = new Notification();
notification.icon = ongoing ? R.drawable.ic_download_animation : R.drawable.ic_notification;
try {
Method m = notification.getClass().getMethod("setLatestEventInfo", Context.class, CharSequence.class, CharSequence.class, PendingIntent.class);
m.invoke(notification, context, title, message, getPendingIntent(intent));
notification.flags |= Notification.FLAG_AUTO_CANCEL;
if (ongoing) {
notification.flags |= Notification.FLAG_ONGOING_EVENT;
notification.flags |= Notification.FLAG_ONLY_ALERT_ONCE;
}
} catch (Exception e) {
// do nothing
}
return notification;
}
@Override
public Notification updateNotification(Context c) {
Notification n = mNotification;
n.icon = mIcon;
n.flags |= Notification.FLAG_ONGOING_EVENT;
if (android.os.Build.VERSION.SDK_INT > 10) {
n.flags |= Notification.FLAG_ONLY_ALERT_ONCE; // only matters for
// Honeycomb
}
// Build the RemoteView object
RemoteViews expandedView = new RemoteViews(
c.getPackageName(),
R.layout.status_bar_ongoing_event_progress_bar);
expandedView.setTextViewText(R.id.title, mTitle);
// look at strings
expandedView.setViewVisibility(R.id.description, View.VISIBLE);
expandedView.setTextViewText(R.id.description,
Helpers.getDownloadProgressString(mCurrentBytes, mTotalBytes));
expandedView.setViewVisibility(R.id.progress_bar_frame, View.VISIBLE);
expandedView.setProgressBar(R.id.progress_bar,
(int) (mTotalBytes >> 8),
(int) (mCurrentBytes >> 8),
mTotalBytes <= 0);
expandedView.setViewVisibility(R.id.time_remaining, View.VISIBLE);
expandedView.setTextViewText(
R.id.time_remaining,
c.getString(R.string.time_remaining_notification,
Helpers.getTimeRemaining(mTimeRemaining)));
expandedView.setTextViewText(R.id.progress_text,
Helpers.getDownloadProgressPercent(mCurrentBytes, mTotalBytes));
expandedView.setImageViewResource(R.id.appIcon, mIcon);
n.contentView = expandedView;
n.contentIntent = mPendingIntent;
return n;
}
@SuppressWarnings("deprecation")
private void enableNotification() {
// Intent to call to turn off AutoAnswer
Intent notificationIntent = new Intent(mContext, AutoAnswerPreferenceActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0, notificationIntent, 0);
// Create the notification
Notification n = new Notification(R.drawable.ic_launcher, null, 0);
n.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_NO_CLEAR;
n.setLatestEventInfo(mContext, mContext.getString(R.string.notification_title), mContext.getString(R.string.notification_text), pendingIntent);
mNotificationManager.notify(NOTIFICATION_ID, n);
}
public static void showNotification(Context context, Settings settings, String text) {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) context.getSystemService(ns);
if (!settings.isShowNotification()) {
// clear existing notification
mNotificationManager.cancel(NOTIFICATION_ID_RUNNING);
return;
}
int icon = R.drawable.ic_stat_notif;
long when = System.currentTimeMillis();
Notification notification = new Notification(icon, null, when);
notification.flags |= Notification.FLAG_ONGOING_EVENT;
notification.flags |= Notification.FLAG_NO_CLEAR;
// define extended notification area
CharSequence contentTitle = "BatteryFu";
CharSequence contentText = text;
Intent notificationIntent = new Intent(context, ModeSelect.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TOP);
PendingIntent contentIntent = PendingIntent.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(NOTIFICATION_ID_RUNNING, notification);
}
/**
* 初始化Notification,此处做Notification的基本设置
*/
private void initNotification() {
try {//解决崩溃问题
PendingIntent contentPendingIntent = createPendingIntent(mContext, SettingActivity.class);
//获取notification管理的实例
notificationManager = (NotificationManager) this.mContext.getSystemService(Context.NOTIFICATION_SERVICE);
createNotification();
notification.flags = Notification.FLAG_ONGOING_EVENT;
notification.contentIntent = contentPendingIntent;
} catch (Exception ex) {
ex.printStackTrace();
} catch (Throwable e) {
e.printStackTrace();
}
}
@SuppressWarnings("deprecation")
public static void showNotification(Context context, int icon, String text)
{
final Notification notifyDetails = new Notification(icon, text, System.currentTimeMillis());
notifyDetails.flags = Notification.FLAG_ONGOING_EVENT;
if (prefsSound(context))
{
notifyDetails.defaults |= Notification.DEFAULT_SOUND;
}
if (prefsVibrate(context))
{
notifyDetails.defaults |= Notification.DEFAULT_VIBRATE;
}
Intent notifyIntent = new Intent(context, ADBWirelessActivity.class);
notifyIntent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent intent = PendingIntent.getActivity(context, 0, notifyIntent, 0);
notifyDetails.setLatestEventInfo(context, context.getResources().getString(R.string.noti_title), text, intent);
if (Utils.mNotificationManager != null)
{
Utils.mNotificationManager.notify(Utils.START_NOTIFICATION_ID, notifyDetails);
}
else
{
Utils.mNotificationManager = (NotificationManager) context.getSystemService(Activity.NOTIFICATION_SERVICE);
}
Utils.mNotificationManager.notify(Utils.START_NOTIFICATION_ID, notifyDetails);
}
/**
* Construct a notification
*/
private void showForwardingEnabledNotification() {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.ic_fwd_24dp)
.setContentTitle(getString(R.string.notification_forwarding_active_title))
.setContentText(getString(R.string.notification_forwarding_touch_disable_text));
mBuilder.setColor(ContextCompat.getColor(this, R.color.colorPrimaryDark));
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, 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(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);
Notification notification = mBuilder.build();
notification.flags = Notification.FLAG_NO_CLEAR | Notification.FLAG_ONGOING_EVENT | Notification.DEFAULT_LIGHTS;
// mId allows you to update the notification later on.
mNotificationManager.notify(NOTIFICATION_ID, notification);
}
private int showSendingNotification() {
final int id = 0;
final Notification notification = new Notification(
R.drawable.ic_notify_icon, "饭否消息正在发送...",
System.currentTimeMillis());
final PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(), 0);
notification.setLatestEventInfo(this, "饭否消息", "正在发送...", contentIntent);
notification.flags |= Notification.FLAG_ONGOING_EVENT;
this.nm.notify(id, notification);
return id;
}
public static Notification createNotification(Context context, String title, String message, int icon, int level, Bitmap largeIcon, PendingIntent intent, boolean isOngoingEvent,int priority) {
Notification notif;
if (largeIcon != null) {
notif = new Notification.Builder(context)
.setContentTitle(title)
.setContentText(message)
.setSmallIcon(icon, level)
.setLargeIcon(largeIcon)
.setContentIntent(intent)
.setWhen(System.currentTimeMillis())
.setPriority(priority)
.build();
} else {
notif = new Notification.Builder(context)
.setContentTitle(title)
.setContentText(message)
.setSmallIcon(icon, level)
.setContentIntent(intent)
.setWhen(System.currentTimeMillis())
.setPriority(priority)
.build();
}
if (isOngoingEvent) {
notif.flags |= Notification.FLAG_ONGOING_EVENT;
}
return notif;
}
private void keepAlive() {
try {
Notification notification = new Notification();
notification.flags |= Notification.FLAG_NO_CLEAR;
notification.flags |= Notification.FLAG_ONGOING_EVENT;
startForeground(0, notification); // 设置为前台服务避免kill,Android4.3及以上需要设置id为0时通知栏才不显示该通知;
} catch (Throwable e) {
e.printStackTrace();
}
}
protected void onStop() {
super.onStop();
if (Logger.isDebug()) {
Log.v(TAG, "onStop……" + ", Skeleton is " + skeleton);
}
if (!sheJiaoMao.isShowStatusIcon()) {
return;
}
int taskId = 0;
ActivityManager am = (ActivityManager)getSystemService(ACTIVITY_SERVICE);
List<RunningTaskInfo> taskInfoList = am.getRunningTasks(1);
if (ListUtil.isNotEmpty(taskInfoList)) {
RunningTaskInfo taskInfo = taskInfoList.get(0);
taskId = taskInfo.id;
}
if (this.getTaskId() != taskId) {
NotificationManager notificationManager = (NotificationManager)
getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent = new Intent(this, SplashActivity.class);
notificationIntent.setAction(Intent.ACTION_MAIN);
notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
PendingIntent contentIntent = PendingIntent.getActivity(
this, (int)System.currentTimeMillis(),
notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
Notification notification = new Notification();
notification.icon = R.drawable.icon_notification;
notification.flags |= Notification.FLAG_ONGOING_EVENT;
notification.flags |= Notification.FLAG_NO_CLEAR;
String contentTitle = this.getString(R.string.app_name);
String contentText = this.getString(R.string.label_ongoing);
notification.contentIntent = contentIntent;
notification.setLatestEventInfo(this, contentTitle, contentText, contentIntent);
notificationManager.notify(R.string.app_name, notification);
}
}
private int showSendingNotification() {
final int id = 10;
final Notification notification = new Notification(
R.drawable.ic_notify_icon, "饭否私信正在发送...",
System.currentTimeMillis());
final PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(), 0);
notification.setLatestEventInfo(this, "饭否私信", "正在发送...", contentIntent);
notification.flags |= Notification.FLAG_ONGOING_EVENT;
this.nm.notify(id, notification);
return id;
}
private boolean isOngoing(int flags) {
return (flags & Notification.FLAG_ONGOING_EVENT) != 0;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i(TAG, "Received start id " + startId + ": " + intent);
if (intent != null) {
distanceFilter = Integer.parseInt(intent.getStringExtra("distanceFilter"));
desiredAccuracy = Integer.parseInt(intent.getStringExtra("desiredAccuracy"));
interval = Integer.parseInt(intent.getStringExtra("interval"));
fastestInterval = Integer.parseInt(intent.getStringExtra("fastestInterval"));
aggressiveInterval = Integer.parseInt(intent.getStringExtra("aggressiveInterval"));
activitiesInterval = Integer.parseInt(intent.getStringExtra("activitiesInterval"));
isDebugging = Boolean.parseBoolean(intent.getStringExtra("isDebugging"));
notificationTitle = intent.getStringExtra("notificationTitle");
notificationText = intent.getStringExtra("notificationText");
useActivityDetection = Boolean.parseBoolean(intent.getStringExtra("useActivityDetection"));
// Build the notification / pending intent
Intent main = new Intent(this, BackgroundLocationServicesPlugin.class);
main.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
PendingIntent pendingIntent = PendingIntent.getActivity(this, 0, main, PendingIntent.FLAG_UPDATE_CURRENT);
Context context = getApplicationContext();
Notification.Builder builder = new Notification.Builder(this);
builder.setContentTitle(notificationTitle);
builder.setContentText(notificationText);
builder.setSmallIcon(context.getApplicationInfo().icon);
Bitmap bm = BitmapFactory.decodeResource(context.getResources(),
context.getApplicationInfo().icon);
float mult = getImageFactor(getResources());
Bitmap scaledBm = Bitmap.createScaledBitmap(bm, (int)(bm.getWidth()*mult), (int)(bm.getHeight()*mult), false);
if(scaledBm != null) {
builder.setLargeIcon(scaledBm);
}
// Integer resId = getPluginResource("location_icon");
//
// //Scale our location_icon.png for different phone resolutions
// //TODO: Get this icon via a filepath from the user
// if(resId != 0) {
// Bitmap bm = BitmapFactory.decodeResource(getResources(), resId);
//
// float mult = getImageFactor(getResources());
// Bitmap scaledBm = Bitmap.createScaledBitmap(bm, (int)(bm.getWidth()*mult), (int)(bm.getHeight()*mult), false);
//
// if(scaledBm != null) {
// builder.setLargeIcon(scaledBm);
// }
// } else {
// Log.w(TAG, "Could NOT find Resource for large icon");
// }
//Make clicking the event link back to the main cordova activity
builder.setContentIntent(pendingIntent);
setClickEvent(builder);
Notification notification;
if (android.os.Build.VERSION.SDK_INT >= 16) {
notification = buildForegroundNotification(builder);
} else {
notification = buildForegroundNotificationCompat(builder);
}
notification.flags |= Notification.FLAG_ONGOING_EVENT | Notification.FLAG_FOREGROUND_SERVICE | Notification.FLAG_NO_CLEAR;
startForeground(startId, notification);
}
// Log.i(TAG, "- url: " + url);
// Log.i(TAG, "- params: " + params.toString());
Log.i(TAG, "- interval: " + interval);
Log.i(TAG, "- fastestInterval: " + fastestInterval);
Log.i(TAG, "- distanceFilter: " + distanceFilter);
Log.i(TAG, "- desiredAccuracy: " + desiredAccuracy);
Log.i(TAG, "- isDebugging: " + isDebugging);
Log.i(TAG, "- notificationTitle: " + notificationTitle);
Log.i(TAG, "- notificationText: " + notificationText);
Log.i(TAG, "- useActivityDetection: " + useActivityDetection);
Log.i(TAG, "- activityDetectionInterval: " + activitiesInterval);
//We want this service to continue running until it is explicitly stopped
return START_REDELIVER_INTENT;
}
public void countApiUse(NotificationRecord record) {
final Notification n = record.getNotification();
if (n.actions != null) {
numWithActions++;
}
if ((n.flags & Notification.FLAG_FOREGROUND_SERVICE) != 0) {
numForegroundService++;
}
if ((n.flags & Notification.FLAG_ONGOING_EVENT) != 0) {
numOngoing++;
}
if ((n.flags & Notification.FLAG_AUTO_CANCEL) != 0) {
numAutoCancel++;
}
if ((n.defaults & Notification.DEFAULT_SOUND) != 0 ||
(n.defaults & Notification.DEFAULT_VIBRATE) != 0 ||
n.sound != null || n.vibrate != null) {
numInterrupt++;
}
switch (n.visibility) {
case Notification.VISIBILITY_PRIVATE:
numPrivate++;
break;
case Notification.VISIBILITY_SECRET:
numSecret++;
break;
}
if (record.stats.isNoisy) {
noisyImportance.increment(record.stats.requestedImportance);
} else {
quietImportance.increment(record.stats.requestedImportance);
}
finalImportance.increment(record.getImportance());
final Set<String> names = n.extras.keySet();
if (names.contains(Notification.EXTRA_BIG_TEXT)) {
numWithBigText++;
}
if (names.contains(Notification.EXTRA_PICTURE)) {
numWithBigPicture++;
}
if (names.contains(Notification.EXTRA_LARGE_ICON)) {
numWithLargeIcon++;
}
if (names.contains(Notification.EXTRA_TEXT_LINES)) {
numWithInbox++;
}
if (names.contains(Notification.EXTRA_MEDIA_SESSION)) {
numWithMediaSession++;
}
if (names.contains(Notification.EXTRA_TITLE) &&
!TextUtils.isEmpty(n.extras.getCharSequence(Notification.EXTRA_TITLE))) {
numWithTitle++;
}
if (names.contains(Notification.EXTRA_TEXT) &&
!TextUtils.isEmpty(n.extras.getCharSequence(Notification.EXTRA_TEXT))) {
numWithText++;
}
if (names.contains(Notification.EXTRA_SUB_TEXT) &&
!TextUtils.isEmpty(n.extras.getCharSequence(Notification.EXTRA_SUB_TEXT))) {
numWithSubText++;
}
if (names.contains(Notification.EXTRA_INFO_TEXT) &&
!TextUtils.isEmpty(n.extras.getCharSequence(Notification.EXTRA_INFO_TEXT))) {
numWithInfoText++;
}
}
/** Convenience method to check the notification's flags for
* either {@link Notification#FLAG_ONGOING_EVENT} or
* {@link Notification#FLAG_NO_CLEAR}.
*/
public boolean isClearable() {
return ((notification.flags & Notification.FLAG_ONGOING_EVENT) == 0)
&& ((notification.flags & Notification.FLAG_NO_CLEAR) == 0);
}
@TargetApi(Build.VERSION_CODES.KITKAT)
@NonNull
public static SimpleNotification toSimpleNotification(@NonNull Notification notification) {
SimpleNotification simpleNotification = new SimpleNotification();
simpleNotification.autoCancel = (notification.flags & Notification.FLAG_AUTO_CANCEL) == Notification.FLAG_AUTO_CANCEL;
android.util.Log.d("json2notification", "autoCancel:" + simpleNotification.autoCancel);
//simpleNotification.bigPictureStyle // TODO
simpleNotification.category = notification.category;
simpleNotification.color = notification.color > 0 ? notification.color : null;
simpleNotification.contentInfo = notification.extras.getString(Notification.EXTRA_INFO_TEXT);
simpleNotification.contentIntent = notification.contentIntent;
simpleNotification.contentTitle = notification.extras.getString(Notification.EXTRA_TITLE);
simpleNotification.contentText = notification.extras.getString(Notification.EXTRA_TEXT);
simpleNotification.defaults = notification.defaults > 0 ? notification.defaults : null;
simpleNotification.deleteIntent = notification.deleteIntent;
//simpleNotification.extras;
simpleNotification.groupKey = notification.getGroup();
if (simpleNotification.groupKey != null) {
simpleNotification.groupSummary = (notification.flags & Notification.FLAG_GROUP_SUMMARY) == Notification.FLAG_GROUP_SUMMARY;
}
Bitmap bitmap = notification.extras.getParcelable(Notification.EXTRA_LARGE_ICON);
if (bitmap != null) simpleNotification.largeIcon = Bitmaps.base64(bitmap);
if ((notification.flags & Notification.FLAG_SHOW_LIGHTS) == Notification.FLAG_SHOW_LIGHTS) {
simpleNotification.lights = Arrays.asList(notification.ledARGB, notification.ledOnMS, notification.ledOffMS);
}
simpleNotification.localOnly = (notification.flags & Notification.FLAG_LOCAL_ONLY) == Notification.FLAG_LOCAL_ONLY;
simpleNotification.number = notification.number > 0 ? notification.number : null;
simpleNotification.ongoing = (notification.flags & Notification.FLAG_ONGOING_EVENT) == Notification.FLAG_ONGOING_EVENT;
simpleNotification.onlyAlertOnce = (notification.flags & Notification.FLAG_ONLY_ALERT_ONCE) == Notification.FLAG_ONLY_ALERT_ONCE;
String[] people = notification.extras.getStringArray(Notification.EXTRA_PEOPLE);
if (people != null) {
simpleNotification.people = Arrays.asList(people);
}
simpleNotification.priority = notification.priority > 0 ? notification.priority : null;
//simpleNotification.progress;
simpleNotification.publicVersion = notification.publicVersion;
simpleNotification.showWhen = notification.extras.getBoolean(Notification.EXTRA_SHOW_WHEN);
if (simpleNotification.showWhen) {
simpleNotification.when = notification.when;
}
simpleNotification.smallIcon = String.valueOf(notification.extras.getInt(Notification.EXTRA_SMALL_ICON)); // TODO getResourceNameById()
android.util.Log.d("json2notification", "simpleNotification.smallIcon" + simpleNotification.smallIcon);
simpleNotification.sortKey = notification.getSortKey();
simpleNotification.sound = notification.sound;
simpleNotification.subText = notification.extras.getString(Notification.EXTRA_SUB_TEXT);
simpleNotification.tickerText = notification.tickerText;
simpleNotification.usesChronometer = notification.extras.getBoolean(Notification.EXTRA_SHOW_CHRONOMETER);
simpleNotification.visibility = notification.visibility > 0 ? notification.visibility : null;
return simpleNotification;
}
@SuppressWarnings("deprecation")
@Override
public void onDownloadStateChanged(int newState) {
if (null != mClientProxy) {
mClientProxy.onDownloadStateChanged(newState);
}
if (newState != mState) {
mState = newState;
if (newState == IDownloaderClient.STATE_IDLE || null == mContentIntent) {
return;
}
int stringDownloadID;
int iconResource;
boolean ongoingEvent;
// get the new title string and paused text
switch (newState) {
case 0:
iconResource = android.R.drawable.stat_sys_warning;
stringDownloadID = R.string.state_unknown;
ongoingEvent = false;
break;
case IDownloaderClient.STATE_DOWNLOADING:
iconResource = android.R.drawable.stat_sys_download;
stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
ongoingEvent = true;
break;
case IDownloaderClient.STATE_FETCHING_URL:
case IDownloaderClient.STATE_CONNECTING:
iconResource = android.R.drawable.stat_sys_download_done;
stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
ongoingEvent = true;
break;
case IDownloaderClient.STATE_COMPLETED:
case IDownloaderClient.STATE_PAUSED_BY_REQUEST:
iconResource = android.R.drawable.stat_sys_download_done;
stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
ongoingEvent = false;
break;
case IDownloaderClient.STATE_FAILED:
case IDownloaderClient.STATE_FAILED_CANCELED:
case IDownloaderClient.STATE_FAILED_FETCHING_URL:
case IDownloaderClient.STATE_FAILED_SDCARD_FULL:
case IDownloaderClient.STATE_FAILED_UNLICENSED:
iconResource = android.R.drawable.stat_sys_warning;
stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
ongoingEvent = false;
break;
default:
iconResource = android.R.drawable.stat_sys_warning;
stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
ongoingEvent = true;
break;
}
mCurrentText = mContext.getString(stringDownloadID);
mCurrentTitle = mLabel.toString();
mCurrentNotification.tickerText = mLabel + ": " + mCurrentText;
mCurrentNotification.icon = iconResource;
mCurrentNotification.setLatestEventInfo(mContext, mCurrentTitle, mCurrentText,
mContentIntent);
if (ongoingEvent) {
mCurrentNotification.flags |= Notification.FLAG_ONGOING_EVENT;
} else {
mCurrentNotification.flags &= ~Notification.FLAG_ONGOING_EVENT;
mCurrentNotification.flags |= Notification.FLAG_AUTO_CANCEL;
}
mNotificationManager.notify(NOTIFICATION_ID, mCurrentNotification);
}
}
@Override
public void onDownloadStateChanged(int newState) {
if (null != mClientProxy) {
mClientProxy.onDownloadStateChanged(newState);
}
if (newState != mState) {
mState = newState;
if (newState == IDownloaderClient.STATE_IDLE || null == mContentIntent) {
return;
}
int stringDownloadID;
int iconResource;
boolean ongoingEvent;
// get the new title string and paused text
switch (newState) {
case 0:
iconResource = android.R.drawable.stat_sys_warning;
stringDownloadID = R.string.state_unknown;
ongoingEvent = false;
break;
case IDownloaderClient.STATE_DOWNLOADING:
iconResource = android.R.drawable.stat_sys_download;
stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
ongoingEvent = true;
break;
case IDownloaderClient.STATE_FETCHING_URL:
case IDownloaderClient.STATE_CONNECTING:
iconResource = android.R.drawable.stat_sys_download_done;
stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
ongoingEvent = true;
break;
case IDownloaderClient.STATE_COMPLETED:
case IDownloaderClient.STATE_PAUSED_BY_REQUEST:
iconResource = android.R.drawable.stat_sys_download_done;
stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
ongoingEvent = false;
break;
case IDownloaderClient.STATE_FAILED:
case IDownloaderClient.STATE_FAILED_CANCELED:
case IDownloaderClient.STATE_FAILED_FETCHING_URL:
case IDownloaderClient.STATE_FAILED_SDCARD_FULL:
case IDownloaderClient.STATE_FAILED_UNLICENSED:
iconResource = android.R.drawable.stat_sys_warning;
stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
ongoingEvent = false;
break;
default:
iconResource = android.R.drawable.stat_sys_warning;
stringDownloadID = Helpers.getDownloaderStringResourceIDFromState(newState);
ongoingEvent = true;
break;
}
mCurrentText = mContext.getString(stringDownloadID);
mCurrentTitle = mLabel.toString();
mCurrentNotification.tickerText = mLabel + ": " + mCurrentText;
mCurrentNotification.icon = iconResource;
mCurrentNotification.setLatestEventInfo(mContext, mCurrentTitle, mCurrentText,
mContentIntent);
if (ongoingEvent) {
mCurrentNotification.flags |= Notification.FLAG_ONGOING_EVENT;
} else {
mCurrentNotification.flags &= ~Notification.FLAG_ONGOING_EVENT;
mCurrentNotification.flags |= Notification.FLAG_AUTO_CANCEL;
}
mNotificationManager.notify(NOTIFICATION_ID, mCurrentNotification);
}
}
@Override
public void onCreate() {
super.onCreate();
Log.d(TAG, "service started");
sPausedVoluntarilz = false;
wasVoluntaryStart();
settings = PreferenceManager.getDefaultSharedPreferences(this);
PreferenceManager.setDefaultValues(this, R.xml.preferences, false);
IntentFilter filter = new IntentFilter();
filter.addAction(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);
filter.addAction(Intent.ACTION_NEW_OUTGOING_CALL);
filter.addAction(Intent.ACTION_MEDIA_REMOVED);
filter.addAction(Intent.ACTION_POWER_CONNECTED);
filter.addAction(Intent.ACTION_POWER_DISCONNECTED);
filter.addAction(Intent.ACTION_REBOOT);
filter.addAction(Intent.ACTION_SHUTDOWN);
filter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
filter.addAction(TelephonyManager.ACTION_PHONE_STATE_CHANGED);
filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
mTrustReceivers = new TrustReceivers();
registerReceiver(mTrustReceivers, filter);
IntentFilter filterPackage = new IntentFilter();
filterPackage.addAction(Intent.ACTION_PACKAGE_ADDED);
filterPackage.addAction(Intent.ACTION_PACKAGE_CHANGED);
filterPackage.addAction(Intent.ACTION_PACKAGE_DATA_CLEARED);
filterPackage.addAction(Intent.ACTION_PACKAGE_REMOVED);
filterPackage.addAction(Intent.ACTION_PACKAGE_REPLACED);
filterPackage.addAction(Intent.ACTION_PACKAGE_RESTARTED);
filterPackage.addDataScheme("package");
registerReceiver(mTrustReceivers, filterPackage);
sIsRunning = true;
mNotification = new Notification(R.drawable.ic_launcher, "Trust is good", System.currentTimeMillis());
Intent i = new Intent(this, TrustActivity.class);
i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
mPendingIntent = PendingIntent.getActivity(this, 0, i, 0);
mNotification.setLatestEventInfo(this, "Control is better", "Trust running", mPendingIntent);
mNotification.flags |= Notification.FLAG_NO_CLEAR;
mNotification.flags |= Notification.FLAG_FOREGROUND_SERVICE;
mNotification.flags |= Notification.FLAG_ONGOING_EVENT;
if (settings.getBoolean("general.notification", false))
startForeground(NOTIFICATION_ID, mNotification);
mAppWatcher = new AppWatcher(this);
mAppWatcher.startWatching();
}