2016-05-26 122 views
2

我想從其他服務啓動一個服務不在一個活動,我做了下面的代碼,但沒有工作它執行塊,但服務未啓動。在其他服務啓動服務不啓動

Myservice.class

HttpPost post = new HttpPost(Constant1.URL_GET_COURSE_LIST); 
String result = HTTPadapter.getDetails(post); 
Log.e("resultofcourselist", "" + result); 
Intent i=new Intent(getApplicationContext(),DemoService.class); 
i.putExtra("result", result); 
startService(i); 

Demoservice.class

intent.getStringExtra("result"); 

try { 
    jsonResponse = new JSONArray(result); 
    jsonObject = jsonResponse.getJSONObject(0); 
    jsonMainNode = jsonObject.optJSONArray("rowsResponse"); 

    //DbAdd dbAdd=new DbAdd(); 
    for (int i = 0; i < jsonMainNode.length(); i++) { 
     JSONObject jsonChildNode = jsonMainNode.getJSONObject(i); 
     result = jsonChildNode.optString("result").toString(); 

     if (result.equals("Success")) { 
      jsonObject = jsonResponse.getJSONObject(1); 
      jsonMainNode = jsonObject.optJSONArray("getCourseList"); 
      // dbAdd.setJsonMainNode(jsonMainNode); 
      for (int j = 0; j < jsonMainNode.length(); j++) { 
       // dbAdd.setJsonChildNode(); 
       JSONObject childnode = jsonMainNode.getJSONObject(j); 
       Intent dbadd = new Intent(getApplicationContext(), Dbadd.class); 
       dbadd.putExtra("mainnode", jsonMainNode.toString()); 
       dbadd.putExtra("childnode", childnode.toString()); 
       // dbadd.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
       startService(dbadd); 
      } 
      stopSelf(); 
     } else { 
      // 
     } 
    } 
} catch (Exception e) { 
    e.printStackTrace(); 
} 

的Manifest.xml

<service android:name=".Myservice" /> 
<service android:name=".DemoService" /> 

登錄

Myservice start print in log but in demoservice on startcommand not execute 

回答

1

刪除以下行,因爲啓動服務你突然打電話stopSelf()其停止服務

stopSelf(); 
+0

@馬丁Demoservice從來沒有穿過我的服務,是我的問題 – user3481301

+0

@ user3481301的答案進行了編輯,從而使我的評論開始(和你的藏漢)過時的^^ –

0

使用意向的售後服務。您不需要停止意向服務。任務完成後它會自動停止。

如何讓意圖服務類:

public class MyIntentService extends IntentService { 
/** 
* Creates an IntentService. Invoked by your subclass's constructor. 
* 
* @param name Used to name the worker thread, important only for debugging. 
*/ 
private static final String TAG = "MyIS"; 
private Context mContext; 
public MyIntentService() { 
    super(TAG); 
    mContext = this;} 

@Override 
protected void onHandleIntent(Intent intent) { 
    //Do Your Code Here. 
}} 

而且不要忘記在清單上註冊://我用:

<service 
     android:name=".MyIntentService " 
     android:exported="false" /> 

使用上下文你從異步啓動的服務意向m上下文

 Intent intent_update = new Intent(mContext, MyIntentService .class); 
    mContext.startService(intent_update); 

需要更多幫助,然後評論。

+0

我得到mcontext,但intentservice也是上下文的孩子,所以其不需要mcontext – user3481301

+0

其實我是從AsyncTask開始的Intent Service,所以我寫了這個。 Sry爲此。 –