Search code examples
androidtwitterservicetwitter4j

Android Service Instantiating Twice When App Closes.(Twitter4j)


I am having a problem where my service is registering again when I close my application through the task manager on my phone. Here is my Code.

Notification_Service

import java.io.IOException;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import twitter4j.DirectMessage;
import twitter4j.MediaEntity;
import twitter4j.StallWarning;
import twitter4j.Status;
import twitter4j.StatusDeletionNotice;
import twitter4j.TwitterStream;
import twitter4j.TwitterStreamFactory;
import twitter4j.User;
import twitter4j.UserList;
import twitter4j.UserStreamListener;
import twitter4j.auth.AccessToken;
import twitter4j.conf.ConfigurationBuilder;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.content.LocalBroadcastManager;
import android.util.Log;
import com.parse.ParseTwitterUtils;

public class Notification_Service extends Service{

@Override
public IBinder onBind(Intent intent) {
    // TODO Auto-generated method stub
    return null;
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
    TwitterStream twitterStream = new TwitterStreamFactory(new ConfigurationBuilder().setJSONStoreEnabled(true).build()).getInstance();
    twitterStream.setOAuthConsumer(ParseTwitterUtils.getTwitter().getConsumerKey(), ParseTwitterUtils.getTwitter().getConsumerSecret());
    AccessToken token = new AccessToken(ParseTwitterUtils.getTwitter().getAuthToken(), ParseTwitterUtils.getTwitter().getAuthTokenSecret());
    twitterStream.setOAuthAccessToken(token);
    twitterStream.addListener(listener);
    twitterStream.user();
    return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    super.onDestroy();
}

UserStreamListener listener = new UserStreamListener() {

    @Override
    public void onDeletionNotice(StatusDeletionNotice arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onScrubGeo(long arg0, long arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStallWarning(StallWarning arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onStatus(final Status status) {
        // TODO Auto-generated method stub
        if(status.getText().contains("@" + ParseTwitterUtils.getTwitter().getScreenName())){
            Notify(status.getUser().getScreenName(), status.getUser().getScreenName(), status.getText());
        }

        Intent intent = new Intent("com.receiveTweet.GrabTweets");
          intent.putExtra("tweet_id", status.getId());
          /*if(status.isFavorited()){
                intent.putExtra("tweetIsFavorited", true);
            }else{
                intent.putExtra("tweetIsFavorited", false);
            }
            */
          if(status.isRetweet()){
          intent.putExtra("tweet", status.getRetweetedStatus().getText());
          }else{
          intent.putExtra("tweet", status.getText());
          }
          intent.putExtra("tweet_name", status.getUser().getName());
          intent.putExtra("tweet_screenname", status.getUser().getScreenName());
          intent.putExtra("tweet_profilepicture", status.getUser().getProfileImageURL());
          MediaEntity []mediaEntities = status.getMediaEntities();
             if (mediaEntities != null && status.getMediaEntities().length>0) {
                 Log.d("MediaEntities","getMediaEntities not null");                                         //just for testing
                 if (mediaEntities.length > 0) {
                     Log.d("MediaEntities","getMediaEntities not null"); 
                   intent.putExtra("tweetPicture", mediaEntities[0].getMediaURL().toString());

                 }
                 }
          LocalBroadcastManager.getInstance(getApplicationContext()).sendBroadcast(intent);
    }

    @Override
    public void onTrackLimitationNotice(int arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onException(Exception arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onBlock(User arg0, User arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onDeletionNotice(long arg0, long arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onDirectMessage(DirectMessage arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onFavorite(User arg0, User arg1, Status arg2) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onFollow(User arg0, User arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onFriendList(long[] arg0) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUnblock(User arg0, User arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUnfavorite(User arg0, User arg1, Status arg2) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUnfollow(User arg0, User arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUserListCreation(User arg0, UserList arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUserListDeletion(User arg0, UserList arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUserListMemberAddition(User arg0, User arg1, UserList arg2) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUserListMemberDeletion(User arg0, User arg1, UserList arg2) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUserListSubscription(User arg0, User arg1, UserList arg2) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUserListUnsubscription(User arg0, User arg1, UserList arg2) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUserListUpdate(User arg0, UserList arg1) {
        // TODO Auto-generated method stub

    }

    @Override
    public void onUserProfileUpdate(User arg0) {
        // TODO Auto-generated method stub

    }
};

 private void Notify(String user,String notificationTitle, String notificationMessage) {
     Uri defaultSound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
     NotificationCompat.Builder builder =  
                new NotificationCompat.Builder(this)  
                .setSmallIcon(R.drawable.ic_launcher)  
                .setTicker("You've Been Mention In A Tweet")
                .setSound(defaultSound)
                .setContentTitle(notificationTitle) 
                .setContentText(notificationMessage);  

        Intent notificationIntent = new Intent(this, MainActivity.class);  
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent,   
                PendingIntent.FLAG_UPDATE_CURRENT);  
        builder.setContentIntent(contentIntent);  

        // Add as notification  
        NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);  
        manager.notify(908596, builder.build());  
     }


public void cancelNotification(int notificationId){

    if (Context.NOTIFICATION_SERVICE!=null) {
        String ns = Context.NOTIFICATION_SERVICE;
        NotificationManager nMgr = (NotificationManager) getApplicationContext().getSystemService(ns);
        nMgr.cancel(908596);
    }
}
public Bitmap getBitmapFromURL(String strURL) {
    try {
        URL url = new URL(strURL);
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoInput(true);
        connection.connect();
        InputStream input = connection.getInputStream();
        Bitmap myBitmap = BitmapFactory.decodeStream(input);
        return myBitmap;
    } catch (IOException e) {
        e.printStackTrace();
        return null;
    }
}
}

In my onCreate of my Fragment class,I have this inside.

getActivity().startService(new Intent(getActivity(), Notification_Service.class));

I put a log inside of the service to see if it was my broadcast receiver or the service,but I keep getting multiple logs from the service. How can I prevent my service from instantiating multiple times?


Solution

  • The default return value for onStartCommand() is START_STICKY which states:

    if this service's process is killed while it is started (after returning from onStartCommand(Intent, int, int)), then leave it in the started state but don't retain this delivered intent. Later the system will try to re-create the service.

    Therefore when you close the application, the Android system is automatically restarting your service. If you'd prefer this not to happen, you can return START_NOT_STICKY (or in special cases START_REDELIVER_INTENT) instead of calling super.onStartCommand().

    Note that onStartCommand() is called every time you call startService() (or the system restarts your service for you). If you want something to run only once for the entire lifecycle of your service, then you should put that in the onCreate() call.