将字符串从一个 activity 发送到另一个 activity 并将其用作 AsyncTask 中的 url 参数

Send string from one activity to another and use it as url parameter in AsyncTask

是否有人知道如何在另一个具有 AsyncTask 的 activity 中使用从一个 activity 接收的字符串并将此字符串用作 doInBackground 中 url link 的一部分?我需要启动 activity,它在 GCM 通知到达时显示提要,并使用通知中的字符串启动 activity。这里是 activity 发送字符串 (GcmIntentServices) 和 activity 与 AsyncTask 接收字符串并转发到 AsyncTask 以构建 url link 用于提要。字符串是 msg1,它由必须附加到 AsyncTask 中的 url link 的文本组成。

GcmIntentServices.java:

public class GcmIntentService extends IntentService {

    public static final int NOTIFICATION_ID = 1;
    private static final String TAG = "GcmIntentService";
    private NotificationManager mNotificationManager;
    NotificationCompat.Builder builder;
    Context context;
    public static final int notifyID = 9001;
    String msg1;
    String msg2;

    public GcmIntentService() {
        super("GcmIntentService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        Bundle extras = intent.getExtras();
        GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
        String msg1 = intent.getStringExtra("cat_name");
        String msg2 = intent.getStringExtra("message");

        // The getMessageType() intent parameter must be the intent you received
        // in your BroadcastReceiver.
        String messageType = gcm.getMessageType(intent);

        if (!extras.isEmpty()) {  // has effect of unparcelling Bundle
            /*
             * Filter messages based on message type. Since it is likely that GCM
             * will be extended in the future with new message types, just ignore
             * any message types you're not interested in, or that you don't
             * recognize.
             */
            if (GoogleCloudMessaging.
                    MESSAGE_TYPE_SEND_ERROR.equals(messageType)) {
                sendNotification("Send error: " + extras.toString());
            } else if (GoogleCloudMessaging.
                    MESSAGE_TYPE_DELETED.equals(messageType)) {
                sendNotification("Deleted messages on server: " +
                        extras.toString());
            // If it's a regular GCM message, do some work.
            } else if (GoogleCloudMessaging.
                    MESSAGE_TYPE_MESSAGE.equals(messageType)) {
                // This loop represents the service doing some work.
                for (int i=0; i<5; i++) {
                    Log.i(TAG, "Working... " + (i+1)
                            + "/5 @ " + SystemClock.elapsedRealtime());
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                    }
                }
                Log.i(TAG, "Completed work @ " + SystemClock.elapsedRealtime());
                // Post notification of received message.
            //    sendNotification(extras.getString("Notice"));
                sendNotification(msg1);
                Log.i(TAG, "Received: " + extras.toString());
            }
        }
        // Release the wake lock provided by the WakefulBroadcastReceiver.
        GcmBroadcastReceiver.completeWakefulIntent(intent);
    }

    private void sendNotification(String msg1) {

     /*   Intent resultIntent = new Intent(this, AndroidRssReader.class);
        resultIntent.putExtra("message", msg);
        PendingIntent resultPendingIntent = PendingIntent.getActivity(this, 0,
                resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);  */

        Intent resultIntent = new Intent(this, AndroidRssReader.class);
        Bundle b = new Bundle();
    //    b.putString("message", msg);
        b.putString("cat_name", msg1);
    //    resultIntent.putExtra("cat_name", msg1);
        resultIntent.putExtras(b);
        resultIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_SINGLE_TOP);
        PendingIntent resultPendingIntent = PendingIntent.getActivity(getApplicationContext(), 0,
                resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder mNotifyBuilder;
        NotificationManager mNotificationManager;

        mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);

        mNotifyBuilder = new NotificationCompat.Builder(this)
           //     .setContentTitle("Alert")
          //      .setContentText("You've received new message.")
                .setContentTitle("")
                .setContentText(msg1)
                .setStyle(new NotificationCompat.BigTextStyle().bigText(msg1))
                         .setSmallIcon(R.drawable.gcm_cloud);
        // Set pending intent
        mNotifyBuilder.setContentIntent(resultPendingIntent);

        // Set Vibrate, Sound and Light
        int defaults = 0;
        defaults = defaults | Notification.DEFAULT_LIGHTS;
        defaults = defaults | Notification.DEFAULT_VIBRATE;
        defaults = defaults | Notification.DEFAULT_SOUND;

