在后台调用方法每隔几分钟检索一次数据

时间:2016-04-24 20:03:35

标签: android service broadcastreceiver

我正在开发一个Android应用程序,通过数据库中的php,mysql,json检索数据。我需要每10分钟创建一个服务或任何方式来调用 getData() 方法。我尝试将这两种方法放在广播接收器中,并使用报警管理器每10分钟重复一次,但它没有正常运行,只适用于 Toast 和< strong> Log.d (简单操作)。有没有一种简单的方法来实现我想要的?我做了很多搜索,但无法找到明确的答案

 //METHOD 1
 private void getData() {

    loading = ProgressDialog.show(this,"Please wait...","Fetching...",false,false);

    String url = Config.DATA_URL;

    StringRequest stringRequest = new StringRequest(url, new Response.Listener<String>() {
        @Override
        public void onResponse(String response) {
            loading.dismiss();
            showJSON(response);

        }
    },
            new Response.ErrorListener() {
                @Override
                public void onErrorResponse(VolleyError error) {
                    Toast.makeText(MainActivity.this,error.getMessage().toString(),Toast.LENGTH_LONG).show();
                }
            });

    RequestQueue requestQueue = Volley.newRequestQueue(this);
    requestQueue.add(stringRequest);
}




 // METHOD 2
private void showJSON(String response){

    String id="";
    String time="";
    String value = "";
    try {

        JSONObject jsonObject = new JSONObject(response);
        JSONArray result = jsonObject.getJSONArray(Config.JSON_ARRAY);

        for (int i = 0; i < result.length(); i++) {
            JSONObject tempData = result.getJSONObject(i);
            id = tempData.getString(Config.KEY_NAME);
            time = tempData.getString(Config.KEY_ADDRESS);
            value = tempData.getString(Config.KEY_VC);
            String data = "Id:\t"+id+", Time:\t" +time+ ", Value:\t"+ value;
            all += data+"\n";
        }



    }

    catch (JSONException e) {
        e.printStackTrace();
    }
    textViewResult.setText(all);

}

2 个答案:

答案 0 :(得分:1)

您使用广播接收器(BR)和闹钟管理器的方式听起来是一种很好的方法,我不确定您遇到了什么问题。你能告诉我们更多吗?

如果没有所有细节我会说潜在的问题是广播接收器通常在Android的UI线程中执行,并且例如不允许您执行网络访问,它必须在X秒内完成。 / p>

1)您没有正确的权限访问互联网?从我记得的这个日志可以很容易错过。 2)您可以请求BR运行后台线程,我知道您可以执行此操作,而不是自己尝试。 3)你可以开始另一个线程。如您所见,为了更新UI,您应该使用异步任务。因此,您可以在后台线程中执行网络,然后在UI线程中使用新数据进行调用。 (这可能是选择)

旁注:为了解析json,我建议你看看Gson。它是谷歌的一个库,使得Json的分析更加简单。 https://github.com/google/gson

答案 1 :(得分:0)

<div className={this.state.checked ? : 'mapping-check' : ''}></div>

}

import com.google.android.gms.gcm.GcmTaskService;
import com.google.android.gms.gcm.TaskParams;

import android.content.Context;
import android.content.SharedPreferences;
import android.location.Address;
import android.location.Geocoder;
import android.net.ConnectivityManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.widget.Toast;

import com.google.android.gms.gcm.GcmNetworkManager;

import com.google.android.gms.gcm.OneoffTask;
import com.google.android.gms.gcm.PeriodicTask;
import com.google.android.gms.gcm.Task;
import com.rcsplcms.ess.Constant;
import com.rcsplcms.ess.GPSTracker;
import com.rcsplcms.ess.R;
import com.rcsplcms.ess.application.ESSApplication;
import com.rcsplcms.ess.util.AppLog;

import org.ksoap2.SoapEnvelope;
import org.ksoap2.serialization.SoapObject;
import org.ksoap2.serialization.SoapPrimitive;
import org.ksoap2.serialization.SoapSerializationEnvelope;
import org.ksoap2.transport.HttpTransportSE;

import java.util.List;
import java.util.Locale;


/**
* Created by MAYURKUMAR TERAIYA on 20-09-2017.
*/

