如何使用remoteviews显示所有Android平台的通知中的进度条

时间:2013-04-15 06:48:35

标签: java android

我想在所有Android平台的通知中显示progressbar。我使用远程视图在android中显示progress bar。我已经在我的项目中添加了 android-support-v4 库。如果我替换

 mBuilder = new NotificationCompat.Builder(MainActivity.this);
 notification = mBuilder.build();

 notification = new Notification(R.drawable.notification, "simulating a upload", System            .currentTimeMillis());

然后显示通知,但不推荐使用方法。

以下是代码:

 class SendDatabaseToServer extends
        AsyncTask<ArrayList<LogFishMetadata>, Integer, String> {
    private NotificationCompat.Builder mBuilder;
    private NotificationManager mNotifyManager;
    private RemoteViews remoteViews;
    private Intent intent;
    private PendingIntent pendingIntent;
    private Notification notification;
    private int notificationId = 1;

    int start;
    int percentage;
    int  inc;
    public SendDatabaseToServer(int value) {
        // TODO Auto-generated constructor stub
        logout = value;
    }

    @Override
    protected void onPreExecute() {
        // TODO Auto-generated method stub
        super.onPreExecute();

        mNotifyManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        intent = new Intent(MainActivity.this, MainActivity.class);
        pendingIntent = PendingIntent.getActivity(MainActivity.this,
                notificationId, intent, 0);
        remoteViews = new RemoteViews(getPackageName(),
                R.layout.notification_downloader);
        mBuilder = new NotificationCompat.Builder(MainActivity.this);
        notification = mBuilder.build();
  //notification = new Notification(R.drawable.notification, "simulating a upload", System.currentTimeMillis());
        notification.contentIntent = pendingIntent;
        notification.flags = notification.flags
                | Notification.FLAG_ONGOING_EVENT;
        notification.contentView = remoteViews;
         notification.contentView.setTextViewText(R.id.timeStamp, DateTime.getStringFromDate(new Date()));
         notification.contentView.setTextViewText(R.id.progress,
                    "UPloading....");
        notification.contentView.setProgressBar(R.id.progressBar, 100, 0,
                false);
        mNotifyManager.notify(notificationId, notification);
    }

    @Override
    protected String doInBackground(ArrayList<LogFishMetadata>... params) {
        // TODO Auto-generated method stub
        int count = params[0].size();
         percentage=100/count;

        for (int i = 0; i < params[0].size(); i++) {
            System.out.println("........." + i);
            start=i*percentage;
            inc=i+1;
            try {
                database.updateServerdata(params[0].get(i));

                        for(int j=start;j<=inc*percentage;j++)
                        {
                        publishProgress(j);
                        }                           

            } catch (Exception e) {
                // TODO: handle exception

            }
        }

        return null;
    }

    @Override
    protected void onProgressUpdate(Integer... values) {
        // TODO Auto-generated method stub
        super.onProgressUpdate(values);
        // progressBar.setProgress(values[0]);
        System.out.println("values......." + values[0]);
        if(values[0]>=100)
        {
            values[0]=98;
        }
        notification.contentView.setProgressBar(R.id.progressBar, 100,
                values[0], false);
        mNotifyManager.notify(notificationId, notification);


    }

    @Override
    protected void onPostExecute(String result) {
        // TODO Auto-generated method stub
        super.onPostExecute(result);
        notification.contentView.setTextViewText(R.id.progress,
                "UPloading Complete");
        notification.contentView.setProgressBar(R.id.progressBar,100, 100,
                false);
        mNotifyManager.notify(notificationId, notification);
        if (logout == 2) {

            System.out.println(" send Aler     dialog....................................");
            logoutConfirmationDialog("Sync Complete; Do you still want to logout?");

        }
        System.out.println("complete");
    }

}

2 个答案:

答案 0 :(得分:1)

您应该将兼容性库添加到项目中。您可以使用Android Tools|Add support Library来执行此操作。然后,您将使用该库中的NotificationCompat,它具有Builder

答案 1 :(得分:0)

我在我的一个项目中使用了以下代码,希望这可以帮助您:

