使用execute调用时,AsyncTask未运行

时间:2015-06-09 01:44:44

标签: android android-asynctask android-service

我正在尝试运行每分钟更新本地数据的AsynTask。我已将日志记录语句放在AsyncTask的所有路径中,但它们都没有被调用过。我没有正确创建/运行异步任务吗?

这是调用该函数的接收器(我知道实际上正在接收该信号):

public class PredictionUpdateReceiver extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        // For our recurring task, we'll just display a message

        new UpdatePrediction(context).execute("");

    }

}

这是我的AsyncTask,它正在查询我的网络服务:

public class UpdatePrediction extends AsyncTask<String, String, String> {

    String user;
    int success;
    Context context;

    // JSON parser class
    JSONParser jsonParser = new JSONParser();

    // JSON Node names
    private static final String TAG_SUCCESS = "success";
    private static final String TAG_PREDICTION = "prediction";
    private static final String TAG_OCCUPANCY_PREDICTION = "occupancy_prediction";

    private static final String url_prediction = "http://localhost/android_connect/get_prediction.php";

    /**
     * Getting product details in background thread
     * */

    public UpdatePrediction(Context context) {
        this.context = context;
    }

    protected String doInBackground(String p) {

        SharedPreferences sharedPref = context.getSharedPreferences("user",
                Context.MODE_PRIVATE);
        user = sharedPref.getString("name", "codohert");
        Log.i("update", "started");

        try {

            // Building Parameters
            List<NameValuePair> params = new ArrayList<NameValuePair>();
            params.add(new BasicNameValuePair("pid", user));

            // getting product details by making HTTP request
            // Note that product details url will use GET request
            JSONObject json = jsonParser.makeHttpRequest(url_prediction, "GET",
                    params);

            // check your log for json response
            Log.d("Prediction Details", json.toString());

            // json success tag
            success = json.getInt(TAG_SUCCESS);
            if (success == 1) {
                Log.i("update", "success");
                // successfully received product details
                JSONArray predictionObj = json.getJSONArray(TAG_PREDICTION); // JSON
                                                                                // Array

                // get first product object from JSON Array
                JSONObject prediction = predictionObj.getJSONObject(0);

                String predict = prediction.getString(TAG_OCCUPANCY_PREDICTION);
                String shour = predict.substring(11, 12);
                String smin = predict.substring(14, 15);
                Integer hour = Integer.parseInt(shour);
                Integer minute = Integer.parseInt(smin);

                SetTime(hour, minute);
                return null;

            } else {
                Log.i("update", "failed");
                return null;
            }
        } catch (JSONException e) {
            Log.i("update", "catch");
            e.printStackTrace();
            return null;
        }
    }

    public void SetTime(int hourOfDay, int minute) {
        SharedPreferences sharedPref = context.getSharedPreferences(
                "prediction", Context.MODE_PRIVATE);
        SharedPreferences.Editor editorh = sharedPref.edit();
        editorh.putInt("prediction_hour", hourOfDay);
        editorh.commit();
        SharedPreferences.Editor editorm = sharedPref.edit();
        editorm.putInt("prediction_min", minute);
        editorm.commit();
        Toast.makeText(context, "Set Prediction", Toast.LENGTH_SHORT).show();

    }

    @Override
    protected String doInBackground(String... params) {
        // TODO Auto-generated method stub
        return null;
    }

}

这是主要活动设置并调用闹钟:

public class MainActivity extends AppCompatActivity implements
        TimePickerFragment.FragmentCallbacks {

    private PendingIntent pendingIntent;
    private AlarmManager manager;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        SharedPreferences sp = this.getSharedPreferences("user",
                Context.MODE_PRIVATE);
        SharedPreferences.Editor editor = sp.edit();
        editor.putString("name", "codohert");
        editor.commit();

        Log.i("main", "world");

        new UpdatePrediction(this).execute("");

        // Retrieve a PendingIntent that will perform a broadcast
        Intent alarmIntent = new Intent(this, PredictionUpdateReceiver.class);
        pendingIntent = PendingIntent.getBroadcast(this, 0, alarmIntent, 0);
        startAlarm();

        // Use the current time as the default values for the picker
        SharedPreferences sharedPref = this.getSharedPreferences("prediction",
                Context.MODE_PRIVATE);

        final Calendar c = Calendar.getInstance();
        int defaultHour = c.get(Calendar.HOUR_OF_DAY);
        int defaultMinute = c.get(Calendar.MINUTE);

        int hour = sharedPref.getInt("prediction_hour", defaultHour);
        int minute = sharedPref.getInt("prediction_min", defaultMinute);

        String timeString = Integer.toString(hour) + ":"
                + Integer.toString(minute);

        TextView predictionText = (TextView) findViewById(R.id.prediction_time);
        predictionText.setText(timeString);
    }

    public void showTimePickerDialog(View v) {
        DialogFragment newFragment = new TimePickerFragment();
        newFragment.show(getFragmentManager(), "timePicker");

    }

    public void showUserNameEdit(View c) {
        EditNameDialog newFragment = new EditNameDialog();
        newFragment.show(getSupportFragmentManager(), "editName");
    }

    @Override
    public void TimeUpdated(int hour, int minute) {
        Toast.makeText(this, "Hour: " + hour + " Minute: " + minute,
                Toast.LENGTH_SHORT).show();

        String timeString = Integer.toString(hour) + ":"
                + Integer.toString(minute);
        TextView predictionText = (TextView) findViewById(R.id.prediction_time);
        predictionText.setText(timeString);
    }

    public void startAlarm() {
        manager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
        int interval = 60000;

        manager.setRepeating(AlarmManager.RTC_WAKEUP,
                System.currentTimeMillis(), interval, pendingIntent);
        Toast.makeText(this, "Alarm Set", Toast.LENGTH_SHORT).show();
    }
}

2 个答案:

答案 0 :(得分:1)

您正在重写AsyncTask,因此您需要实现此方法:

@Override 
protected String doInBackground(String... params) {
    // TODO Auto-generated method stub 
    return null; 
}

而不是这一个:

protected String doInBackground(String p) {
    ...
}

请参阅AsyncTask documentation

答案 1 :(得分:0)

在内部编写protected String doInBackground(String p)的代码 @Override protected String doInBackground(String... params) { // TODO Auto-generated method stub return null; }