运行Countdowntimer时执行doInBackground()时发生错误

时间:2016-04-29 21:05:41

标签: java android android-asynctask countdowntimer

我试图在后台运行一个倒数计时器来通过asynctask进行一些计算,但是我收到了这个错误

这是我的代码

public class CurrentStatus extends AsyncTask<Context,Void,Context> {

float BatteryStatus;
int TimeStatus,HoursToCharge;
String USID, BatteryID, NetworkID, NetworkStatus, roamingLevel,
     TimeID,ETTC,DischargeRate;
int dischargeRate;
Context newContext;
SharedPreferences sharedPreferences;





public float getBatteryLevel(Context context)
{
    Intent batteryIntent = context.registerReceiver(null, new     
IntentFilter(Intent.ACTION_BATTERY_CHANGED));
int level = batteryIntent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
int scale = batteryIntent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
   return ((float) level / (float) scale) * 100.0f;

}

public void getDischargeRate(final Context context)
{
final int currentBattery=(int)getBatteryLevel(context);
int q=0;
 sharedPreferences=context.getSharedPreferences
  ("MyDischargePref" ,Context.MODE_PRIVATE);

final SharedPreferences.Editor editor1=sharedPreferences.edit();
new CountDownTimer(120000,600)
{
    int BatteryDischargeRate;
    public void onTick(long millisUntilFinished)
    {
        System.out.println(" seconds"+currentBattery);
    }
    int afterUsage;
    public void onFinish()
    {
        afterUsage = (int)getBatteryLevel(context);
        System.out.println("On Finish: "+ afterUsage);
        BatteryDischargeRate=currentBattery-afterUsage;
        System.out.println("Entering preference. BYE!    
       "+BatteryDischargeRate);



 editor1.putString("DischargeRate",Integer.toString(BatteryDischargeRate));

        }
}.start();

}


public String getNetworkInterface(Context context) {

WifiManager wifi = (WifiManager)     context.getSystemService(Context.WIFI_SERVICE);
if (wifi.isWifiEnabled())
    return "On";
else
    return "Off";

}

public String getRoaming(Context context) {
boolean x = false;
TelephonyManager telephoneManager;
telephoneManager = (TelephonyManager)    
context.getSystemService(Context.TELEPHONY_SERVICE);
x = telephoneManager.isNetworkRoaming();
if (x)
    return "On";
else
    return "Off";
}

public String getDataConnectionType(Context context) {
TelephonyManager telephoneManager;
telephoneManager = (TelephonyManager)
 context.getSystemService(Context.TELEPHONY_SERVICE);
int a = telephoneManager.getNetworkType();

switch (a) {
    case TelephonyManager.NETWORK_TYPE_1xRTT:
    case TelephonyManager.NETWORK_TYPE_CDMA:
    case TelephonyManager.NETWORK_TYPE_GPRS:
    case TelephonyManager.NETWORK_TYPE_IDEN:
    case TelephonyManager.NETWORK_TYPE_EDGE:
        String nw = "00";
        return "2G";
    case TelephonyManager.NETWORK_TYPE_UMTS:
    case TelephonyManager.NETWORK_TYPE_EVDO_0:
    case TelephonyManager.NETWORK_TYPE_EVDO_A:
    case TelephonyManager.NETWORK_TYPE_HSDPA:
    case TelephonyManager.NETWORK_TYPE_HSUPA:
    case TelephonyManager.NETWORK_TYPE_HSPA:
    case TelephonyManager.NETWORK_TYPE_EVDO_B:
    case TelephonyManager.NETWORK_TYPE_EHRPD:
    case TelephonyManager.NETWORK_TYPE_HSPAP:
        nw = "01";
        return "3G";
    case TelephonyManager.NETWORK_TYPE_LTE:
        nw = "11";
        return "4G";
    default:
        return "Unknown";
}
}

public String getDataMode(Context context) {
ConnectivityManager cm = (ConnectivityManager)  
context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean x = activeNetwork != null &&
 activeNetwork.isConnectedOrConnecting();
if (x) {
    if (activeNetwork.getType() == ConnectivityManager.TYPE_MOBILE)
        return "On";
    else
        return "Off";
} else
    return "No Active Network";
}



public void retrieveStatus(Context context) {

Context retrieveContext=context;
SharedPreferences sharedPreferences=retrieveContext.getSharedPreferences("MyPref", Context.MODE_PRIVATE);


BatteryStatus = getBatteryLevel(retrieveContext);
if (BatteryStatus > 5 && BatteryStatus < 25) {
    BatteryID = "11";
}
if (BatteryStatus > 25 && BatteryStatus < 50) {
    BatteryID = "10";
}
if (BatteryStatus > 50 && BatteryStatus < 75) {
    BatteryID = "01";
}
if (BatteryStatus > 75 && BatteryStatus < 100) {
    BatteryID = "00";
}

NetworkID = getNetworkInterface(retrieveContext);
if (NetworkID == "ON") {
    NetworkID = getDataConnectionType(retrieveContext);
    if (NetworkStatus == "3G") {
        NetworkStatus = "11";
    }
    if (NetworkStatus == "2G") {
        NetworkStatus = "10";
    }
} else {
    NetworkStatus = "00";
}
NetworkID = getNetworkInterface(retrieveContext);
if (NetworkID == "On") {
    NetworkStatus = "01";
}

roamingLevel = getRoaming(retrieveContext);
if (roamingLevel.equals("On")) {
    roamingLevel = "1";
} else {
    roamingLevel = "0";
}
ETTC=(sharedPreferences.getString("ETTC",""));

HoursToCharge=Integer.parseInt(ETTC);
if (HoursToCharge > 12) {
    TimeID = "11";
}
if (HoursToCharge > 6 && HoursToCharge < 12) {
    TimeID = "10";
}
if (HoursToCharge > 3 && HoursToCharge < 6) {
    TimeID = "01";
}
if (HoursToCharge > 0 && HoursToCharge < 3) {
    TimeID = "00";
}

DischargeRate=(sharedPreferences.getString("MyDischargePref",""));
    System.out.println("Battery id:"+BatteryID);
System.out.println("ETTC:"+TimeID);
System.out.println("Network Status:"+NetworkStatus);
System.out.println("DischargeRate"+DischargeRate);
System.out.println("Roaming"+roamingLevel);

}

@Override
protected Context doInBackground(Context... params) {
Context backgroundcontext;

backgroundcontext=params[0];
getDischargeRate(backgroundcontext);
return backgroundcontext;
 }


@Override
protected void onPostExecute(Context context) {

 retrieveStatus(context);

}

}

这是LogCat

04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime:     FATAL EXCEPTION: AsyncTask #1
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime:    Process: com.first.shash_000.anantha, PID: 30111
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime: java.lang.RuntimeException: An error occured while executing doInBackground()
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime:     at android.os.AsyncTask$3.done(AsyncTask.java:304)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime:     at java.util.concurrent.FutureTask.finishCompletion(FutureTask.java:355)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime:      at java.util.concurrent.FutureTask.setException(FutureTask.java:222)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime:     at java.util.concurrent.FutureTask.run(FutureTask.java:242)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime:     at android.os.AsyncTask$SerialExecutor$1.run(AsyncTask.java:231)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1112)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime:     at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:587)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime:     at java.lang.Thread.run(Thread.java:818)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime:  Caused by: java.lang.RuntimeException: Can't create handler inside thread that has not called Looper.prepare()
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime:     at android.os.Handler.<init>(Handler.java:200)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime:     at android.os.Handler.<init>(Handler.java:114)
04-30 02:32:21.697 30111-30974/com.first.shash_000.anantha E/AndroidRuntime:     at android.os.CountDownTimer$1.<init>(CountDownTimer.java:114)