DownloadTask类:

    public class DownloadTask extends AsyncTask<String, Integer, Void> {
    private NotificationHelper mNotificationHelper;
    public static int notificationID = 1;

    SharedPreferences settings;
    SharedPreferences.Editor editor;
    Context context;
    String title;
    public static String downlaodPath;
    boolean download = false;

    public DownloadTask(Context context, String title) {
        this.context = context;
        this.title = title;
        mNotificationHelper = new NotificationHelper(context, title);
    }

    protected void onPreExecute() {
        notificationID++;
        mNotificationHelper.createNotification(notificationID);
    }

    @Override
    protected Void doInBackground(String... aurl) {

        try {

            URL url = new URL(aurl[0]);
            URLConnection conexion = url.openConnection();
            conexion.connect();
            downlaodPath = "mnt/sdcard/Demo/"+title + ".mp3"; 
            File file = new File("mnt/sdcard/Demo/");
            file.mkdirs();
            File outputfile = new File(file, title + ".mp3");
            FileOutputStream fileOutput = new FileOutputStream(outputfile);
            InputStream inputStream = conexion.getInputStream();
            int totalSize = conexion.getContentLength();
            int downloadedSize = 0;
            byte[] buffer = new byte[1024];
            int bufferLength = 0;  
            while ((bufferLength = inputStream.read(buffer)) != -1) {
                downloadedSize += bufferLength;
                onProgressUpdate((int) ((downloadedSize * 100) / totalSize));
                fileOutput.write(buffer, 0, bufferLength);
            }
            fileOutput.close();
        } catch (Exception e) {
            download = true;
            e.printStackTrace();

        }
        return null;

    }

    protected void onProgressUpdate(Integer... progress) {
        mNotificationHelper.progressUpdate(progress[0]);
    }

    protected void onPostExecute(Void result) {
        if (download) {
            Toast.makeText(context, "Could Not Connect to Server.", 5).show();
            mNotificationHelper.clearNotification();
        }
        else
            mNotificationHelper.completed();

    }
}

NotificationHelper Class:

public class NotificationHelper extends Activity {
    private Context mContext;
    private int NOTIFICATION_ID = 1;
    private Notification mNotification;
    private NotificationManager mNotificationManager;
    private PendingIntent mContentIntent;
    private CharSequence mContentTitle;
    private String title;
    CharSequence tickerText;
    int icon;

    public NotificationHelper(Context context, String title) {
        mContext = context;
        this.title = title;
    }

    public void createNotification(int newtask) {

        mNotificationManager = (NotificationManager) mContext
                .getSystemService(Context.NOTIFICATION_SERVICE);
        NOTIFICATION_ID = newtask;
        icon = android.R.drawable.stat_sys_download;
        tickerText = mContext.getString(R.string.download);
        long when = System.currentTimeMillis();
        mNotification = new Notification(icon, tickerText, when);
        mContentTitle = title;
        CharSequence contentText = "0% complete";
        Intent notificationIntent = new Intent();
        mContentIntent = PendingIntent.getActivity(mContext, 0,
                notificationIntent, 0);
        mNotification.setLatestEventInfo(mContext, mContentTitle, contentText,
                mContentIntent);
        mNotification.flags = Notification.FLAG_ONGOING_EVENT;
        mNotificationManager.notify(NOTIFICATION_ID, mNotification);
    }

    public void progressUpdate(int percentageComplete) {
        CharSequence contentText = percentageComplete + "% complete";
        mNotification.setLatestEventInfo(mContext, mContentTitle, contentText,
                mContentIntent);
        mNotificationManager.notify(NOTIFICATION_ID, mNotification);
    }

    public void completed() {

        mNotificationManager.cancel(NOTIFICATION_ID);
        Notification completeNotification = new Notification(icon, tickerText,
                System.currentTimeMillis());

        try {
            PackageManager packageManager = mContext.getPackageManager();
            Intent completeIntent = new Intent();


            PendingIntent cIntent = PendingIntent.getActivity(mContext, 0,
                    completeIntent, 0);
            completeNotification.setLatestEventInfo(mContext, title,
                    "Download Complete", cIntent);
            completeNotification.flags = Notification.FLAG_AUTO_CANCEL;
            mNotificationManager.notify(NOTIFICATION_ID, completeNotification);
        } catch (Exception e) {
            // TODO: handle exception
            e.printStackTrace();
        }

        Log.e("LOG", "last");

        TestFragment3.activity.sendBroadcast(new Intent(
                Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://"
                        + Environment.getExternalStorageDirectory())));
    }

    public void clearNotification() {
        mNotificationManager.cancel(NOTIFICATION_ID);
    }

}