Androidではかなり新しい。
ここでの問題は簡単です。私のアプリは、一定の時間間隔で起動する必要があります。問題は、それを正しく呼び出すことができないことです。
コメント // HERE IS THE PROBLEM にコードが壊れており、コンテキストを見つけて宣言できないというエラーが表示されます。
public class BackgroundService extends Service {
Integer background_connect = null;
String SERVER_IP;
String APP_ID;
private Context context;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
DB_Queries db = new DB_Queries(getApplicationContext());
Cursor c = db.getSettings();
StringBuilder app_id = new StringBuilder();
StringBuilder server_ip = new StringBuilder();
if (c.moveToFirst()) {
do {
server_ip.append(c.getString(c.getColumnIndex("server_ip")));
app_id.append(c.getString(c.getColumnIndex("app_id")));
} while (c.moveToNext());
}
db.close();
SERVER_IP = server_ip.toString();
APP_ID = app_id.toString();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
requestServerDelay delay = new requestServerDelay();
delay.execute("http://" + SERVER_IP + "/index.php/app/requestAppRecall");
return super.onStartCommand(intent, flags, startId);
}
private class requestServerDelay extends AsyncTask<String, Void, Void> {
@Override
protected Void doInBackground(String... params) {
HttpClient client = new DefaultHttpClient();
HttpPost post = new HttpPost(params[0]);
post.addHeader("Content-type", "application/x-www-form-urlencoded");
List<NameValuePair> pair = new ArrayList<NameValuePair>();
pair.add(new BasicNameValuePair("app_id", APP_ID));
try {
post.setEntity(new UrlEncodedFormEntity(pair));
HttpResponse response = client.execute(post);
InputStream is = response.getEntity().getContent();
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
StringBuilder str = new StringBuilder();
String chunk = null;
while ((chunk = br.readLine()) != null) {
str.append(chunk);
}
background_connect = Integer.parseInt(str.toString());
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
@Override
protected void onPostExecute(Void result) {
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
public void run() {
//HERE IS THE PROBLEM
Intent intent = new Intent(getApplication().getApplicationContext(), getApplication().getApplicationContext().getClass());
intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
intent.addFlags(Intent.FLAG_ACTIVITY_PREVIOUS_IS_TOP);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().getApplicationContext().startActivity(intent);
}
}, background_connect * 60 * 1000);
}
}
}