【发布时间】:2012-03-24 15:48:22
【问题描述】:
我已经完成了将数据传递给 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" />
【问题讨论】:
-
嗯哪里可以做这个???
-
请你写定时器的代码
-
thanksss 但它没有工作没有数据传递到 url :(
-
它填充 null 但我运行程序时不填充,是你的吗?
-
是的,代码完美运行,但您的数据库可能还有其他问题。请参阅我的编辑帖子
标签: android android-intent android-widget android-service android-networking