我已经完成了将数据传递给 url 的代码,并且成功了。但是现在我需要在后台执行此操作,因此即使应用程序结束,我也会提供服务来执行此操作。我的问题是当我启动服务时它传递一次数据,但我需要每隔一段时间传递一次数据,所以该怎么做?
这是我的代码
public class MyService extends Service {
private static final String TAG = "MyService";
@Override
public IBinder onBind(Intent intent) {
return null;
}
Random r;
@Override
public void onCreate() {
Toast.makeText(this, "My Service Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
@Override
public void onDestroy() {
Toast.makeText(this, "My Service Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
player.stop();
}
@Override
public void onStart(Intent intent, int startid) {
Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
Log.d(TAG, "onStart");
r=new Random();
//
int o=r.nextInt(1000);
HttpPost postMethod = new HttpPost("http://androidsaveitem.appspot.com/save");
List<NameValuePair> formparams = new ArrayList<NameValuePair>();
formparams.add(new BasicNameValuePair("description+", "description FOR id "+String.valueOf(o)));
formparams.add(new BasicNameValuePair("id+", String.valueOf(o)));
UrlEncodedFormEntity entity;
try {
entity = new UrlEncodedFormEntity(formparams);
postMethod.setEntity(entity);
DefaultHttpClient hc = new DefaultHttpClient();
try {
HttpResponse response = hc.execute(postMethod);
} catch (ClientProtocolException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
在活动中我写了这个
startService(new Intent(this, MyService.class));
我已经在清单文件中写了权限
<service android:enabled="true" android:name=".MyService" />
<uses-permission android:name="android.permission.INTERNET" />