3

I'm running a TwitterStream in my app, which runs fine, but keeps running even when I close the app (i.e.e when the app lifecycle enters pause or stop). I'm thinking it's not being a good citizen by doing that, so I'm trying to get it to start/stop based on the lifecycle.

Here is my code to start the app:

 @Override
public void onStart(){
    super.onStart();
    Log.i("ONSTART IS CALLED", String.valueOf(twitterConfig));
    initiateTwitterStream();

}

private void initiateTwitterStream() {
    FilterQuery query = new FilterQuery();
    String keywords[] = {"#Ferguson"};
    query.track(keywords);
    twitterStream = new TwitterStreamFactory(twitterConfig).getInstance();
    UserStreamListener listener = new UserStreamListener() {
        @Override
        public void onStatus(final Status status) {
            Log.i("STATUS", status.getUser().getName() + " : " + status.getText());
            getActivity().runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    Log.i("STATUS ON UI THREAD", String.valueOf(Looper.getMainLooper().getThread() == Thread.currentThread()));
                    mAdapter.insert(status.getText(), 0);
                    mAdapter.notifyDataSetChanged();
                }
            });

        }

        @Override
        public void onDeletionNotice(long directMessageId, long userId) {

        }

        @Override
        public void onFriendList(long[] friendIds) {

        }

        @Override
        public void onFavorite(User source, User target, Status favoritedStatus) {

        }

        @Override
        public void onUnfavorite(User source, User target, Status unfavoritedStatus) {

        }

        @Override
        public void onFollow(User source, User followedUser) {

        }

        @Override
        public void onUnfollow(User source, User unfollowedUser) {

        }

        @Override
        public void onDirectMessage(DirectMessage directMessage) {

        }

        @Override
        public void onUserListMemberAddition(User addedMember, User listOwner, UserList list) {

        }

        @Override
        public void onUserListMemberDeletion(User deletedMember, User listOwner, UserList list) {

        }

        @Override
        public void onUserListSubscription(User subscriber, User listOwner, UserList list) {

        }

        @Override
        public void onUserListUnsubscription(User subscriber, User listOwner, UserList list) {

        }

        @Override
        public void onUserListCreation(User listOwner, UserList list) {

        }

        @Override
        public void onUserListUpdate(User listOwner, UserList list) {

        }

        @Override
        public void onUserListDeletion(User listOwner, UserList list) {

        }

        @Override
        public void onUserProfileUpdate(User updatedUser) {

        }

        @Override
        public void onBlock(User source, User blockedUser) {

        }

        @Override
        public void onUnblock(User source, User unblockedUser) {

        }


        @Override
        public void onDeletionNotice(StatusDeletionNotice statusDeletionNotice) {

        }

        @Override
        public void onTrackLimitationNotice(int numberOfLimitedStatuses) {

        }

        @Override
        public void onScrubGeo(long userId, long upToStatusId) {

        }

        @Override
        public void onStallWarning(StallWarning warning) {

        }

        @Override
        public void onException(Exception ex) {

        }
    };
    twitterStream.addListener(listener);
    twitterStream.filter(query);
}

Here is the code to stop the app (I commented out the twitterstream.shutdown line as not necessary since I do call on the twitterstream again later):

 @Override
public void onStop(){
    Log.i("ONSTOP IS CALLED", String.valueOf(twitterConfig));
  twitterStream.cleanUp();
  //  twitterStream.shutdown();
    super.onStop();
}

NOTE: the Twitter authentication happens in the onCreate method as follows:

 @Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_tweet, container, false);

    // Set the adapter
    mListView = (AbsListView) view.findViewById(android.R.id.list);
    mTweetCompose = (EditText) view.findViewById(R.id.comptwitter);
    ((AdapterView<ListAdapter>) mListView).setAdapter(mAdapter);

    Log.i("THE VIEW IS CREATED", "BUT WHEN?");
    TwitterSession session =
            Twitter.getSessionManager().getActiveSession();
    TwitterAuthToken authToken = session.getAuthToken();
    mTtoken = authToken.token;
    mSecret = authToken.secret;
    ConfigurationBuilder cb = new ConfigurationBuilder();
    cb.setDebugEnabled(true)
            .setOAuthConsumerKey(TWITTER_KEY)
            .setOAuthConsumerSecret(TWITTER_SECRET)
            .setOAuthAccessToken(mTtoken)
            .setOAuthAccessTokenSecret(mSecret);
    twitterConfig = cb.build();
    //Set up Twitter Stream

    //Set up Tweet Composing
    initiateTwitterCompose();
    return view;
}

Note that the code runs fine if I put the initiateTwitterStream method in the oncreate method - so I'm guessing the error I get is due to the asynchronous code being misaligned between the activity stopping and starting.

Here is the error code:

01-31 22:19:04.186  26728-26737/com.example.lgorse.cineios_test A/libc﹕ Fatal signal 11 (SIGSEGV) at 0x00000008 (code=1), thread 26737 (FinalizerDaemon)

Any more information required - please ask. Look forward to hearing from you.

Laurent
  • 1,554
  • 19
  • 42
  • please check this answer - http://stackoverflow.com/questions/18016532/stop-the-twitter-stream-and-return-list-of-status-with-twitter4j – mbaxi Feb 03 '15 at 09:08
  • were you able to receive statuses in onStatus function using 3G data ? I am currently using it on 3G data and I have not received a single status however I receiving onfollow events. You think it is problem with network speed. ? – Pranjal Sahu Jul 28 '15 at 20:18
  • 1
    @sahu I don't think so. I've throttled my connection to 3G in test environment and still received data. – Laurent Jul 28 '15 at 21:28
  • It is ok I started receiving data after some time. It wasn't actually in real time but I got a bunch of tweets together after waiting for sometime. Thanks – Pranjal Sahu Jul 29 '15 at 05:47

0 Answers0