您可以編寫服務和AlarmManager來執行此操作。只需在服務中註冊您的應用程序,並調用alarmMangaer.setRepeat()方法來啓動您的服務器代碼或您想要在onStart()方法服務中執行的任何其他操作。
public class MyService extends Service{
Calendar cur_cal = Calendar.getInstance();
@Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
Intent intent = new Intent(this, MyService.class);
PendingIntent pintent = PendingIntent.getService(getApplicationContext(),
0, intent, 0);
AlarmManager alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
cur_cal.setTimeInMillis(System.currentTimeMillis());
alarm.setRepeating(AlarmManager.RTC_WAKEUP, cur_cal.getTimeInMillis(),
60 * 1000*3, pintent);
}
@Override
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
// your code for background process
}
}
在AndroidManifest.xml中添加此
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<service
android:name="com.yourpackage.MyService"
android:enabled="true" />
<receiver android:name=".BootCompletedIntentReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
編輯:BootCompletedIntentReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
public class BootCompletedIntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if ("android.intent.action.BOOT_COMPLETED".equals(intent.getAction())) {
Intent pushIntent = new Intent(context, MyService.class);
context.startService(pushIntent);
}
}
}