我想每10秒重新启动一次IntentService(用于处理HTTP POST请求)。我尝试使用每个帖子中都介绍的AlarmManager和PendingIntent。但是我的IntentService无法启动。我找不到任何原因,因此不胜感激。
IntentService
public class MyService extends IntentService{
public MyService() {
super("MyService");
// TODO Auto-generated constructor stub
}
@Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Service Started", Toast.LENGTH_SHORT).show();
System.out.println("Service Started");
// POST request code here
}
}
MainActivity
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
start();
}
public void start() {
Intent intent = new Intent(this, MyService.class);
intent.putExtra("com.hybris.proxi.triggerTime", 5000);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, 0);
long trigger = System.currentTimeMillis() + (5*1000);
AlarmManager am =( AlarmManager)getSystemService(Context.ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, trigger, pendingIntent);
}
}
最佳答案
您可以使用以下代码:
final Handler handler = new Handler();
TimerTask timertask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
startService(new Intent(getApplicationContext(),
MyService.class));
}
});
}
};
Timer timer = new Timer();
timer.schedule(timertask, 0, 10000);
}
这将以10秒的间隔执行
另外,添加您的Service类以显示:
<service
android:name=".MyService"
android:enabled="true" >
</service>
关于android - IntentService与AlarmManager,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/33030727/