我有我创建的后台任务
package com.cnn.service;
/**
*
* @author USER
*/
import android.app.Service;
import android.os.IBinder;
import android.content.Intent;
public class AndroidStartServiceOnBoot extends Service {
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
// do something when the service is created
}
}
和其他文件
package com.cnn.service;
/**
*
* @author USER
*/
import android.content.Context;
import android.content.BroadcastReceiver;
import android.content.Intent;
// here is the OnRevieve methode which will be called when boot completed
public class BootCompleted extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
//we double check here for only boot complete event
if(intent.getAction().equalsIgnoreCase(Intent.ACTION_BOOT_COMPLETED))
{
//here we start the service
Intent serviceIntent = new Intent(context, AndroidStartServiceOnBoot.class);
context.startService(serviceIntent);
}
}
}
我有每秒运行的任务
final Handler handler = new Handler();
Runnable runable = new Runnable() {
@Override
public void run() {
try{
//do your code here
//also call the same runnable
handler.postDelayed(this, 1000);
}
catch (Exception e) {
// TODO: handle exception
}
finally{
//also call the same runnable
handler.postDelayed(this, 1000);
}
}
};
handler.postDelayed(runable, 1000);
我想在后台服务中每秒执行一些http发布。
我应该将代码放在BootCompleted
类中?
答案 0 :(得分:0)
在服务类的onCreate方法
中