简体   繁体   中英

How to pass string from OnStartCommand into OnHandleIntent in an IntentService?

Android/Java noob here. I have a URL that I am discovering in another part of my application. I am successfully passing that URL as a string into an intent service's OnStartCommand. I would then like to make that string containing my URL available to HttpURLConnection residing in a thread in OnHandleIntent as shown below. How can I get I get the URL within the myUrl string into OnHandleIntent?

@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        String myUrl;
        myUrl = intent.getExtras().getString("myUrl");

         return super.onStartCommand(intent, flags, startId);   
    }

    @Override
    protected void onHandleIntent(Intent intentNotify) {
        try {
              URL url = new URL("myUrl");
              HttpURLConnection con = (HttpURLConnection) url.openConnection();
              readStream(con.getInputStream());
              } catch (Exception e) {
              e.printStackTrace();
            }
    }

You should not be overriding the onStartCommand of an intentservice. From the javadoc for onStartCommand

You should not override this method for your IntentService. Instead, override onHandleIntent(Intent), which the system calls when the IntentService receives a start request.

Is there a reason why you are not trying to retrieve the extras from the intent passed to onHandleIntent like below?

@Override
protected void onHandleIntent(Intent intent) {
    String myUrl = intent.getExtras().getString("myUrl");

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM