Android使用字符串从另一个活动Asynctask (Void)的活动



我有一个应用程序,我需要从一个活动发送字符串到另一个,并在活动的AsyncTask部分使用此字符串。我成功地发送字符串,并在第二个活动的onCreate部分接收它,但在asyncTask中,这个字符串需要成为feed url的一部分,总是接收空值。GcmIntentServices.java activity发送String到AndroidRSSReader activity, String msg1.

GcmIntentServices.java:

package com.andrija.bladimircodewp;
import com.google.android.gms.gcm.GoogleCloudMessaging;
import android.app.IntentService;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.TaskStackBuilder;
import android.content.Context;
import android.content.Intent;
import android.media.RingtoneManager;
import android.os.Bundle;
import android.os.SystemClock;
import android.provider.Settings;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.Toast;
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");
    //    String msg = intent.getStringExtra("message");
    //    String msg = msg1 + ":" + msg2;
        // 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());
    }
    }

和活动接收字符串从另一个,AndroidRSS Reader.java:

package com.andrija.bladimircodewp;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import android.app.ProgressDialog;
import android.app.ListActivity;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
public class AndroidRssReader extends ListActivity {
    private RSSFeed myRssFeed = null;
//    TextView mojtext = null;
//  public String msg1 = "Katarina";

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.mainrss);
    //    mojtext = (TextView)findViewById(R.id.moj_text);
        Bundle extras = getIntent().getExtras();
   //     if(extras != null){
        //    String msg = extras.getString("message");
         String msg1 = extras.getString("cat_name");
        //    mojtext.setText("EVO TITLA : " + msg);
        //    Toast.makeText(AndroidRssReader.this, msg1, Toast.LENGTH_LONG).show();
       //     new MyTask().execute();
            MyTask task = new MyTask();
            task.msg1 = extras.getString("cat_name");
            task.execute();


    //    }
    }

    private class MyTask extends AsyncTask<Void, Void, Void>{
        public String msg1;
        public MyTask (String msg1) {
            this.msg1 = msg1;
        }
        @Override
        protected Void doInBackground(Void... arg0) {
            try {
        //  URL rssUrl = new URL("http://160.99.61.22/pushapp/category/Katarina/feed/");
              URL rssUrl = new URL("http://160.99.61.22/pushapp/category/" + msg1 + "/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 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);
    }
}

为什么总是在后台的Asynctask字符串msg1是空的部分?

将参数传递给异步任务,如下所示:

MyTask task = new MyTask();
t.doInBackground("hello");
private class MyTask extends AsyncTask<String, Void, Void>
{
    @Override
    protected Void doInBackground(String... params)
    {
        String msg1 = params[0];
        return null;
    }
}

最新更新