我想知道如何设置我的应用程序,每隔15分钟就通过API帖子更新其详细信息。现在,我知道如何使用get并使用一个线程,以便在访问API时为它创建一个加载器。
我是这样做的:
private int authenticateLogin()
{
EditText user = ((EditText)findViewById(R.id.username));
EditText pass = ((EditText)findViewById(R.id.password));
StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy);
String username = user.getText().toString(), password = pass.getText().toString();
String URL = "MyUrl";
String authData = "Basic " + Base64.encodeToString((username + ":" + password).getBytes(), Base64.NO_WRAP);
HttpClient httpclient = new DefaultHttpClient();
HttpGet httpget = new HttpGet(URL);
httpget.setHeader("Authorization", authData);
HttpResponse response = null;
try {
response = httpclient.execute(httpget);
StatusLine sl = response.getStatusLine();
int statCode = sl.getStatusCode();
if (statCode == 200) {
String entityStringDrivers = EntityUtils.toString(response.getEntity());
Intent i = new Intent(Login.this,DriverLogin.class);
i.putExtra("stringDrivers", entityStringDrivers);
startActivity(i);
return 100;
}
else
{
user.setText("");
pass.setText("");
Toast.makeText(getBaseContext(), "Unauthorized Login", Toast.LENGTH_SHORT).show();
return 100;
}
} catch (Exception e) {
// Auto-generated catch block
e.printStackTrace();
return 100;
}
finally {
}
}
我想知道在发布时我该怎么做,并在后台进行。我不知道从哪里开始每15分钟POST一次。有任何想法吗?谢谢!
答案 0 :(得分:0)
您可以检查一下,并使用Intent Services在后台运行。
android timer,对于意向服务,请查看Intent Services
答案 1 :(得分:0)
使用计时器处理程序,如下所示:
在代码段startTimeReqTask()
中启动计时器。
private Handler m_handler = new Handler();
....
Runnable m_handlerTask = new Runnable() {
@Override
public void run() {
m_handler.postDelayed(m_handlerTask, 900000); // 15 minutes
new authenticateLoginTask().execute(); // POST (your asynctask)
}
};
private void startTimeReqTask() // start timer
{
m_handlerTask.run();
}
private void stopTimeReqTask() // stop time
{
m_handler.removeCallbacks(m_handlerTask);
}
并使用AsyncTask
authenticateLoginTask来做背景。
答案 2 :(得分:0)
如果您想要执行此背景,请创建一个服务并在主活动的onCreate或某些BroadcastReceiver中启动它
例如:(您需要添加try-catch或其他类型的保护代码)
public class MyService extends Service {
@Override
public void onStartCommand(Intent intent, int flags, int startId) {
//Use intent to pass your username and password here
//start a PostThread here.
}
private class PostThread extends Thread {
private static final int INTERVAL = 15 * 60 * 1000L;
private boolean canceled = false;
@Override
public void run() {
while (!canceled) {
Post();
Thread.sleep(INTERVAL); // or you can use a Timer to trigger this
}
}
public void interrupt() { canceled = true; super.interrupt();}
}
}
答案 3 :(得分:0)
Timer timer = new Timer();
timer.schedule(new TimerTask() {
@Override
public void run() {
runOnUiThread(new Runnable() {
@Override
public void run() {
// call your api method here
}
});
}
}, 0, /*here define your internal*/);
// when you no longer required this api call just call "cancel" method of timer