其他服务中的启动服务无法启动

时间:2016-05-26 11:13:40

标签: java android

我想从不在活动中的其他服务启动一个服务,我做了以下代码,但是没有工作它执行块但服务没有启动。

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

2 个答案:

答案 0 :(得分:1)

删除以下行,因为在启动服务后,您突然调用stopSelf()来停止服务

stopSelf();

答案 1 :(得分:0)

使用Intent服务。您无需停止Intent Service。任务完成后它将自动停止。

如何制作Intent服务类:

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.
}}

不要忘记在Manifest中注册:

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

使用您获取的上下文从Async启动Intent服务://我使用mContext

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

需要更多帮助然后评论。