应用程序关闭时,Android服务实例化两次。(Twitter4j)

时间:2014-10-09 17:54:06

标签: android twitter service twitter4j

我遇到问题,当我通过手机上的任务管理器关闭我的应用程序时,我的服务再次注册。这是我的代码。

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;
    }
}
}

在我的片段课程的onCreate中,我有这个内容。

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

我在服务中放入一个日志,看看它是我的广播接收器还是服务,但我不断从服务中获取多个日志。如何防止我的服务多次实例化?

1 个答案:

答案 0 :(得分:2)

onStartCommand()的默认返回值为START_STICKY,其中指出:

  

如果此服务的进程在启动时被终止(从onStartCommand(Intent,int,int)返回后),则将其保留在启动状态但不保留此传递的意图。 稍后系统会尝试重新创建服务。

因此,当您关闭应用程序时,Android系统会自动重启您的服务。如果您不希望这种情况发生,您可以返回START_NOT_STICKY(或在特殊情况下START_REDELIVER_INTENT),而不是致电super.onStartCommand()

请注意,每次调用onStartCommand()(或系统为您重新启动服务)时都会调用startService()。如果您希望在服务的整个生命周期内只运行一次,那么您应该将其放在onCreate()调用中。