开发者

Android: Running thread preventing animation from starting

I currently have an Android activity which manages some locally-stored RSS feeds. In this activity, these feeds are updated in their own thread via a private class. I'm also trying to include an "updating" icon that rotates with a RotateAnimation while this thread is running.

The animation works by itself, but doesn't work while the thread is running despite the log entries stating the code is being executed. I suspect this is due to the thread not being entirely safe, and taking up most of the CPU time. However I'd just like to know if there's a better way of achieving this.

The function updateAllFeeds() is called from a button press. Here's the relevant code:

/**
 * Gets the animation properties for the rotation
 */
protected RotateAnimation getRotateAnimation() {
    // Now animate it
    Log.d("RSS Alarm", "Performing animation");
    RotateAnimation anim = new RotateAnimation(359f, 0f, 16f, 21f);
    anim.setInterpolator(new LinearInterpolator());
    anim.setRepeatCount(Animation.INFINITE);
    anim.setDuration(700);
    return anim;
}

/**
 * Animates the refresh icon with a rotate
 */
public void setUpdating() {
    btnRefreshAll.startAni开发者_运维知识库mation(getRotateAnimation());
}

/**
 * Reverts the refresh icon back to a still image
 */
public void stopUpdating() {
    Log.d("RSS Alarm", "Stopping animation");
    btnRefreshAll.setAnimation(null);
    refreshList();
}

/**
 * Updates all RSS feeds in the list
 */
protected void updateAllFeeds() {
    setUpdating();
    Updater updater = new Updater(channels);
    updater.run();

}

/**
 * Class to update RSS feeds in a new thread
 * @author Michael
 *
 */
private class Updater implements Runnable {

    // Mode flags
    public static final int MODE_ONE = 0;
    public static final int MODE_ALL = 1;

    // Class vars
    Channel channel;
    ArrayList<Channel> channelList;
    int mode;

    /**
     * Constructor for singular update
     * @param channel
     */
    public Updater(Channel channel) {
        this.mode = MODE_ONE;
        this.channel = channel;
    }

    /**
     * Constructor for updating multiple feeds at once
     * @param channelList The list of channels to be updated
     */
    public Updater(ArrayList<Channel> channelList) {
        this.mode = MODE_ALL;
        this.channelList = channelList;
    }

    /**
     * Performs all the good stuff
     */
    public void run() {
        // Flag for writing problems
        boolean write_error = false;

        // Check if we have a singular or list
        if(this.mode == MODE_ONE) {
            // Updating one feed only
            int updateStatus = channel.update(getApplicationContext());

            // Check for error
            if(updateStatus == 2) {
                // Error - show dialog
                write_error = true;
            }
        }
        else {
            // Iterate through all feeds
            for(int i = 0; i < this.channelList.size(); i++) {
                // Update this item
                int updateStatus = channelList.get(i).update(getApplicationContext());                
                 if(updateStatus == 2) {
                     // Error - show dialog
                     write_error = true;
                 }
            }
        }

        // If we have an error, show the dialog
        if(write_error) {
            runOnUiThread(new Runnable(){
                public void run() {  
                    showDialog(ERR_SD_READ_ONLY);
                }
             });
        }

        // End updater
        stopUpdating();
    }   // End run()
}   // End class Updater

(I know the updateStatus == 2 bit is bad practice, that's one of the next things I plan to tidy up).

Any help is greatly appreciated, many thanks in advance.


Run the updater runnable in a separate thread. Do the following changes.

protected void updateAllFeeds() {
    setUpdating();
    new Thread( new Updater(channels)).start();
}

Call stopUpdating() in runOnUiThread block.

private class Updater implements Runnable {
    .........
    .........    
    .........
    public void run() {
        .........
        .........

        // End updater
        runOnUiThread(new Runnable(){
                public void run() {  
                     stopUpdating();
                }
             });

    }   // End run()
}   // End class Updater


Move anything that affects the UI off into its own Runnable and then post it with your button

btnRefreshAll.post(new StopUpdating());


I managed to get this working last night using Android's AsyncTask class. It was surprisingly easy to implement, though the downside was I had to write one class for updating an individual feed, and another for updating all feeds. Here's the code for updating all feeds at once:

private class MassUpdater extends AsyncTask<ArrayList<Channel>, Void, Void> {

    @Override
    protected Void doInBackground(ArrayList<Channel>... channels) {
        ArrayList<Channel> channelList = channels[0];

        // Flag for writing problems
        boolean write_error = false;

            // Iterate through all feeds
            for(int i = 0; i < channelList.size(); i++) {
                // Update this item
                int updateStatus = channelList.get(i).update(getApplicationContext());                
                 if(updateStatus == FileHandler.STATUS_WRITE_ERROR) {
                     // Error - show dialog
                     write_error = true;
                 }
            }


        // If we have an error, show the dialog
        if(write_error) {
            runOnUiThread(new Runnable(){
                public void run() {  
                    showDialog(ERR_SD_READ_ONLY);
                }
             });
        }
        return null;
    }

    protected void onPreExecute() {
        btnRefreshAll.setAnimation(getRotateAnimation());
        btnRefreshAll.invalidate();
        btnRefreshAll.getAnimation().startNow();
    }

    protected void onPostExecute(Void hello) {
        btnRefreshAll.setAnimation(null);
        refreshList();
    }
}

Thanks for your answers guys. userSeven7s' reply also makes a lot of sense so I may use that as a backup should I run into any problems with AsyncTask.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