我正在寫一個應用程序來解析來自服務器的數據(我通過WAMP創建服務器)並警告數據是否達到某個閾值(振動,播放聲音...)。因此,我希望我的應用程序在應用程序完成時仍然會收到數據警告。我知道android中的服務可以做到這一點,但我不知道寫一個服務類。所以,如果你知道,請幫助我。 我已經解析了數據,並將其顯示在android應用程序中。我的應用程序自動從服務器獲取數據3分鐘。 這是代碼:如何在應用程序完成時從服務器獲取數據?
public class CurrentData extends Fragment {
public CurrentData() {
super();
// TODO Auto-generated constructor stub
}
TextView id;
TextView temp;
TextView acc;
TextView moisture;
TextView battery;
TextView date;
TextView time;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.currentdata_layout,
container, false);
id = (TextView) rootView.findViewById(R.id.showID);
temp = (TextView) rootView.findViewById(R.id.showTEMP);
acc = (TextView) rootView.findViewById(R.id.showACC);
moisture = (TextView) rootView.findViewById(R.id.showMoisture);
battery = (TextView) rootView.findViewById(R.id.showBat);
date = (TextView) rootView.findViewById(R.id.showDATE);
time = (TextView) rootView.findViewById(R.id.showTIME);
callAsynTask();
return rootView;
}
private void callAsynTask() {
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
@Override
public void run() {
try {
new GetInfo().execute();
} catch (Exception e) {
}
}
});
}
};
timer.schedule(doAsynTask,0, 180000);
}
public class GetInfo extends AsyncTask<String, Void, Parameter> {
@Override
protected Parameter doInBackground(String... arg0) {
String data = ((new LandSlideHttpClient().getDeviceData()));
Parameter parameter = new Parameter();
try {
parameter = JSONLandslideParser.getParameter(data);
} catch (JSONException e) {
e.printStackTrace();
}
return parameter;
}
@Override
protected void onPostExecute(final Parameter result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
id.setText(result.id.getID());
temp.setText(" " + result.currentData.getTemp());// + " °C");
acc.setText(" " + result.currentData.getAcc());// + " m/s2");
moisture.setText(" " + result.currentData.getMoisture());// +
// " mps");
battery.setText(" " + result.currentData.getBattery());// + " %");
date.setText(result.currentData.getDate());
time.setText(result.currentData.getTime());
new warning(); // class to alert
}
}
}
我很抱歉,但你一定要閱讀文檔,請情侶教程並自己嘗試。現在你的問題太廣泛了,不適合SO。 –