2016-04-24 83 views
0

我正在開發一個android應用程序,通過php,mysql,json從數據庫中檢索數據。我需要創建一個服務或任何方法來調用的getData()方法每次10分鐘。我試圖把這2種方法在廣播接收器和用於報警經理每10分鐘重複,但它並不能正常運行,它的工作只爲吐司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); 

} 

回答

1

你使用的廣播接收器(BR)和警報管理方式聽起來是個好辦法,我不知道到底是什麼問題,你遇到。你能告訴我們更多嗎?

如果沒有所有細節,我會說一個潛在的問題是廣播接收器通常在Android的UI線程中執行,並且不允許您執行網絡訪問,並且它必須在X秒內完成。

1)您沒有訪問互聯網正確的權限?從我記得的日誌可以很容易錯過。 2)要麼你可以請求無線局域網運行後臺線程,我知道你可以做到,而不是自己嘗試。 3)你可以開始另一個線程。正如你所看到的更新UI,你可能應該使用一個異步任務。因此,您可以在後臺線程中執行網絡,然後您可以在UI線程中使用新數據進行調用。 (這很可能是去選擇)

旁註:解析JSON,我建議你看看GSON。這是一個來自谷歌的圖書館,使Json的parsin更簡單。 https://github.com/google/gson

0
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); 
} 

}

// CODE FOR START BACKGROUND TASK 

GoogleApiAvailability api = GoogleApiAvailability.getInstance(); 
Int errorCheck = api.isGooglePlayServicesAvailable(LoginActivity.this); 

      if(errorCheck == ConnectionResult.SUCCESS) { 
        //google play services available, hooray 
       } else if(api.isUserResolvableError(errorCheck)) { 
        //GPS_REQUEST_CODE = 1000, and is used in onActivityResult 
        api.showErrorDialogFragment(LoginActivity.this, errorCheck, GPS_REQUEST_CODE); 
        //stop our activity initialization code 
        return; 
       } else { 
        //GPS not available, user cannot resolve this error 
        //todo: somehow inform user or fallback to different 
        method 
        //stop our activity initialization code 
        return; 
} 

GCMServiceTracking.scheduleRepeat(LoginActivity.this); 


GRADLE FILE 
compile 'com.google.android.gms:play-services:8.3.0' 

MENIFEST FILE 
    <service 
     android:name=".services.GCMServiceTracking" 
     android:exported="true" 
     android:permission="com.google.android.gms.permission.BIND_NETWORK_TASK_SERVICE"> 
     <intent-filter> 
      <action android:name="com.google.android.gms.gcm.ACTION_TASK_READY" /> 
     </intent-filter> 
    </service>