/**
* Send Button click event.
**/
send.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
NetAsync(view);
}
});
}
点击事件" NetAsync(查看)"执行并将gps坐标发送到服务器,但我想要的是,而不是在用户启动应用程序时使用按钮点击事件" NetAsync(view)"每10分钟后自动执行一次。请告诉我如何做到这一点,因为我是Android编程的新手。
答案 0 :(得分:11)
你可以像这样使用TimerTask和Timer类来实现它
final Handler handler = new Handler();
Timer timer = new Timer();
TimerTask doAsynchronousTask = new TimerTask() {
@Override
public void run() {
handler.post(new Runnable() {
public void run() {
try {
//your method here
} catch (Exception e) {
}
}
});
}
};
timer.schedule(doAsynchronousTask, 0, 600000); //execute in every 10 minutes
答案 1 :(得分:1)
尝试以下内容:
TimerTask scanTask;
final Handler handler = new Handler();
Timer t = new Timer();
public void doWifiScan(){
scanTask = new TimerTask() {
public void run() {
handler.post(new Runnable() {
public void run() {
NetAsync(view);
}
});
}};
t.schedule(scanTask, 300, 600000);
}
答案 2 :(得分:0)
使用处理程序您可以轻松实现目标,请遵循以下代码,
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
if (!isSyncStart) {
startSyncProcess(true); //write Your Method Here!
}
}
}, 600000);
答案 3 :(得分:0)
将AlarmManager与广播接收器一起使用
private PendingIntent mPingAlarmPendIntent;
private static final String PING_ALARM = "com.sithagi.PING_ALARM";
private Intent mPingAlarmIntent = new Intent(PING_ALARM);
private BroadcastReceiver mPingAlarmReceiver = new PingAlarmReceiver();
mPingAlarmPendIntent = PendingIntent.getBroadcast(getApplicationContext(), 0, mPingAlarmIntent,
PendingIntent.FLAG_UPDATE_CURRENT);
// Each and every 15 minutes will trigger onReceive of your BroadcastReceiver
((AlarmManager)getSystemService(Context.ALARM_SERVICE)).setInexactRepeating(AlarmManager.RTC_WAKEUP,
System.currentTimeMillis() + (AlarmManager.INTERVAL_FIFTEEN_MINUTES), AlarmManager.INTERVAL_FIFTEEN_MINUTES, mPingAlarmPendIntent);
// Register the receiver
registerReceiver(mPingAlarmReceiver, new IntentFilter(PING_ALARM));
// To cancel Alarm Service
((AlarmManager)getSystemService(Context.ALARM_SERVICE)).cancel(mPingAlarmPendIntent);
// unregister the receiver onDestroy or if you want stop
unregisterReceiver(mPingAlarmReceiver);
/**
* BroadcastReceiver will trigger
*/
private class PingAlarmReceiver extends BroadcastReceiver {
public void onReceive(Context ctx, Intent i) {
// Do your work here
}
}