2016-05-26 82 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为此。 –