为什么runnable会在我的小部件中停止?

时间:2015-09-11 17:14:54

标签: java android widget runnable traffic

我有以下代码在TextView上以MB为单位更新总数据流量。首先,当您在屏幕上加载小部件时,然后停止。 我用Log.d检查了Runnable,它停止运行。为什么?。 你能救我吗?

public class TdWidget extends AppWidgetProvider {

private static long mStartRX = 0;
private static Handler mHandler = new Handler();
RemoteViews remoteViews;
AppWidgetManager appWidgetManager;
ComponentName thisWidget;

public void init(Context context,AppWidgetManager appWidgetManager)
{
    mStartRX = TrafficStats.getTotalRxBytes();
    remoteViews = new RemoteViews(context.getPackageName(), R.layout.main);
    this.appWidgetManager = appWidgetManager;
    thisWidget = new ComponentName(context, TdWidget.class);

    mHandler.postDelayed(mRunnable, 1000);
}

@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds) {        
    init(context, appWidgetManager);       
}

private final Runnable mRunnable = new Runnable() {
    public void run() {

        Log.d("Runnable","*********RUNNABLE*******");
        float dwBytes = TrafficStats.getTotalRxBytes()- mStartRX;
        float dwBytesf = dwBytes/1048576;           

        remoteViews.setTextViewText(R.id.txtshow, "MB Dwn= " + String.format("%.2f", dwBytesf));
        appWidgetManager.updateAppWidget(thisWidget, remoteViews);

        mHandler.postDelayed(mRunnable, 1000);
    }
};

}

1 个答案:

答案 0 :(得分:0)

你可以尝试一下..如果我清楚地听了你的问题。

private final Runnable mRunnable = new Runnable() {
    public void run() {

        Log.d("Runnable","*********RUNNABLE*******");
        another();
    }
    private void another(){
        float dwBytes = TrafficStats.getTotalRxBytes()- mStartRX;
        float dwBytesf = dwBytes/1048576;           
        remoteViews.setTextViewText(R.id.txtshow, "MB Dwn= " + String.format("%.2f", dwBytesf));
        appWidgetManager.updateAppWidget(thisWidget, remoteViews);

        try{ Thread.sleep(1000); }catch(Exception ex){  Log.e("Exception"," : "+ex.getMessage())  }

        another();

    }

};