public class MyService extends Service {
long i = 0;
final String TAG="MyService";
public void onCreate() {
//initialize service here
}
public int onStartCommand(Intent intent, int flags, int startId) {
log.i(TAG, i+":BEGIN");
if (intent!=null) {
String action = intent.getAction();
log.i(TAG, i+":"+action);
if (action.equals("RETRIEVE_SETTINGS_FROM_NET_SERVER") {
new GetSettings().run();
} else if (action.equals("RESTART_SERVICE_COMPONENT")) {
//create alarmmanager code here
}
log.i(TAG, i+":complete");
i++;
}
}
private class GetSettings implements Runnable {
String urlString;
public GetSettings(String _urlString) {
if (_urlString!=null) urlString = _urlString;
}
public void run() {
HttpURLConnection c;
if (urlString!= null) {
try {
URL u = new URL(urlString);
c = (HttpURLConnection) u.openConnection();
c.setRequestMethod("GET");
c.setInstanceFollowRedirects(true);
c.setDoOutput(true);
c.connect();
int serverResponse = c.getResponseCode();
switch (serverResponse) {
case HttpURLConnection.HTTP_OK:
InputStream in;
in = c.getInputStream();
int next = -1;
StringBuffer tmpSvrResp = new StringBuffer();
while ((next = in.read()) != -1) {
tmpSvrResp.append((char)next);
}
in.close();
Map <String, String> newSettings = splitQuery(tmpSvrResp.toString());
//Apply new settings.
break;
default:
break;
}
} catch (MalformedURLException e) {
log.i(e.toString());
} finally {
if (c!=null) c.disconnect();
if (isSuccessful)
Intent i = new Intent(MyService.this, MyService.class);
i.setAction("RESTART_SERVICE_COMPONENT");
startService(i); //This call repeats RETRIEVE SETTINGS... action
} else {
Toast.makeText(MyService.this, "Error: setting new configuration from server!",Toast.LENGTH_SHORT);
}
}
}
}
}
private Map<String, String> splitQuery(URL url) throws UnsupportedEncodingException {
Map<String, String> query_pairs = new LinkedHashMap<String, String>();
String query = url.getQuery();
String[] pairs = query.split("&");
for (String pair : pairs) {
int idx = pair.indexOf("=");
query_pairs.put(URLDecoder.decode(pair.substring(0, idx), "UTF-8"), URLDecoder.decode(pair.substring(idx + 1), "UTF-8"));
}
return query_pairs;
}
}
here is a sample log...
MyService 0:BEGIN
MyService 0:RETRIEVE_SETTINGS_FROM_NET_SERVER
MyService 0:complete
MyService 1:BEGIN
MyService 1:RETRIEVE_SETTINGS_FROM_NET_SERVER
MyService 1:complete
MyService 2:BEGIN
MyService 2:RESTART_SERVICE_COMPONENT
MyService 2:complete
こんにちは、検索しましたが、同じようなものは見つかりませんでした。サーバーから更新された設定を取得するサービスがあります。その後、スケジュールを再開します。私の問題は、startservice(i); を呼び出すたびに発生することです。サービスは、新しいアクションを実行する前に、最初に前のアクションでインテントを呼び出します。