04-30 02:32:21.697 30111-30974 / com.first.shash_000.anantha E / AndroidRuntime:at android.os.CountDownTimer。(CountDownTimer.java:114)     04-30 02:32:21.697 30111-30974 / com.first.shash_000.anantha E / AndroidRuntime:at com.first.shash_000.anantha.CurrentStatus $ 1.(CurrentStatus.java:55)     04-30 02:32:21.697 30111-30974 / com.first.shash_000.anantha E / AndroidRuntime:at com.first.shash_000.anantha.CurrentStatus.getDischargeRate(CurrentStatus.java:54)     04-30 02:32:21.697 30111-30974 / com.first.shash_000.anantha E / AndroidRuntime:at com.first.shash_000.anantha.CurrentStatus.doInBackground(CurrentStatus.java:226)     04-30 02:32:21.697 30111-30974 / com.first.shash_000.anantha E / AndroidRuntime:at com.first.shash_000.anantha.CurrentStatus.doInBackground(CurrentStatus.java:26)     04-30 02:32:21.697 30111-30974 / com.first.shash_000.anantha E / AndroidRuntime:at android.os.AsyncTask $ 2.call(AsyncTask.java:292)

1 个答案:

答案 0 :(得分:0)

你不应该把你的CountDownTimer放在doInBackground()中,考虑改变你的代码逻辑来在主线程上运行定时器,例如onPostExecute(Context context)