public class GCMServiceTracking extends GcmTaskService {


private static final String TAG = GCMServiceTracking.class.getSimpleName();

public static final String GCM_ONEOFF_TAG = "oneoff|[0,0]";
public static final String GCM_REPEAT_TAG = "repeat|[7200,1800]";

@Override
public void onInitializeTasks() {
    //called when app is updated to a new version, reinstalled etc.
    //you have to schedule your repeating tasks again
    super.onInitializeTasks();
}

@Override
public int onRunTask(TaskParams taskParams) {
    //do some stuff (mostly network) - executed in background thread (async)

    //Toast.makeText(getApplicationContext(), "Service Executed", 
    Toast.LENGTH_SHORT).show();

    //obtain your data
    Bundle extras = taskParams.getExtras();

    Handler h = new Handler(getMainLooper());
    Log.v(TAG, "onRunTask");


    if (taskParams.getTag().equals(GCM_ONEOFF_TAG)) {
        h.post(new Runnable() {
            @Override
            public void run() {
                //Toast.makeText(GCMServiceTracking.this, "ONEOFF executed", 
        Toast.LENGTH_SHORT).show();
            }
        });
    } else if (taskParams.getTag().equals(GCM_REPEAT_TAG)) {
        h.post(new Runnable() {
            @Override
            public void run() {
                //Toast.makeText(GCMServiceTracking.this, "REPEATING executed", Toast.LENGTH_SHORT).show();

                gpsTracker = new GPSTracker(GCMServiceTracking.this);

                Toast.makeText(getApplicationContext(), "Data Syncing.", Toast.LENGTH_SHORT).show();


            }
        });
    }
    return GcmNetworkManager.RESULT_SUCCESS;
}



public static void scheduleOneOff(Context context) {
    //in this method, single OneOff task is scheduled (the target service 
   that will be called is MyTaskService.class)
    Bundle data = new Bundle();
    data.putString("some key", "some budle data");
    try {
        OneoffTask oneoff = new OneoffTask.Builder()
                //specify target service - must extend GcmTaskService
                .setService(GCMServiceTracking.class)
                //tag that is unique to this task (can be used to cancel task)
                .setTag(GCM_ONEOFF_TAG)
                //executed between 0 - 10s from now
                .setExecutionWindow(10, 10)
                //set required network state, this line is optional
                .setRequiredNetwork(Task.NETWORK_STATE_ANY)
                //request that charging must be connected, this line is optional
                .setRequiresCharging(false)
                //set some data we want to pass to our task
                .setExtras(data)
                //if another task with same tag is already scheduled, replace it with this task
                .setUpdateCurrent(true)
                .build();
        GcmNetworkManager.getInstance(context).schedule(oneoff);
        Log.v(TAG, "oneoff task scheduled");
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static void scheduleRepeat(Context context) {
    //in this method, single Repeating task is scheduled (the target service that will be called is MyTaskService.class)
    try {
        PeriodicTask periodic = new PeriodicTask.Builder()
                //specify target service - must extend GcmTaskService
                .setService(GCMServiceTracking.class)
                //repeat every 60 seconds
                .setPeriod(300)
                //specify how much earlier the task can be executed (in seconds)
                .setFlex(30)
                //tag that is unique to this task (can be used to cancel task)
                .setTag(GCM_REPEAT_TAG)
                //whether the task persists after device reboot
                .setPersisted(true)
                //if another task with same tag is already scheduled, replace it with this task
                .setUpdateCurrent(true)
                //set required network state, this line is optional
                .setRequiredNetwork(Task.NETWORK_STATE_ANY)
                //request that charging must be connected, this line is optional
                .setRequiresCharging(false)
                .build();
        GcmNetworkManager.getInstance(context).schedule(periodic);
        Log.v(TAG, "repeating task scheduled");
    } catch (Exception e) {
        Log.e(TAG, "scheduling failed");
        e.printStackTrace();
    }
}

public static void cancelOneOff(Context context) {
    GcmNetworkManager
            .getInstance(context)
            .cancelTask(GCM_ONEOFF_TAG, GCMServiceTracking.class);
}

public static void cancelRepeat(Context context) {
    GcmNetworkManager
            .getInstance(context)
            .cancelTask(GCM_REPEAT_TAG, GCMServiceTracking.class);
}

public static void cancelAll(Context context) {
    GcmNetworkManager
            .getInstance(context)
            .cancelAllTasks(GCMServiceTracking.class);
}