我已经实现了twitter4j的用户流监听器(3.0.6快照)作为服务(在启动和用户存在的情况下运行)并且代码工作正常,但在我的Android应用程序中我有随机关闭流的问题。 抛出异常420:“使用相同的帐户名运行相同应用程序身份验证的太多副本”。 有没有办法解决这个问题,或者这是一个普遍问题,因为具有不同IP的用户必须在一个Twitter应用程序中使用相同的凭据登录? 大约有40个用户正在运行我的应用...
这是我的代码:
TwitterConnectionManager.java
public class TwitterConnectionManager {
private static final String TAG = TwitterConnectionManager.class.getSimpleName();
public static final String TWITTER_USER = "";
public static final String TWITTER_CONSUMER_KEY = "";
public static final String TWITTER_CONSUMER_SECRET = "";
public static final String TWITTER_ACCESS_TOKEN = "";
public static final String TWITTER_ACCESS_TOKEN_SECRET = "";
private static Twitter instance = null;
private static Configuration conf = null;
private static Authorization auth = null;
public static Twitter getInstance() {
if (instance == null) {
instance = getTwitterConnection();
}
return instance;
}
public TwitterConnectionManager() {
}
public static Twitter getTwitterConnection() {
authorize();
Twitter twitter = new TwitterFactory().getInstance(auth);
return twitter;
}
private static void authorize() {
try {
ConfigurationBuilder cb = new ConfigurationBuilder();
cb.setOAuthConsumerKey(TWITTER_CONSUMER_KEY);
cb.setOAuthConsumerSecret(TWITTER_CONSUMER_SECRET);
cb.setOAuthAccessToken(TWITTER_ACCESS_TOKEN);
cb.setOAuthAccessTokenSecret(TWITTER_ACCESS_TOKEN_SECRET);
if (conf == null) {
conf = cb.build();
if (auth == null) {
auth = AuthorizationFactory.getInstance(conf);
}
}
}
catch (Exception e) {
Log.i(TAG, "Error authenticate Twitter: " + e.toString());
}
}
public static TwitterStream getTwitterStreamConnection(UserStreamListener listener) {
TwitterStream ts = getTwitterStreamConnection();
ts.addListener(listener);
return ts;
}
public static TwitterStream getTwitterStreamConnection() {
authorize();
TwitterStream ts = new TwitterStreamFactory().getInstance(auth);
return ts;
}
}
TwitterService.java
public final class TwitterService extends Service {
private static final String TAG = TwitterService.class.getSimpleName();
private static NotificationManager notificationManager = null;
private static SharedPreferences prefs = null;
private static AudioManager audioManager = null;
private static TwitterStream twitterStream = null;
private static ConnectThread connectThread = null;
//private Twitter twitter = null;
static final long MILLISECOND = 1000;
public class MyServiceLocalBinder extends Binder {
TwitterService getService() {
return TwitterService.this;
}
}
private final IBinder mBinder = new MyServiceLocalBinder();
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return mBinder;
}
@Override
public void onStart(Intent intent, int StartId) {
Log.i(TAG, "Starting twitter service");
if (!isConnected()) {
connectThread = new ConnectThread();
connectThread.start();
}
}
@Override
public boolean onUnbind(Intent intent) {
Log.i(TAG, "onUnbind");
twitterStream.shutdown();
super.onUnbind(intent);
stopSelf();
return true;
}
public boolean isConnected() {
if (connectThread != null && twitterStream != null) {
return true;
}
return false;
}
@Override
public void onDestroy() {
stopSelf();
twitterStream.shutdown();
}
@Override
public void onCreate() {
super.onCreate();
// ***** ONLY for debugging *****//
// android.os.Debug.waitForDebugger();
// Get the system parameters
prefs = PreferenceManager.getDefaultSharedPreferences(this);
notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
}
@SuppressLint("NewApi")
private void setNotification(String txt) {
// Check the common preferences for notification
if (prefs.getBoolean("ckbPrefNotify", true)) {
Intent notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP | Intent.FLAG_ACTIVITY_CLEAR_TOP);
Notification.Builder mBuilder = new Notification.Builder(getApplicationContext());
mBuilder.setAutoCancel(true);
mBuilder.setSmallIcon(R.drawable.ic_launcher);
mBuilder.setContentTitle(getResources().getString(R.string.appName));
mBuilder.setContentText(txt);
// Get ringer mode
int ringerMode = audioManager.getRingerMode();
// Check sound preferences
if (ringerMode == AudioManager.RINGER_MODE_NORMAL && prefs.getBoolean("ckbPrefSoundNotify", false) == true) {
playSound();
}
// Check vibration preferences
if (ringerMode != AudioManager.RINGER_MODE_SILENT && prefs.getBoolean("ckbPrefVibrationNotify", false) == true) {
long[] pattern = { 0, 200, 80, 800, 80, 200, 80, 200 };
mBuilder.setVibrate(pattern);
}
PendingIntent pi = PendingIntent.getActivity(this, 0, notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
mBuilder.setContentIntent(pi);
notificationManager.notify(1, mBuilder.build());
}
}
private void playSound() {
MediaPlayer mp = new MediaPlayer();
AssetFileDescriptor descriptor = null;
try {
descriptor = this.getAssets().openFd("sounds/owl_01.mp3");
mp.setDataSource(descriptor.getFileDescriptor(), descriptor.getStartOffset(), descriptor.getLength());
descriptor.close();
mp.prepare();
} catch (Exception e) {
Log.e(TAG, "Unable to play audio file: " + e.getMessage());
e.printStackTrace();
}
mp.start();
}
private class ConnectThread extends Thread {
public void run() {
if (twitterStream != null) {
twitterStream.cleanUp();
twitterStream.shutdown();
twitterStream = null;
}
startStreaming();
}
}
private void startStreaming() {
// Get the stream
twitterStream = TwitterConnectionManager.getTwitterStreamConnection();
if (twitterStream != null) {
// Add the listeners
twitterStream.addListener(new MyUserStreamAdapter());
try {
Log.i(TAG, "Start connectStream() for twitterStream.user()");
twitterStream.user();
}
catch (java.lang.IllegalStateException illstaex) {
Log.e(TAG, "ConnectThread connectStream() IllegalStateException illstaex=" + illstaex);
connectThread = null;
twitterStream = null;
}
}
else {
Log.e(TAG, "ConnectThread connect() got no twitter stream");
connectThread = null;
}
}
private class MyUserStreamAdapter extends UserStreamAdapter {
@Override
public void onStatus(Status status) {
super.onStatus(status);
if (status.getUser().getScreenName().equalsIgnoreCase(TwitterConnectionManager.TWITTER_USER)) {
String text = status.getText();
Log.i(TAG, "onStatus(): " + text);
setNotification(status.getText());
}
}
}
}