package com.ved.musicmapapp;
import java.util.List;
import org.json.JSONException;
import org.json.JSONObject;
import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.view.View;
import android.widget.Toast;
import com.google.android.gcm.GCMBaseIntentService;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.FailReason;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.listener.ImageLoadingListener;
import com.ved.musicmapapp.Objects.User;
import com.ved.musicmapapp.receiver.FollowedBroadcastReceiver;
import com.ved.musicmapapp.receiver.LikeBroadcastReceiver;
import com.ved.musicmapapp.utils.ServerUtilities;
import com.ved.musicmapapp.utils.SettingsManager;
import com.ved.musicmapapp.utils.Statics;
public class GCMIntentService extends GCMBaseIntentService {
private static int mId = 1;
private static final String TAG = "GCMIntentService";
private long whenChanged = 0;
public GCMIntentService() {
super(Statics.GCM_SENDER_ID);
}
/**
* Method called on device registered
**/
@Override
protected void onRegistered(Context context, String registrationId) {
SharedPreferences prefs = getSharedPreferences("MUSIC_MAP",
MODE_PRIVATE);
ServerUtilities.register(context, prefs.getString("FB_ID", ""),
registrationId);
}
/**
* Method called on device un registred
* */
@Override
protected void onUnregistered(Context context, String registrationId) {
Log.i(TAG, "Device unregistered");
ServerUtilities.unregister(context, registrationId);
}
/**
* Method called on Receiving a new message
* */
@Override
protected void onMessage(Context context, Intent intent) {
Log.i(TAG, "Received message");
String message = intent.getExtras().getString("message");
Log.i("Men", "Received message: " + message);
Log.i("check", "Notification ::///"+SettingsManager.getInstance(this).isShowNotification());
if (message != null && SettingsManager.getInstance(this).isShowNotification()) {
// notifies user
try {
JSONObject messageJSON = new JSONObject(message);
String type = messageJSON.getString("type");
/*if(type.equals("logout")){
context.sendBroadcast(new Intent(
Statics.ACTION_LOGOUT));
}else */
if (type.equals("like")) { // LIKE
context.sendBroadcast(new Intent(
LikeBroadcastReceiver.ACTION));
} else if (type.contains("follow")) { // FOLLOW
JSONObject userJSON = messageJSON.getJSONObject("user");
String fbid = userJSON.getString("fbid");
User user = Statics.hashUsers == null ? null
: Statics.hashUsers.get(fbid);
boolean isFollowed = false;
if (type.equals("follow")
&& SettingsManager.getInstance(context)
.isShowNotification()) {
generateNotification(context, messageJSON);
isFollowed = true;
if (user != null) {
user.setFollowMe(true);
}
} else {
// unfollow
if (user != null) {
user.setFollowMe(false);
}
}
if (messageJSON.has("no_follow")) {
int noFollow = messageJSON.getInt("no_follow");
Intent followReceived = new Intent();
followReceived
.setAction(FollowedBroadcastReceiver.ACTION);
followReceived.putExtra("no_follow", noFollow);
followReceived.putExtra("fb_id", fbid);
followReceived.putExtra("followed", isFollowed);
context.sendBroadcast(followReceived);
}
} else if (type.equals("mChanges")) {
// Send broadcast sang service sau do trog nay goi ham
// syncSong
Intent send = new Intent(
"com.ved.musicmapapp.service.syncsong");
context.sendBroadcast(send);
generateNotificationChanges(context, messageJSON);
}
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* Method called on receiving a deleted message
* */
@Override
protected void onDeletedMessages(Context context, int total) {
Log.i(TAG, "Received deleted messages notification");
}
/**
* Method called on Error
* */
@Override
public void onError(Context context, String errorId) {
Log.i(TAG, "Received error: " + errorId);
}
@Override
protected boolean onRecoverableError(Context context, String errorId) {
// log message
Log.i(TAG, "Received recoverable error: " + errorId);
return super.onRecoverableError(context, errorId);
}
/**
* Issues a notification to inform the user that server has sent a message.
*/
private void generateNotification(final Context context,
JSONObject messageJSON) {
try {
final long when = Long.parseLong(messageJSON.getString("time")) * 1000;
final String msg = messageJSON.getString("message");
//final String follow_fbid = messageJSON.getString("follow_fbid");
// get no_follow
JSONObject userJSON = messageJSON.getJSONObject("user");
final String fbid = userJSON.getString("fbid");
// final String userName = userJSON.getString("full_name");
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheInMemory(true).cacheOnDisc(true)
.bitmapConfig(Bitmap.Config.RGB_565).build();
ImageLoader.getInstance().loadImage(
"https://graph.facebook.com/" + fbid
+ "/picture?type=large", options,
new ImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
}
@Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
Bitmap icon = BitmapFactory.decodeResource(
context.getResources(),
R.drawable.default_avatar);
showNotification(context, fbid, msg, when,
icon);
}
@Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage) {
showNotification(context, fbid, msg, when,
loadedImage);
}
@Override
public void onLoadingCancelled(String imageUri,
View view) {
Bitmap icon = BitmapFactory.decodeResource(
context.getResources(),
R.drawable.default_avatar);
showNotification(context, fbid, msg, when,
icon);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void generateNotificationChanges(final Context context,
JSONObject messageJSON) {
try {
final String msg = messageJSON.getString("message");
try {
whenChanged = messageJSON.getLong("time") * 1000;
} catch (Exception e) {
whenChanged = Long.parseLong(messageJSON.getString("time")) * 1000;
}
JSONObject userJSON = messageJSON.getJSONObject("user");
int size = Statics.PixelFromDp(context, 50);
final String fbid = userJSON.getString("fbid");
DisplayImageOptions options = new DisplayImageOptions.Builder()
.cacheInMemory(true).cacheOnDisc(true)
.bitmapConfig(Bitmap.Config.RGB_565).build();
ImageLoader.getInstance().loadImage(
"https://graph.facebook.com/" + fbid
+ "/picture?type=large", new ImageSize(size, size),
options, new ImageLoadingListener() {
@Override
public void onLoadingStarted(String imageUri, View view) {
}
@Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
Bitmap icon = BitmapFactory.decodeResource(
context.getResources(),
R.drawable.default_avatar);
showNotification(context, fbid, msg, whenChanged, icon
);
}
@Override
public void onLoadingComplete(String imageUri,
View view, Bitmap loadedImage) {
showNotification(context, fbid, msg, whenChanged,
loadedImage);
}
@Override
public void onLoadingCancelled(String imageUri,
View view) {
Bitmap icon = BitmapFactory.decodeResource(
context.getResources(),
R.drawable.default_avatar);
showNotification(context, fbid, msg, whenChanged, icon);
}
});
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private void showNotification(Context context, String fbId, String msg,
long when, Bitmap icon) {
icon = cropBitmap(icon);
NotificationManager notificationManager = (NotificationManager) context
.getSystemService(Context.NOTIFICATION_SERVICE);
Intent notificationIntent;
ActivityManager am = (ActivityManager) context
.getSystemService(Context.ACTIVITY_SERVICE);
int check = 2; // Closed
List<RunningTaskInfo> arrs = am.getRunningTasks(Integer.MAX_VALUE);
if(arrs.size() > 0 && arrs.get(0).topActivity.getPackageName().equals(context.getPackageName())){
check = 0; // Running
}else{
for (RunningTaskInfo item : arrs) {
if(item.topActivity.getPackageName().equals(context.getPackageName())){
check = 1; // In Background
break;
}
}
}
MainActivity.FROM_GCM = false;
MainActivity.FB_ID_GCM = "";
PendingIntent resultPendingIntent;
if (check == 0) {
notificationIntent = new Intent(
MainActivity.BROAST_CAST_VIEW_USER_DETAIL);
notificationIntent.putExtra("FOLLOW_FBID", fbId);
notificationIntent.setFlags(Intent.FLAG_ACTIVITY_BROUGHT_TO_FRONT);
resultPendingIntent = PendingIntent.getBroadcast(context,
mId, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
} else if(check == 1){
MainActivity.FROM_GCM = true;
MainActivity.FB_ID_GCM = fbId;
notificationIntent = new Intent(this, MainActivity.class);
resultPendingIntent = PendingIntent.getActivity(context,
mId, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
}else{
notificationIntent = new Intent(this, MainActivity.class);
notificationIntent.putExtra("FOLLOW_FBID", fbId);
// MainActivity.FROM_GCM = true;
// MainActivity.FB_ID_GCM = fbId;
resultPendingIntent = PendingIntent.getActivity(context,
mId, notificationIntent, Intent.FLAG_ACTIVITY_NEW_TASK);
}
NotificationCompat.Builder builder = new NotificationCompat.Builder(
context).setContentTitle(context.getString(R.string.app_name))
.setContentText(msg).setSmallIcon(R.drawable.appicon)
.setWhen(when).setContentIntent(resultPendingIntent)
.setLargeIcon(icon);
Notification notification = builder.build();
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notification.defaults |= Notification.DEFAULT_SOUND;
// notification.sound = Uri.parse("android.resource://" +
// context.getPackageName() + "your_sound_file_name.mp3");
notification.defaults |= Notification.DEFAULT_VIBRATE;
notificationManager.notify(mId, notification);
mId++;
}
private Bitmap cropBitmap(Bitmap source) {
int bWidth = source.getWidth();
int bHeight = source.getHeight();
int size = Math.min(bWidth, bHeight);
int width, height;
if (android.os.Build.VERSION.SDK_INT >= 11) {
height = (int) getApplicationContext().getResources().getDimension(
android.R.dimen.notification_large_icon_height);
width = (int) getApplicationContext().getResources().getDimension(
android.R.dimen.notification_large_icon_width);
} else {
width = (int) Statics.PixelFromDp(getApplicationContext(), 50);
height = width;
}
if (size == bWidth) {
return Bitmap.createScaledBitmap(Bitmap.createBitmap(source, 0,
(bHeight - size) / 2, size, size), width, height, true);
} else {
return Bitmap.createScaledBitmap(Bitmap.createBitmap(source,
(bWidth - size) / 2, 0, size, size), width, height, true);
}
}
}