        mNotifyBuilder.setDefaults(defaults);
        // Set the content for Notification
    //    mNotifyBuilder.setContentText("New message from Server");
        // Set autocancel
        mNotifyBuilder.setAutoCancel(true);
        // Post a notification
        mNotificationManager.notify(notifyID, mNotifyBuilder.build());
    }
    }

AndroidRssReader.java(更新):

public class AndroidRssReader extends ListActivity {

    private RSSFeed myRssFeed = null;

    ProgressDialog progressDialog;

    private String kat;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mainrss);


        Bundle extras = getIntent().getExtras();

        if(extras != null) {
            if(extras.containsKey("cat_name")) {

                String kat = extras.getString("cat_name");

                MyTask task = new MyTask();

                task.execute(kat);

                Toast.makeText(AndroidRssReader.this, kat, Toast.LENGTH_LONG).show();  // here I'm getting kat value properly!!!

            }
        }

    }



    private class MyTask extends AsyncTask<String, Void, Void>{


        @Override

        protected Void doInBackground(String... params) {

            String kat = params[0];

            Log.d("AJDE!", kat); // here, I'm getting kat value properly in logcat, why kat doesnt go toURL rssUrl ???

            try {

                URL rssUrl = new URL("http://www.example.com/category/" + kat + "/feed/");

                SAXParserFactory mySAXParserFactory = SAXParserFactory.newInstance();
                SAXParser mySAXParser = mySAXParserFactory.newSAXParser();
                XMLReader myXMLReader = mySAXParser.getXMLReader();
                RSSHandler myRSSHandler = new RSSHandler();
                myXMLReader.setContentHandler(myRSSHandler);
                InputSource myInputSource = new InputSource(rssUrl.openStream());
                myXMLReader.parse(myInputSource);

                myRssFeed = myRSSHandler.getFeed();
            } catch (MalformedURLException e) {
                e.printStackTrace();
            } catch (ParserConfigurationException e) {
                e.printStackTrace();
            } catch (SAXException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            return null;

        }



        @Override
        protected void onPostExecute(Void result) {
            if (myRssFeed!=null)
            {
                TextView feedTitle = (TextView)findViewById(R.id.feedtitle);
                TextView feedSadrzajPosta = (TextView)findViewById(R.id.feedsadrzaj_posta);
                TextView feedPubdate = (TextView)findViewById(R.id.feedpubdate);
                TextView feedLink = (TextView)findViewById(R.id.feedlink);
                feedTitle.setText(myRssFeed.getTitle());
                feedSadrzajPosta.setText(myRssFeed.getSadrzajPosta());
                feedPubdate.setText(myRssFeed.getPubdate());
                feedLink.setText(myRssFeed.getLink());

                ArrayAdapter<RSSItem> adapter =
                        new ArrayAdapter<RSSItem>(getApplicationContext(),
                                R.layout.list_black_text,R.id.list_content,myRssFeed.getList());
                setListAdapter(adapter);

                //      Toast.makeText(getApplicationContext(), "GGG: " + msg1, Toast.LENGTH_SHORT).show();


            }else{



                TextView textEmpty = (TextView)findViewById(android.R.id.empty);
                textEmpty.setText("No Feed Found!");
            }

            super.onPostExecute(result);
        }

     /*   @Override
        protected void onPreExecute() {
            super.onPreExecute();
            progressDialog = ProgressDialog.show(AndroidRssReader.this, "Please WAIT", "Loading ...");
        }  */

    }



    @Override
    protected void onListItemClick(ListView l, View v, int position, long id) {
        // TODO Auto-generated method stub
        Intent intent = new Intent(this,ShowDetails.class);
        Bundle bundle = new Bundle();
        bundle.putString("keyTitle", myRssFeed.getItem(position).getTitle());
        bundle.putString("keySadrzajPosta", myRssFeed.getItem(position).getSadrzaj_posta());
        bundle.putString("keyLink", myRssFeed.getItem(position).getLink());
        bundle.putString("keyPubdate", myRssFeed.getItem(position).getPubdate());
        intent.putExtras(bundle);
        startActivity(intent);
    }
}

现在,我得到了具有预期值的字符串 kat,在 doInbackground 中使用 Log.d 检查,但字符串 kat 没有进一步使用 URL link.

您必须将字符串作为参数 msg1 发送

task.execute(msg1);

doInBackground 然后接收跟随

String msg1 = arg0[0];

那么就可以完美的使用变量msg1

您可以尝试在一个字符串中分开生成 url 并显示 logcat 的输出吗?例如

String url = "http://www.example.com/category/"+kat+"/feed/";
Log.i("URL",url);

所以我们可以更好地了解会发生什么