0

我已经完成了将数据传递给 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" />
4

1 回答 1

0

与其让你Service一直在后台运行(除非它一直在工作!),你应该考虑向操作系统注册一个警报,它会以指定的时间间隔唤醒你的服务,然后在它完成后让它重新进入睡眠状态.

这将简化您的Service实现并使您摆脱大多数与时间相关的问题。您还将获得好处,如果您的Service崩溃或因某种原因被杀死,警报计时器将在下一个周期将其恢复。

它的工作方式是通过创建一个BroadcastReceiver监听Intent您在Android 的AlarmManager.

您选择哪个选项在很大程度上取决于您的间隔有多大,因为广播警报比让计时器等待更昂贵。如果你想每隔几秒钟做一次工作,计时器可能会更好。如果您的等待时间以分钟或小时为单位,请执行警报操作。

首先,您需要创建警报。

PendingIntent pi = PendingIntent.getService(context, 0, yourIntent, yourFlags);
AlarmManager am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
am.setInexactRepeating(AlarmManger.ELAPSED_REALTIME, // Alarm type 
                       5000,                         // Time before first alarm
                       AlarmManager.INTERVAL_HOUR,   // Alarm interval
                       pi);                          // Sent when alarm happens

要真正使用警报,您必须听它响起。为此,您需要创建一个BroadcastReceiver.

public class SnoozeButton extends BroadcastReceiver {
    public void onReceive (Context context, Intent intent) {
        if (thisIntentIsTheOneIWant(intent){
            context.startService(intent);
        }
    }

    private boolean thisIntentIsTheOneIWant(Intent intent) {
        // Test here to make sure this intent is for your app 
        // and service.  You may get Intents other than what
        // you are interested in.
    }
}

请注意,您必须BroadcastReciever在您的AndroidManifest.xml.

于 2012-03-24T16:42:38.057 回答