0
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)時;在執行新操作之前,該服務將首先調用前一個操作的意圖。從新的操作之前的可運行調用前一操作調用服務。如何防止這一點?
我會嘗試START_NOT_STICKY。感謝您的建議。稍後編輯代碼:D – Sybregunne
返回START_NOT_STICKY對我無效。 – Sybregunne
我看着你的編輯代碼,但找不到任何東西。它應該工作正常。順便說一下,您分享的完整日誌是?另外,請檢查您是否在第一次啓動意圖的地方沒有兩次調用過'startIntent(i)'。 – AnniJais