Intent resultIntent = new Intent(this, ResultActivity.class);...// Because clicking the notification opens a new ("special") activity, there's// no need to create an artificial back stack.PendingIntent resultPendingIntent = PendingIntent.getActivity( this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);
NotificationCompat.Builder mBuilder;...// Sets an ID for the notificationint mNotificationId = 001;// Gets an instance of the NotificationManager serviceNotificationManager mNotifyMgr = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);// Builds the notification and issues it.mNotifyMgr.notify(mNotificationId, mBuilder.build());
int id = 1;...Intent resultIntent = new Intent(this, ResultActivity.class);TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);// Adds the back stackstackBuilder.addParentStack(ResultActivity.class);// Adds the Intent to the top of the stackstackBuilder.addNextIntent(resultIntent);// Gets a PendingIntent containing the entire back stackPendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);...NotificationCompat.Builder builder = new NotificationCompat.Builder(this);builder.setContentIntent(resultPendingIntent);NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);mNotificationManager.notify(id, builder.build());
// Instantiate a Builder object.NotificationCompat.Builder builder = new NotificationCompat.Builder(this);// Creates an Intent for the ActivityIntent notifyIntent = new Intent(new ComponentName(this, ResultActivity.class));// Sets the Activity to start in a new, empty tasknotifyIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);// Creates the PendingIntentPendingIntent notifyIntent = PendingIntent.getActivity( this, 0, notifyIntent, PendingIntent.FLAG_UPDATE_CURRENT);// Puts the PendingIntent into the notification builderbuilder.setContentIntent(notifyIntent);// Notifications are issued by sending them to the// NotificationManager system service.NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);// Builds an anonymous Notification object from the builder, and// passes it to the NotificationManagermNotificationManager.notify(id, builder.build());
mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);// Sets an ID for the notification, so it can be updatedint notifyID = 1;mNotifyBuilder = new NotificationCompat.Builder(this) .setContentTitle("New Message") .setContentText("You've received new messages.") .setSmallIcon(R.drawable.ic_notify_status)numMessages = 0;// Start of a loop that processes data and then notifies the user... mNotifyBuilder.setContentText(currentText) .setNumber(++numMessages); // Because the ID remains unchanged, the existing notification is // updated. mNotificationManager.notify( notifyID, mNotifyBuilder.build());...
Intent resultIntent = new Intent(this, ResultActivity.class);resultIntent.putExtra(CommonConstants.EXTRA_MESSAGE, msg);resultIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);// Because clicking the notification launches a new ("special") activity, // there's no need to create an artificial back stack.PendingIntent resultPendingIntent = PendingIntent.getActivity( this, 0, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);// This sets the pending intent that should be fired when the user clicks the// notification. Clicking the notification launches a new activity.builder.setContentIntent(resultPendingIntent);
构造一个Big View
下面的代码展示如何在big view中显示Button:
// Sets up the Snooze and Dismiss action buttons that will appear in the// big view of the notification.Intent dismissIntent = new Intent(this, PingService.class);dismissIntent.setAction(CommonConstants.ACTION_DISMISS);PendingIntent piDismiss = PendingIntent.getService(this, 0, dismissIntent, 0);Intent snoozeIntent = new Intent(this, PingService.class);snoozeIntent.setAction(CommonConstants.ACTION_SNOOZE);PendingIntent piSnooze = PendingIntent.getService(this, 0, snoozeIntent, 0);
// Constructs the Builder object.NotificationCompat.Builder builder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.ic_stat_notification) .setContentTitle(getString(R.string.notification)) .setContentText(getString(R.string.ping)) .setDefaults(Notification.DEFAULT_ALL) // requires VIBRATE permission /* * Sets the big view "big text" style and supplies the * text (the user's reminder message) that will be displayed * in the detail area of the expanded notification. * These calls are ignored by the support library for * pre-4.1 devices. */.setStyle(new NotificationCompat.BigTextStyle() .bigText(msg)) .addAction (R.drawable.ic_stat_dismiss, getString(R.string.dismiss), piDismiss) .addAction (R.drawable.ic_stat_snooze, getString(R.string.snooze), piSnooze);
通过添加setProgress(max, progress, false),然后发布Notification则可以在Notification中增加一个进度条,第三个参数指的就是任务长度是否确定(indeterminate (true) or determinate (false))。 当progress慢慢增长到max时,可以继续显示Notification也可以清除掉。不管怎样,可以通过setProgress(0, 0, false)清掉进度条:
int id = 1;...mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);mBuilder = new NotificationCompat.Builder(this);mBuilder.setContentTitle("Picture Download") .setContentText("Download in progress") .setSmallIcon(R.drawable.ic_notification);// Start a lengthy operation in a background threadnew Thread( new Runnable() { @Overridepublicvoidrun() { int incr; // Do the "lengthy" operation 20 timesfor (incr = 0; incr <= 100; incr+=5) { // Sets the progress indicator to a max value, the// current completion percentage, and "determinate"// state mBuilder.setProgress(100, incr, false); // Displays the progress bar for the first time. mNotifyManager.notify(id, mBuilder.build()); // Sleeps the thread, simulating an operation// that takes timetry { // Sleep for 5 seconds Thread.sleep(5*1000); } catch (InterruptedException e) { Log.d(TAG, "sleep failure"); } } // When the loop is finished, updates the notification mBuilder.setContentText("Download complete") // Removes the progress bar .setProgress(0,0,false); mNotifyManager.notify(id, mBuilder.build()); } }// Starts the thread by calling the run() method in its Runnable).start();
图:任务完成,清掉进度条
显示一个持续的活动指示器
要显示一个不确定(持续)的进度条,可以设置setProgress(0, 0, true)。
// Sets the progress indicator to a max value, the current completion// percentage, and "determinate" statemBuilder.setProgress(100, incr, false);// Issues the notificationmNotifyManager.notify(id, mBuilder.build());
将上面的代码替换成下面的
// Sets an activity indicator for an operation of indeterminate lengthmBuilder.setProgress(0, 0, true);// Issues the notificationmNotifyManager.notify(id, mBuilder.build());
/* * Sets up a SwipeRefreshLayout.OnRefreshListener that is invoked when the user * performs a swipe-to-refresh gesture. */mySwipeRefreshLayout.setOnRefreshListener( new SwipeRefreshLayout.OnRefreshListener() { @OverridepublicvoidonRefresh() { Log.i(LOG_TAG, "onRefresh called from SwipeRefreshLayout"); // This method performs the actual data-refresh operation.// The method calls setRefreshing(false) when it's finished. myUpdateOperation(); } });
/* * Listen for option item selections so that we receive a notification * when the user requests a refresh by selecting the refresh action bar item. */@OverridepublicbooleanonOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { // Check if user triggered a refresh:case R.id.menu_refresh: Log.i(LOG_TAG, "Refresh menu item selected"); // Signal SwipeRefreshLayout to start the progress indicator mySwipeRefreshLayout.setRefreshing(true); // Start the refresh background task.// This method calls setRefreshing(false) when it's finished. myUpdateOperation(); returntrue; } // User didn't trigger a refresh, let the superclass handle this actionreturnsuper.onOptionsItemSelected(item);}
Android不使用交换分区,但保存那些不在前台(不可见)的进程到最近最少使用(least-recent used LRU)的cache中。这样,在一个App离开后,不会退出,再次启动时,可以快速的切换到这个app。 LRU中的进程cache会影响系统的整体性能,所以在系统监测到剩余内存很低时,会将LRU中的进程进行杀死,但也会考虑那些特别占用内存的进程。
Profiling with Traceview and dmtracedump Analyzing UI Performance with Systrace
保持App的响应避免ANR
参考地址:http://developer.android.com/training/articles/perf-anr.html ANR是Application Not Responding的简称,意思是应用程序无响应。在Android系统中,UI操作超过5秒,BroadcastReceiver中操作超过10秒,都会导致ANR,系统会弹出ANR的对话框,app会崩溃。
privateclassDownloadFilesTaskextendsAsyncTask<URL, Integer, Long> {// Do the long-running work in hereprotected Long doInBackground(URL... urls) { intcount = urls.length; long totalSize = 0; for (int i = 0; i < count; i++) { totalSize += Downloader.downloadFile(urls[i]); publishProgress((int) ((i / (float) count) * 100)); // Escape early if cancel() is calledif (isCancelled()) break; } return totalSize; } // This is called each time you call publishProgress()protectedvoid onProgressUpdate(Integer... progress) { setProgressPercent(progress[0]); } // This is called when doInBackground() is finishedprotectedvoid onPostExecute(Long result) { showNotification("Downloaded " + result + " bytes"); }}//这样执行new DownloadFilesTask().execute(url1, url2, url3);