My application receives messages from GCM.
I have configured a service and a broadcastreceiver correctly. Then, when a message is comming, I show a notification. I have differents notifications for different kind of messages. This runs fine.
Well, now I need to update the notification when a new message is received, such as Whatsapp.
For example, when Whatsapp receives one message from a contact, shows text message, "Hello world!" but when receive another one from same contact, changes the information on notification, showing "Two new messages". If receive message from other contact, notification shows "3 messages on 2 chats" and something like that.
I need to do the same with two type of messages but not all. Then, I need to know which notifications are showing the actionBar and then update ones and no others. I would like to create a bucle for all notifications showed, analyze them and check if there are anyone showed yet of my specific type, previously to create new one.
How can I get info from the notificationManager or StatusActionBar in order to change it? How can I check if the notification showed on Actionbar has the same type of notification comming?
Thanks.
GCMIntentService.java
This service analyze an "extra" value from GCM Message (notificationType). Make a switch case and composes data for show in notification.
Has a method to show the notification. I have put some comments on showNotification method for understad what I need.
public class GCMIntentService extends IntentService {
private String TAG = this.getClass().getSimpleName();
private SQLiteDatabase localDB;
private SharedPreferences localSettings;
public GCMIntentService() {
super(StaticValues.GOOGLE_PROJECT_NUMBER);
}
#Override
protected void onHandleIntent(Intent intent) {
Bundle extras = intent.getExtras();
int gcmNotificationType;
String gcmMess;
long gcmUserIDFrom;
long gcmUserIDTo;
String gcmUserFromCode;
String gcmEventShortDescription;
boolean showNotification = false;
GoogleCloudMessaging gcm = GoogleCloudMessaging.getInstance(this);
String messageType = gcm.getMessageType(intent);
if (!extras.isEmpty()) {
if (GoogleCloudMessaging.MESSAGE_TYPE_MESSAGE.equals(messageType)) {
// Hay notificaciones de varios tipos así que las catalogamos y hacemos cosas diferentes en función del tipo
// Hay que recuperar los settings para saber qué notificaciones se tratan y cuáles no.
if (extras.getString("notificationType") != null) {
gcmNotificationType = Integer.valueOf(extras.getString("notificationType"));
gcmMess = extras.getString("message");
gcmEventShortDescription = extras.getString("eventShortDescription");
gcmUserFromCode = getString(R.string.app_name);
Log.d(TAG, "NotificationType: " + gcmNotificationType);
localSettings = getSharedPreferences(StaticValues.PREFS, 0);
switch (gcmNotificationType) {
case StaticValues.NOTIFICATION_MESSAGE_SINGLE:
Log.d(TAG, "Message received from " + extras.getString("userFromCode"));
localDB = PassObjects.getLocalDB();
gcmUserFromCode = extras.getString("userFromCode");
gcmUserIDFrom = Long.valueOf(extras.getString("userIDFrom"));
gcmUserIDTo = Long.valueOf(extras.getString("userIDTo"));
String inDate;
inDate = FormatValidators.convertTimeStampToString();
GenericMessageMethods.addMessages(gcmUserIDFrom, gcmUserIDTo, gcmMess, inDate, getApplicationContext(), localDB, false);
// Sólo llamo a la cola de broadcast de la pantalla
// si el mensaje es para el perfil en uso
if (gcmUserIDTo == PassObjects.getLOG_INFO_LAST_USER_ID()) {
Intent chatIntent = new Intent("com.example.JourneyApp.journeyActivities.LocalMessagesActivity");
chatIntent.putExtra("userIDFrom",extras.getString("userIDFrom"));
chatIntent.putExtra("userIDTo", extras.getString("userIDTo"));
chatIntent.putExtra("message", extras.getString("message"));
chatIntent.putExtra("messageDate", inDate);
sendBroadcast(chatIntent);
}
if (localSettings.getBoolean("TMP_NOTIFY_MESSAGES_FLAG",true)) {
if (localSettings.getBoolean("NOTIFY_MESSAGES_FLAG",true)) {
showNotification = true;
} else {
Log.d(TAG, "Notifications desactivated: "
+ "MessagesFlag: " + localSettings.getBoolean("NOTIFY_MESSAGES_FLAG",true));
}
} else {
Log.d(TAG, "Notifications TEMPORALLY desactivated. " +
" Processing messages with LocalMessagesActivity running");
}
break;
case StaticValues.NOTIFICATION_MESSAGE_ON_EVENT_ALL_ON_LINE:
Log.d(TAG, "Message received on event " + gcmEventShortDescription + " from " + extras.getString("userFromCode"));
gcmUserFromCode = extras.getString("userFromCode") + " " + getString(R.string.GCM_ON_EVENT) + " " + gcmEventShortDescription;
Intent foroIntent = new Intent("com.example.JourneyApp.journeyActivities.ForoMessagesActivity");
foroIntent.putExtra("userIDFrom",extras.getString("userIDFrom"));
foroIntent.putExtra("eventID", extras.getString("eventID"));
foroIntent.putExtra("message", extras.getString("message"));
foroIntent.putExtra("userFromCode", extras.getString("userFromCode"));
sendBroadcast(foroIntent);
if (localSettings.getBoolean("TMP_NOTIFY_EVENT_MESSAGES_FLAG",true)) {
if (localSettings.getBoolean("NOTIFY_EVENT_MESSAGES_FLAG",true)) {
showNotification = true;
} else {
Log.d(TAG, "Notifications desactivated: "
+ "EventMessagesFlag: " + localSettings.getBoolean("NOTIFY_EVENT_MESSAGES_FLAG",true));
}
} else {
Log.d(TAG, "Notifications TEMPORALLY desactivated: " +
" Processing messages with ForoMessagesActivity running");
}
break;
case StaticValues.NOTIFICATION_NEW_EVENT:
Log.d(TAG, getString(R.string.GCM_new_event_created) + " " + gcmEventShortDescription);
if (localSettings.getInt("NOTIFY_NEW_EVENTS_TYPE_ID",StaticValues.NOTIFICATION_ALWAYS) != StaticValues.NOTIFICATION_NEVER) {
if (localSettings.getInt("NOTIFY_NEW_EVENTS_TYPE_ID",StaticValues.NOTIFICATION_ALWAYS) == StaticValues.NOTIFICATION_ONLY_MY_INTEREST) {
if (PassObjects.getLOG_INFO_LAST_USER_ID() > 0) {
ArrayList<Integer> arrayLikesProfileLogged = PassObjects.getLOG_INFO_USER_LIKES();
ArrayList<Integer> arrayLikesOnEvent = new ArrayList<Integer>();
// Los extras están en String. Lo paso a un String[], lo recorro, parseo a int
// y añado al array. Recorro el del evento y en cuanto encuentro uno coincidente,
// salgo y muestro notificación
String extrasEventLikesString = extras.getString("eventLikes");
Log.d(TAG, "EventLikes: (string) " + extrasEventLikesString);
String[] auxS = extrasEventLikesString.replace(" ", "").split(",");
for (int i = 0; i < auxS.length; i++) {
arrayLikesOnEvent.add(Integer.parseInt(auxS[i]));
}
Log.d(TAG, "EventLikes: (ArrayList<Integer>) " + arrayLikesOnEvent.toString());
for (int x:arrayLikesOnEvent) {
if (arrayLikesProfileLogged.contains(x)) {
gcmMess = getString(R.string.mess_new_event_created);
showNotification = true;
break;
}
}
} else {
Log.d(TAG, "Notification is: " + localSettings.getInt("NOTIFY_NEW_EVENTS_TYPE_ID",StaticValues.NOTIFICATION_ALWAYS) + " but user not logged");
}
} else {
gcmMess = getString(R.string.mess_new_event_created);
showNotification = true;
}
} else {
Log.d(TAG, "Notifications desactivated: "
+ "Notify new events type: " + localSettings.getInt("NOTIFY_NEW_EVENTS_TYPE_ID", StaticValues.NOTIFICATION_ALWAYS) );
}
break;
case StaticValues.NOTIFICATION_NEW_USER:
Log.d(TAG, "New user created: " + extras.getString("userFromCode"));
if (localSettings.getInt("NOTIFY_NEW_USERS_TYPE_ID", StaticValues.NOTIFICATION_ALWAYS) != StaticValues.NOTIFICATION_NEVER) {
if (localSettings.getInt("NOTIFY_NEW_USERS_TYPE_ID", StaticValues.NOTIFICATION_ALWAYS) == StaticValues.NOTIFICATION_ONLY_MY_INTEREST) {
if (PassObjects.getLOG_INFO_LAST_USER_ID() > 0) {
ArrayList<Integer> arrayLikesProfileLogged = PassObjects.getLOG_INFO_USER_LIKES();
ArrayList<Integer> arrayLikesOnUser = new ArrayList<Integer>();
// Los extras están en String. Lo paso a un String[], lo recorro, parseo a int
// y añado al array. Recorro el del evento y en cuanto encuentro uno coincidente,
// salgo y muestro notificación
String extrasUserLikesString = extras.getString("userLikes");
Log.d(TAG, "UserLikes: (string) " + extrasUserLikesString);
String[] auxS = extrasUserLikesString.replace(" ", "").split(",");
for (int i = 0; i < auxS.length; i++) {
arrayLikesOnUser.add(Integer.parseInt(auxS[i]));
}
Log.d(TAG, "UserLikes: (ArrayList<Integer>): " + arrayLikesOnUser.toString());
for (int x:arrayLikesOnUser) {
if (arrayLikesProfileLogged.contains(x)) {
gcmMess = getString(R.string.mess_profile_created_part1);
showNotification = true;
break;
}
}
} else {
Log.d(TAG, "Notification is: " + localSettings.getInt("NOTIFY_NEW_USERS_TYPE_ID", StaticValues.NOTIFICATION_ALWAYS) + " but user not logged");
}
} else {
gcmMess = getString(R.string.mess_profile_created_part1);
showNotification = true;
}
} else {
Log.d(TAG, "Notifications desactivated: "
+ "Notify new uers type: " + localSettings.getInt("NOTIFY_NEW_USERS_TYPE_ID", StaticValues.NOTIFICATION_ALWAYS) );
}
break;
case StaticValues.NOTIFICATION_CHANGE_EVENT:
Log.d(TAG, "Changes on event: " + gcmEventShortDescription);
gcmMess = getString(R.string.GCM_changes_on_event) + " " + gcmEventShortDescription;
showNotification = true;
break;
case StaticValues.NOTIFICATION_LINK_EVENT:
Log.d(TAG, "Linked user from event: " + gcmEventShortDescription);
if (localSettings.getBoolean("NOTIFY_EVENT_LINK_FLAG", true)) {
gcmMess = getString(R.string.mess_linked) + " " + getString(R.string.GCM_ON_EVENT) + " " + gcmEventShortDescription;
showNotification = true;
} else {
Log.d(TAG, "Notifications desactivated: "
+ "Notify link event: " + localSettings.getBoolean("NOTIFY_EVENT_LINK_FLAG", true) );
}
break;
case StaticValues.NOTIFICATION_UNLINK_EVENT:
Log.d(TAG, "Unlinked user from event: " + gcmEventShortDescription);
if (localSettings.getBoolean("NOTIFY_EVENT_UNLINK_FLAG", true)) {
gcmMess = getString(R.string.mess_unlinked) + " " + getString(R.string.GCM_ON_EVENT) + " " + gcmEventShortDescription;
showNotification = true;
} else {
Log.d(TAG, "Notifications desactivated: "
+ "Notify unlink event: " + localSettings.getBoolean("NOTIFY_EVENT_UNLINK_FLAG", true) );
}
break;
case StaticValues.NOTIFICATION_EVENT_CAPACITY_FULL:
Log.d(TAG, "Capacity full on event: " + gcmEventShortDescription);
if (localSettings.getBoolean("NOTIFY_EVENT_CAPACITY_FULL_FLAG", true)) {
gcmMess = getString(R.string.GCM_event_capacity_completed) + " " + gcmEventShortDescription;
showNotification = true;
} else {
Log.d(TAG, "Notifications desactivated: "
+ "Notify event capacity full: " + localSettings.getBoolean("NOTIFY_EVENT_CAPACITY_FULL_FLAG", true));
}
break;
case StaticValues.NOTIFICATION_EVENT_WILL_BEGIN_AT:
Log.d(TAG, "Begin notification on event: " + gcmEventShortDescription);
gcmMess = getString(R.string.GCM_event_will_begin_part_1) + " " + gcmEventShortDescription + " " + getString(R.string.GCM_event_will_begin_part_2);
showNotification = true;
break;
case StaticValues.NOTIFICATION_EVENT_CANCELLED:
Log.d(TAG, "Cancel event: " + gcmEventShortDescription);
gcmMess = getString(R.string.GCM_event_canceled) + " " + gcmEventShortDescription;
showNotification = true;
break;
default:
Log.d(TAG, "Notification not in case");
break;
} //END Switch
if (showNotification) {
showNotification(gcmNotificationType, gcmMess, gcmUserFromCode);
}
} else {
Log.d(TAG, "Cannot find <notificationType> label on extras");
Log.d(TAG, "Extras.size(): " + extras.size() + ", extrasToString " + extras.toString());
}
} else {
Log.d(TAG, "Other GCM message type received");
}
} else {
Log.d(TAG, "Extras are empty");
}
GCMBroadcastReceiver.completeWakefulIntent(intent);
}
private void showNotification(int nType, String mMessage, String mTitle) {
NotificationManager mNotificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// I would like to analyze ActionBar data or NotificationManager data
// Something like...
// for (x:CurrentVisibleNotifications) { // Which will be this object?
// int currentId = x.getId();
// int currentNumber = x.getNumber(); // This is a property of notification
// if (currentId == nType) {
// mMessage = currentNumber++ + " new messages";
// }
// }
NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.journey_icon_orange)
.setContentTitle(mTitle)
.setContentText(mMessage)
.setTicker(getString(R.string.app_name))
.setAutoCancel(true)
;
// Intent notIntent = new Intent(this, MainActivity.class);
// PendingIntent contIntent = PendingIntent.getActivity(this, 0, notIntent, 0);
// mBuilder.setContentIntent(contIntent);
mNotificationManager.notify(nType, mBuilder.build());
}
For update a view when your app receive the PushNotification you need LocalBroadCastManager
http://developer.android.com/reference/android/support/v4/content/LocalBroadcastManager.html
In the Service "GCMIntentService", in the method onMessage you need add the nextCode:
Intent intent = new Intent("Reload");
// You can also include some extra data.
intent.putExtra("message", "Reload");
LocalBroadcastManager.getInstance(getApplicationContext())
.sendBroadcast(intent);
Whit this you register a new Broadcasting message.
Now in the class for update you need add the next:
in the onCreate method:
LocalBroadcastManager.getInstance(getApplicationContext())
.registerReceiver(mMessageReceiver,
new IntentFilter("Reload"));
and before you need add next methods:
private BroadcastReceiver mMessageReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
// Get extra data included in the Intent
String message = intent.getStringExtra("message");
if (message.equalsIgnoreCase("Reload")) {
//Actions...for reload a listView, TextView, etc...
}
}
};
And important add the onDestroy method:
#Override
public void onDestroy() {
// Unregister since the activity is about to be closed.
LocalBroadcastManager.getInstance(getApplicationContext())
.unregisterReceiver(mMessageReceiver);
super.onDestroy();
}
.... PD: Sorry for my English...
Related
I have developed my application using this tutorial:
http://code.tutsplus.com/tutorials/how-to-recognize-user-activity-with-activity-recognition--cms-25851
Even though I request updates every 3 seconds (or for a change, 5 seconds, 10 seconds etc); the timing of the generated values is highly inconsistent. At times it would generate 4 values in 10 minutes! Why is the API being so inconsistent? Also, I'm unable to disconnect the API, even after I call API.disconnect(), I still keep getting values in logcat, which heats up the phone and consumes battery excessively.
Here is the full project: https://github.com/AseedUsmani/MotionAnalyser2
Basic Code:
1) Activity:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_analysing);
mApiClient = new GoogleApiClient.Builder(this)
.addApi(ActivityRecognition.API)
.addConnectionCallbacks(this)
.addOnConnectionFailedListener(this)
.build();
mStartButton = (Button) findViewById(R.id.startButton);
mFinishButton = (Button) findViewById(R.id.finishButton);
mStartButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//resetting counter
for (int j = 0; j < 8; j++) {
mCount[j] = 0;
}
mServiceCount = 0;
mApiClient.connect();
mStartButton.setVisibility(View.INVISIBLE);
mFinishButton.setVisibility(View.VISIBLE);
}
}
mFinishButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mApiClient.disconnect();
}
}
}
#Override
public void onConnected(#Nullable Bundle bundle) {
Intent intent = new Intent(this, ActivityRecognizedService.class);
PendingIntent pendingIntent = PendingIntent.getService(this, 0, intent, PendingIntent.FLAG_UPDATE_CURRENT);
ActivityRecognition.ActivityRecognitionApi.requestActivityUpdates(mApiClient, 3000, pendingIntent);
}
#Override
public void onConnectionSuspended(int i) {
Toast.makeText(AnalysingActivity.this, "Connection to Google Services suspended!", Toast.LENGTH_LONG).show();
}
#Override
public void onConnectionFailed(#NonNull ConnectionResult connectionResult) {
Toast.makeText(AnalysingActivity.this, "Connection to Google Services failed!", Toast.LENGTH_LONG).show();
}
}
2) Service:
public class ActivityRecognizedService extends IntentService {
AnalysingActivity mObject = new AnalysingActivity();
int confidence;
public ActivityRecognizedService() {
super("ActivityRecognizedService");
}
public ActivityRecognizedService(String name) {
super(name);
}
#Override
protected void onHandleIntent(Intent intent) {
if (ActivityRecognitionResult.hasResult(intent)) {
ActivityRecognitionResult result = ActivityRecognitionResult.extractResult(intent);
handleDetectedActivities(result.getProbableActivities());
}
}
private void handleDetectedActivities(List<DetectedActivity> probableActivities) {
confidence = mObject.confidence;
mObject.mServiceCount++;
for (DetectedActivity activity : probableActivities) {
switch (activity.getType()) {
case DetectedActivity.IN_VEHICLE: {
if (activity.getConfidence() >= confidence) {
mObject.mCount[0]++;
}
mObject.mActivity[0] = "In Vehicle: " + Integer.toString(activity.getConfidence()) + " " + Integer.toString(mObject.mCount[0]);
Log.e("ActivityRecogition", "In Vehicle: " + activity.getConfidence() + " " + Integer.toString(mObject.mCount[0]));
break;
}
case DetectedActivity.ON_BICYCLE: {
if (activity.getConfidence() >= confidence) {
mObject.mCount[1]++;
}
mObject.mActivity[1] = "Cycling: " + Integer.toString(activity.getConfidence()) + " " + Integer.toString(mObject.mCount[1]);
Log.e("ActivityRecogition", "Cycling: " + activity.getConfidence() + " " + Integer.toString(mObject.mCount[1]));
break;
}
case DetectedActivity.ON_FOOT: {
if (activity.getConfidence() >= confidence) {
mObject.mCount[2]++;
}
mObject.mActivity[2] = "On Foot: " + Integer.toString(activity.getConfidence()) + " " + Integer.toString(mObject.mCount[2]);
Log.e("ActivityRecogition", "On foot: " + activity.getConfidence() + " " + Integer.toString(mObject.mCount[2]));
break;
}
case DetectedActivity.RUNNING: {
if (activity.getConfidence() >= confidence) {
mObject.mCount[3]++;
}
mObject.mActivity[3] = "Running: " + Integer.toString(activity.getConfidence()) + " " + Integer.toString(mObject.mCount[3]);
Log.e("ActivityRecogition", "Running: " + activity.getConfidence() + " " + Integer.toString(mObject.mCount[3]));
break;
}
case DetectedActivity.STILL: {
if (activity.getConfidence() >= confidence) {
mObject.mCount[4]++;
}
mObject.mActivity[4] = "Still: " + Integer.toString(activity.getConfidence()) + " " + Integer.toString(mObject.mCount[4]);
Log.e("ActivityRecogition", "Still: " + activity.getConfidence() + " " + Integer.toString(mObject.mCount[4]));
break;
}
case DetectedActivity.WALKING: {
if (activity.getConfidence() >= confidence) {
mObject.mCount[5]++;
}
mObject.mActivity[5] = "Walking: " + Integer.toString(activity.getConfidence()) + " " + Integer.toString(mObject.mCount[5]);
Log.e("ActivityRecogition", "Walking: " + activity.getConfidence() + " " + Integer.toString(mObject.mCount[5]));
break;
}
case DetectedActivity.TILTING: {
if (activity.getConfidence() >= confidence) {
mObject.mCount[6]++;
}
mObject.mActivity[6] = "Tilting: " + Integer.toString(activity.getConfidence()) + " " + Integer.toString(mObject.mCount[6]);
Log.e("ActivityRecogition", "Tilting: " + activity.getConfidence() + " " + Integer.toString(mObject.mCount[6]));
break;
}
case DetectedActivity.UNKNOWN: {
if (activity.getConfidence() >= confidence) {
mObject.mCount[7]++;
}
mObject.mActivity[7] = "Unknown: " + Integer.toString(activity.getConfidence()) + " " + Integer.toString(mObject.mCount[7]);
Log.e("ActivityRecogition", "Unknown: " + activity.getConfidence() + " " + Integer.toString(mObject.mCount[7]));
break;
}
}
}
}
}
Per the requestActivityUpdates() documentation:
Activities may be received more frequently than the detectionIntervalMillis parameter if another application has also requested activity updates at a faster rate. It may also receive updates faster when the activity detection service receives a signal that the current activity may change, such as if the device has been still for a long period of time and is then unplugged from a phone charger.
Activities may arrive several seconds after the requested detectionIntervalMillis if the activity detection service requires more samples to make a more accurate prediction.
And
Beginning in API 21, activities may be received less frequently than the detectionIntervalMillis parameter if the device is in power save mode and the screen is off.
Therefore you should not expect calls exactly every 3 seconds, but assume that each call you get is the start of a state change - if you haven't received any callback, it is because nothing has changed.
Also note that the correct call to stop receiving updates is removeActivityUpdates(), passing in the same PendingIntent as you passed into requestActivityUpdates().
In my project there is an option to download a set of files.To check the storage availability I used the below code
public static int getSDCardStatus() {
String extState = Environment.getExternalStorageState();
int status;
if (extState.equals(Environment.MEDIA_MOUNTED)) {
status = MOUNTED;
} else if (extState.equals(Environment.MEDIA_MOUNTED_READ_ONLY)) {
status = READ_ONLY;
} else {
status = UNMOUNTED;
}
return status;
}
private String getLoginFolders() {
// TODO Auto-generated method stub
File file = null;
int status = Constants.getSDCardStatus();
if (status == Constants.MOUNTED) {
File f = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"/SOTC_OFF/.nomedia");
f.mkdirs();
file = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"/SOTC_OFF/" + sotcPref.getString("domain", "") + "/"
+ sotcPref.getString("user_id", ""));
file.mkdirs();
}
return file.getAbsolutePath();
}
While making download in LG Nexus 4 and Samsung Nexus 4 working fine. But in Micromax a114 canvas 2.2 and Nexus 5 not working fine.
For reference the service class which I am using for download
public class DownloadService extends IntentService {
#Override
public void onDestroy() {
super.onDestroy();
if (Constants.DEBUG)
Log.i("StatusDownloadservice", "Ondestroy");
}
private int OFFSET;
private int LIMIT;
String data;
private final String TAG = "DownloadService";
private int result = Activity.RESULT_CANCELED;
public static int COMPLETED = 100;
public static int FAILED = 101;
public static int LOW_SPACE = 102;
public static int NETWORK_PROBLEM = 103;
public static int ASSERT_EXISIT = 104;
public static int PARTIALLY_DOWNLOADED = 105;
public static int NO_FILE = 105;
private NotificationManager notificationManager;
private Notification notification;
ConnectivityManager connMgr;
ArrayList<ConcurrentHashMap<String, String>> showAssetList;
RemoteViews contentView;
private SharedPreferences sotcPref;
PendingIntent contentIntent;
int downloadCount = 1;
String url;
String showname;
String showdatecreated;
String showId;
Messenger messenger;
int noofFiles;
Thread handleIntentThread = null;
Thread downloadJoinThread = null;
public Handler notifyHandler = new Handler();
int assetCount = 0;
// To track the app event
MixpanelAPI mMixpanel;
private SharedPreferences myPrefs;
// private boolean isServiceRunning=false;
public DownloadService() {
super("com.iw.sotc.show.offline.DownloadService");
if (Constants.DEBUG)
Log.d(TAG, "Offline step 5 " + "DownloadService()constructor");
if (Constants.DEBUG)
Log.d(TAG, "DownloadService... Constructor");
OFFSET = 0;
LIMIT = 3;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
super.onStartCommand(intent, flags, startId);
return START_REDELIVER_INTENT;
}
#Override
protected void onHandleIntent(Intent intent) {
if (Constants.DEBUG)
Log.i("StatusDownloadservice", "OnhandleIntent");
// Initialize the Mixpanel library for tracking and push notifications.
mMixpanel = MixpanelAPI.getInstance(this, Constants.MIXPANEL_API_TOKEN);
myPrefs = getApplicationContext().getSharedPreferences("SOTCPref",
MODE_PRIVATE);
final Intent intentCpy = intent;
// synchronized (intentCpy) {
/*
* new Thread(new Runnable() {
*
* #Override public void run() {
*/
if (Constants.DEBUG)
Log.d(TAG, "Offline step 6 " + "onHandleIntent");
connMgr = (ConnectivityManager) getApplicationContext()
.getSystemService(Context.CONNECTIVITY_SERVICE);
sotcPref = getApplicationContext().getSharedPreferences("SOTCPref",
MODE_PRIVATE);
if (Constants.DEBUG)
Log.d(TAG, "onHandleIntent.........");
Bundle extras = intentCpy.getExtras();
url = extras.getString("url");
showname = extras.getString("showname");
showdatecreated = extras.getString("showdatecreated");
// sara
if (showdatecreated.contains("/")) {
data = showdatecreated.replaceAll("/", "#");
if (Constants.DEBUG) {
System.out.println("date");
System.out.println(data);
}
} else {
data = showdatecreated;
if (Constants.DEBUG) {
System.out.println("date in else");
System.out.println(showdatecreated);
System.out.println(data);
}
}
showId = extras.getString("share_id");
noofFiles = extras.getInt("noofFiles");
messenger = (Messenger) extras.get("MESSENGER");
/*
* Intent notificationIntent = new Intent(); contentIntent =
* PendingIntent.getService( getApplicationContext(), 1,
* notificationIntent, 0);
*/
// contentIntent =
// PendingIntent.getActivity(getApplicationContext(), 0,
// notificationIntent, 0);
showNotification();
if (Constants.DEBUG)
Log.i("FOO", "Notification started");
if (showname.length() > 18)
showname = showname.substring(0, 17);
if (DownloadAssets.TOTAL_ASSET_COUNT == 0) {
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 7 "
+ "if(DownloadAssets.TOTAL_ASSET_COUNT == 0)");
Log.i("Downloadassetvalue", ""
+ DownloadAssets.TOTAL_ASSET_COUNT);
}
// TODO Auto-generated method stub
downloadSetofAssets(OFFSET, LIMIT, url);
assetCount = DownloadAssets.TOTAL_ASSET_COUNT;
if (Constants.DEBUG)
Log.d(TAG, "Offline step 7 asset count :" + assetCount);
DownloadAssets.TOTAL_ASSET_COUNT = 0;
}
if (assetCount > LIMIT) {
if (Constants.DEBUG)
Log.d(TAG, "Offline step 7.1 "
+ "if(DownloadAssets.TOTAL_ASSET_COUNT > LIMIT)");
for (OFFSET = LIMIT; OFFSET < assetCount;) {
if (Constants.DEBUG)
Log.d(TAG,
"Offline step 8.1 "
+ "for(OFFSET = LIMIT; OFFSET < DownloadAssets.TOTAL_ASSET_COUNT;)");
downloadSetofAssets(OFFSET, LIMIT, url);
OFFSET = OFFSET + LIMIT;
}
DownloadAssets.TOTAL_ASSET_COUNT = 0;
}
if (Constants.DEBUG)
Log.d(TAG, "download check :downloadJoinThread is running");
if (Constants.DEBUG)
Log.i("DownloadingStatus", "InService");
if (downloadCount >= 1) {
result = DownloadService.COMPLETED;
// to notify the changes made after the offline
// coded by Karthikeyan V
showNotificationDownloadComplete("download successful.");
Message msg = Message.obtain();
try {
if (Constants.DEBUG)
Log.i("DownloadServicestatus", "Sendmessenger");
msg.arg1 = result;
messenger.send(msg);
} catch (android.os.RemoteException e1) {
if (Constants.DEBUG)
Log.w(getClass().getName(), "Exception sending message", e1);
}
} else {
result = DownloadService.FAILED;
Message msg = Message.obtain();
msg.arg1 = result;
try {
messenger.send(msg);
} catch (RemoteException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// stopForeground(true);
/*
* notification.setLatestEventInfo(DownloadService.this,
* "Download Failed", "", contentIntent);
*/
showNotificationDownloadComplete("download failed.");
}
/*
* }
*
* }).start();
*/
/*
* //to notify the changes made after the offline
* ViewShowList.showListadapter.notifyDataSetChanged();
*/
// }
}
private void showNotificationDownloadComplete(String statusDownload) {
notificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
notification = new Notification(R.drawable.sotc_notification_icon, "",
System.currentTimeMillis());
contentView = new RemoteViews(getPackageName(),
R.layout.upload_progress_aftercomplete);
notification.flags |= Notification.FLAG_NO_CLEAR;
contentView
.setImageViewResource(R.id.imageOfflineshowCompletion, R.drawable.icon);
contentView.setTextViewText(R.id.textView1offlineshowCompletion, showname+"\t"+statusDownload);
//For click event
Intent intentOpenOfflineshows = new Intent(this,
com.iw.sotc.show.offline.ViewOfflineShows.class);
contentIntent = PendingIntent.getActivity(this, 2,
intentOpenOfflineshows, 0);
notification.flags |= Notification.FLAG_AUTO_CANCEL
| Notification.FLAG_SHOW_LIGHTS;
notification.contentIntent = contentIntent;
notification.contentView = contentView;
notificationManager.notify(1, notification);
}
private void showNotification() {
notificationManager = (NotificationManager) this
.getSystemService(Context.NOTIFICATION_SERVICE);
notification = new Notification(R.drawable.sotc_notification_icon, "",
System.currentTimeMillis());
contentView = new RemoteViews(getPackageName(),
R.layout.upload_progress_bar);
notification.flags |= Notification.FLAG_NO_CLEAR;
contentView
.setImageViewResource(R.id.imageOfflineshow, R.drawable.icon);
contentView.setTextViewText(R.id.textView1, showname);
contentView.setProgressBar(R.id.progressBar1, 100, 0, false);
notification.contentIntent = contentIntent;
notification.contentView = contentView;
notificationManager.notify(1, notification);
/*
* notificationManager = (NotificationManager) this
* .getSystemService(Context.NOTIFICATION_SERVICE); notification = new
* Notification( R.drawable.sotc_notification_icon, "", System
* .currentTimeMillis()); notification.flags = notification.flags |
* Notification.FLAG_ONGOING_EVENT; notification.flags|=
* Notification.FLAG_NO_CLEAR; notification.contentView = new
* RemoteViews( getApplicationContext().getPackageName(),
* R.layout.upload_progress_bar); notification.icon =
* R.drawable.sotc_notification_icon;
* notification.contentView.setTextViewText(R.id.textView1, showname);
* notification.contentIntent = contentIntent;
* notification.contentView.setProgressBar(R.id.progressBar1, 100, 0,
* false); notificationManager.notify(1, notification);
* startForeground(1, notification);
*/
}
private void downloadSetofAssets(int OFFSET, int LIMIT, String url) {
if (Constants.DEBUG)
Log.d(TAG, "Offline step 8 " + "downloadSetofAssets");
if (Constants.DEBUG)
try {
url = url.replace("value1",
URLEncoder.encode("" + OFFSET, "UTF-8"));
url = url.replace("value2",
URLEncoder.encode("" + LIMIT, "UTF-8"));
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (Constants.DEBUG)
Log.i(TAG, "Show offline -- Asset URL: " + url);
showAssetList = DownloadAssets.hit(getApplicationContext(), url);
for (ConcurrentHashMap<String, String> asset : showAssetList) {
String thumbUrl = asset.get("thumb_url");
// String normalUrl = asset.get("normal_url");
// added by Karthikeyan v
// To avoid downloading png file for document type files
// here just used the variable name as normalUrl for testing purpose
// // do not confuse
String largeUrl = asset.get("large_url");
String normalUrl = asset.get("normal_url");
String mp4Url = asset.get("mp4_url");
String fileType = asset.get("filetype");
String assetID = asset.get("id");
String assetType = asset.get("asset_type");
if (Constants.DEBUG)
Log.d(TAG, "Thumb Url :" + thumbUrl);
if (Constants.DEBUG)
Log.d(TAG, "Normal Url :" + normalUrl);
if (Constants.DEBUG)
Log.d(TAG, "Asset ID : " + assetID);
if (Constants.DEBUG)
Log.d(TAG, "Asset Type : " + assetType);
if (Constants.DEBUG)
Log.d(TAG, "MP4 Url : " + mp4Url);
if (Constants.DEBUG)
Log.d(TAG, "FileType : " + fileType);
if (assetType.equals("1")) { // Image
File assetDirectory = createAssetDirectory(showId, showname,
data, assetID, assetType);
if (assetDirectory != null) {
File thumb = new File(assetDirectory.getAbsolutePath(),
"/Thumb");
thumb.mkdirs();
// Thumbnail
File thumbFile = new File(thumb.getAbsolutePath(),
"/Thumb." + getExtention(thumbUrl));
if (Constants.DEBUG)
Log.d(TAG,
"Thumb File ath : "
+ thumbFile.getAbsolutePath());
doInBackground(this, thumbUrl,
thumbFile.getAbsolutePath(), messenger);
File normal = new File(assetDirectory.getAbsolutePath(),
"/Normal");
normal.mkdirs();
// Normal
File normalFile = new File(normal.getAbsolutePath(),
"/Normal." + getExtention(normalUrl));
if (Constants.DEBUG)
Log.i("NormalFilepath", normalFile.getAbsolutePath());
if (Constants.DEBUG)
Log.d(TAG,
"Normal File path: "
+ normalFile.getAbsolutePath());
doInBackground(this, normalUrl,
normalFile.getAbsolutePath(), messenger);
if (Constants.DEBUG)
Log.i("DownloadServicestatus", "DownloadComplete");
}
} else if (assetType.equals("2")) { // Video
File assetDirectory = createAssetDirectory(showId, showname,
data, assetID, assetType);
if (assetDirectory != null) {
if (!fileType.equals("Youtube")) { // via AddLink
File thumb = new File(assetDirectory.getAbsolutePath(),
"/Thumb");
thumb.mkdirs();
// Thumbnail
File thumbFile = new File(thumb.getAbsolutePath(),
"/Thumb." + getExtention(thumbUrl));
if (Constants.DEBUG)
Log.d(TAG,
"Thumb File ath : "
+ thumbFile.getAbsolutePath());
doInBackground(this, thumbUrl,
thumbFile.getAbsolutePath(), messenger);
File mp4url = new File(
assetDirectory.getAbsolutePath(), "/Normal");
mp4url.mkdirs();
// mp4_Url
File mp4File = new File(mp4url.getAbsolutePath(),
"/Normal." + getExtention(mp4Url));
if (Constants.DEBUG)
Log.d(TAG,
"Normal File path: "
+ mp4File.getAbsolutePath());
doInBackground(this, mp4Url,
mp4File.getAbsolutePath(), messenger);
if (Constants.DEBUG)
Log.i("DownloadServicestatus", "DownloadComplete");
} else if (Constants.DEBUG)
Log.d(TAG,
"Asset type is video but is Youtube link. So not proceeding for offline");
}
} else if (assetType.equals("3")) { // Audio
File assetDirectory = createAssetDirectory(showId, showname,
data, assetID, assetType);
if (assetDirectory != null) {
File thumb = new File(assetDirectory.getAbsolutePath(),
"/Thumb");
thumb.mkdirs();
// Thumbnail
File thumbFile = new File(thumb.getAbsolutePath(),
"/Thumb." + getExtention(thumbUrl));
if (Constants.DEBUG)
Log.d(TAG,
"Thumb File ath : "
+ thumbFile.getAbsolutePath());
doInBackground(this, thumbUrl,
thumbFile.getAbsolutePath(), messenger);
File normal = new File(assetDirectory.getAbsolutePath(),
"/Normal");
normal.mkdirs();
// Normal
File normalFile = new File(normal.getAbsolutePath(),
"/Normal." + getExtention(normalUrl));
if (Constants.DEBUG)
Log.d(TAG,
"Normal File path: "
+ normalFile.getAbsolutePath());
doInBackground(this, normalUrl,
normalFile.getAbsolutePath(), messenger);
if (Constants.DEBUG)
Log.i("DownloadServicestatus", "DownloadComplete");
}
} else {
if (!assetType.equals("5")) {
File assetDirectory = createAssetDirectory(showId,
showname, data, assetID, assetType);
if (assetDirectory != null) {
File thumb = new File(assetDirectory.getAbsolutePath(),
"/Thumb");
thumb.mkdirs();
// Thumbnail
File thumbFile = new File(thumb.getAbsolutePath(),
"/Thumb." + getExtention(thumbUrl));
if (Constants.DEBUG)
Log.d(TAG,
"Thumb File ath : "
+ thumbFile.getAbsolutePath());
doInBackground(this, thumbUrl,
thumbFile.getAbsolutePath(), messenger);
File normal = new File(
assetDirectory.getAbsolutePath(), "/Normal");
normal.mkdirs();
// Normal
File normalFile = new File(normal.getAbsolutePath(),
"/Normal." + getExtention(largeUrl));
if (Constants.DEBUG)
Log.i("Normal File path: ",
normalFile.getAbsolutePath());
doInBackground(this, largeUrl,
normalFile.getAbsolutePath(), messenger);
if (Constants.DEBUG)
Log.i("DownloadServicestatus", "DownloadComplete");
} else // "5" Link
{
if (Constants.DEBUG)
Log.d(TAG, "This is Web Link");
}
}
}
}
}
private String getLoginFolders() {
// TODO Auto-generated method stub
File file = null;
int status = Constants.getSDCardStatus();
if (status == Constants.MOUNTED) {
File f = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"/SOTC_OFF/.nomedia");
f.mkdirs();
file = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"/SOTC_OFF/" + sotcPref.getString("domain", "") + "/"
+ sotcPref.getString("user_id", ""));
file.mkdirs();
}
return file.getAbsolutePath();
}
private File createAssetDirectory(String showid, String showname,
String data, String assetID, String assetType) {
// TODO Auto-generated method stub
if (Constants.DEBUG)
Log.d(TAG, "Offline step 10 " + "createAssetDirectory");
File file = null;
int status = Constants.getSDCardStatus();
if (status == Constants.MOUNTED) {
if (DownloadAssets.TOTAL_ASSET_COUNT != 0) {
/**
* From to concept here is to avoid duplication of new offline
* shows when show is updated. So, we are here renaming previous
* offline show's folder name with updated asset count.
*/
boolean isRenameSuccess = false;
File f = new File(getLoginFolders());
if (!f.exists())
f.mkdirs();
File[] fileArray = f.listFiles();
File f2 = new File(getLoginFolders(), "/" + showid.trim() + ","
+ showname.trim() + "," + data);
for (File from : fileArray) {
String s1 = from.getName().substring(0,
from.getName().lastIndexOf(","));
if (Constants.DEBUG)
Log.i(TAG, "s1: " + s1);
if (f2.getName().equalsIgnoreCase(s1)) {
// Rename
File to = new File(getLoginFolders(), "/"
+ showid.trim() + "," + showname.trim() + ","
+ data + "," + noofFiles);
if (Constants.DEBUG)
Log.i(TAG, "from existence: " + from.exists());
try {
isRenameSuccess = from.renameTo(to);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (Constants.DEBUG)
Log.i(TAG, "isRenameSuccess: " + isRenameSuccess);
break;
}
}
file = new File(getLoginFolders(), "/" + showid.trim() + ","
+ showname.trim() + "," + data + "," + noofFiles
+ "/File_" + assetID + "," + assetType.trim());
}
if (file != null)
if (!file.exists())
file.mkdirs();
}
return file;
}
public static String getExtention(String url) {
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
return extension;
}
boolean doInBackground(Context context, String urlPath,
String destinationPath, Messenger messenger) {
final String desti = destinationPath;
final String url = urlPath;
final Messenger messengerCopy = messenger;
final Context cntxt = context;
/*
* new Thread(new Runnable() {
*
* #Override public void run() {
*/
if (Constants.DEBUG)
Log.d(TAG, "Offline step 9 " + "doInBackground");
// boolean isDownloaded = false;
int lastPercent = 0;
File destination = new File(desti);
if (Constants.DEBUG)
Log.i("DestinationFile", destination.getAbsolutePath());
if (!destination.exists()) {
if (chkConnectionStatus()) {
InputStream stream = null;
FileOutputStream fos = null;
try {
URL imageUrl = new URL(url);
HttpURLConnection conn = (HttpURLConnection) imageUrl
.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
stream = conn.getInputStream();
int contentLength = conn.getContentLength();
if (Constants.DEBUG)
Log.i(TAG, "contentLength : " + contentLength);
if (contentLength == 0) {
result = DownloadService.NO_FILE;
destination.delete();
Toast.makeText(getApplicationContext(),
getResources().getString(R.string.Text_NoFile),
1000).show();
} else if (contentLength > availablestorageOnExternalDir()) {
// No Space Available
result = DownloadService.LOW_SPACE;
destination.delete();
Toast.makeText(
getApplicationContext(),
getResources().getString(
R.string.Text_NoSpaceShow), 1000)
.show();
} else {
fos = new FileOutputStream(destination.getPath());
long total = 0l;
final int buffer_size = 4 * 1024;
try {
byte[] bytes = new byte[buffer_size];
for (;;) {
int count = stream.read(bytes, 0, buffer_size);
if (count == -1)
break;
fos.write(bytes, 0, count);
total += count;
int percent = (int) ((total * 100) / contentLength);
if (percent > lastPercent) {
if (Constants.DEBUG)
Log.i("Percent", "" + percent);
contentView.setProgressBar(
R.id.progressBar1, 100, percent,
false);
notification.contentView = contentView;
lastPercent = percent;
if (Constants.DEBUG)
Log.i("DownloadingPercent", ""
+ percent);
}
}
if (destination.length() < contentLength) {
result = DownloadService.PARTIALLY_DOWNLOADED;
destination.delete();
} else {
if (Constants.DEBUG)
Log.e(TAG,
"Sucessful downloaded-------------------------------------------------"
+ downloadCount++);
// Sucessful finished
if (Constants.DEBUG)
Log.e(TAG,
"Sucessful downloaded-------------------------------------------------"
+ downloadCount);
result = Activity.RESULT_OK;
}
} catch (Exception ex) {
}
// To track the offline event
JSONObject properties = new JSONObject();
try {
properties.put("User Name",
myPrefs.getString("email_id", null));
properties.put("MAIL",
myPrefs.getString("email_id", null));
} catch (JSONException e) {
}
mMixpanel.identify(myPrefs.getString("email_id", null));
mMixpanel.getPeople().set(properties);
mMixpanel.track("mA_Show Offline End", properties);
}
conn.disconnect();
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = destination.getAbsolutePath();
try {
messengerCopy.send(msg);
} catch (android.os.RemoteException e1) {
if (Constants.DEBUG)
Log.w(getClass().getName(),
"Exception sending message", e1);
}
if (Constants.DEBUG)
Log.v(TAG, "Completed.............. ");
} catch (Exception e) {
e.printStackTrace();
}
finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
// / no network connection
result = DownloadService.NETWORK_PROBLEM;
notification.setLatestEventInfo(cntxt,
"Please check your network connection", "",
contentIntent);
notification.flags |= Notification.FLAG_NO_CLEAR;
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(1, notification);
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = destination.getAbsolutePath();
try {
messengerCopy.send(msg);
} catch (android.os.RemoteException e1) {
if (Constants.DEBUG)
Log.w(getClass().getName(),
"Exception sending message", e1);
}
}
} else {
result = DownloadService.ASSERT_EXISIT;
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = destination.getAbsolutePath();
try {
messengerCopy.send(msg);
} catch (android.os.RemoteException e1) {
if (Constants.DEBUG)
Log.w(getClass().getName(), "Exception sending message", e1);
}
}
/*
* }
*
* }).start();
*/
return true;
}
public long availablestorageOnExternalDir() // Get Available space(in Bytes)
{
StatFs stat = new StatFs(Environment.getExternalStorageDirectory()
.getPath());
long bytesAvailable = (long) stat.getBlockSize()
* (long) stat.getAvailableBlocks();
long megAvailable = bytesAvailable / (1024 * 1024);
if (Constants.DEBUG)
Log.e("", "Available MB : " + megAvailable);
if (Constants.DEBUG)
Log.e("", "Available Bytes : " + bytesAvailable);
return bytesAvailable;
}
public boolean chkConnectionStatus() {
final android.net.NetworkInfo wifi = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile = connMgr
.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable()) {
if (wifi.isConnected())
return true;
return false;
} else if (mobile.isAvailable()) {
if (mobile.isConnected())
return true;
return false;
} else
return false;
}
}
My queries :
1.Is anything need to check additionally?
2.Is the folder structure is different in many android devices?
3.If the android devices having different folder structure or storage options(internal or external) how can I look forward?
I am trying to download files using IntentService.My downloading queue is interrupted.
I am using the following code to start a service
Intent intent = new Intent(ViewShowList.this, DownloadService.class);
// Create a new Messenger for the communication back
Messenger messenger = new Messenger(handler);
intent.putExtra("MESSENGER", messenger);
intent.putExtra("url", url);
intent.putExtra("share_id", showID);
intent.putExtra("showname", name);
intent.putExtra("showdatecreated", dateCreated);
intent.putExtra("noofFiles", noofFiles);
startService(intent);
Handler for communication back
#SuppressLint("HandlerLeak")
private Handler handler = new Handler() {
public void handleMessage(Message message) {
Log.d(TAG, "handleMessage.....................");
//Object path = message.obj;
if (message.arg1 == DownloadService.COMPLETED) {
Toast.makeText(mContext, getResources().getString(R.string.Text_MadeOffline), Toast.LENGTH_SHORT).show();
createOfflineShowsList();
syncShowAssets();
if (showListadapter != null) {
showListadapter.notifyDataSetChanged();
}
} else {
Log.e(TAG, "Download Failed...");
}
}
};
DownloadService.java
This is service class which extend IntentService
public class DownloadService
extends IntentService {
private int OFFSET;
private int LIMIT;
String data;
private final String TAG = "DownloadService";
private int result = Activity.RESULT_CANCELED;
public static int COMPLETED = 100;
public static int FAILED = 101;
public static int LOW_SPACE = 102;
public static int NETWORK_PROBLEM = 103;
public static int ASSERT_EXISIT = 104;
public static int PARTIALLY_DOWNLOADED = 105;
public static int NO_FILE = 105;
private NotificationManager notificationManager;
private Notification notification;
ConnectivityManager connMgr;
ArrayList<HashMap<String, String>> showAssetList;
private SharedPreferences sotcPref;
PendingIntent contentIntent;
int i = 1;
String url;
String showname;
String showdatecreated;
String showId;
Messenger messenger;
int noofFiles;
public DownloadService() {
super("DownloadService");
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 5 " + "DownloadService()constructor");
}
if (Constants.DEBUG) {
Log.d(TAG, "DownloadService... Constructor");
}
OFFSET = 0;
LIMIT = 3;
}
#SuppressWarnings("deprecation")
#Override
protected void onHandleIntent(Intent intent) {
// TODO Auto-generated method stub
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 6 " + "onHandleIntent");
}
connMgr = (ConnectivityManager) getApplicationContext().getSystemService(Context.CONNECTIVITY_SERVICE);
notificationManager = (NotificationManager) getApplicationContext().getSystemService(getApplicationContext().NOTIFICATION_SERVICE);
sotcPref = getApplicationContext().getSharedPreferences("SOTCPref", MODE_PRIVATE);
if (Constants.DEBUG) {
Log.d(TAG, "onHandleIntent.........");
}
Bundle extras = intent.getExtras();
url = extras.getString("url");
showname = extras.getString("showname");
showdatecreated = extras.getString("showdatecreated");
//sara
if (showdatecreated.contains("/")) {
data = showdatecreated.replaceAll("/", "#");
if (Constants.DEBUG) {
System.out.println("date");
}
if (Constants.DEBUG) {
System.out.println(data);
}
} else {
data = showdatecreated;
if (Constants.DEBUG) {
System.out.println("date in else");
}
if (Constants.DEBUG) {
System.out.println(showdatecreated);
}
if (Constants.DEBUG) {
System.out.println(data);
}
}
showId = extras.getString("share_id");
noofFiles = extras.getInt("noofFiles");
messenger = (Messenger) extras.get("MESSENGER");
Intent notificationIntent = new Intent();
contentIntent = PendingIntent.getActivity(getApplicationContext(), 0, notificationIntent, 0);
notification = new Notification(R.drawable.sotc_notification_icon, "", System.currentTimeMillis());
notification.flags = notification.flags | Notification.FLAG_ONGOING_EVENT;
notification.contentView = new RemoteViews(getApplicationContext()
.getPackageName(), R.layout.upload_progress_bar);
notification.icon = R.drawable.sotc_notification_icon;
notification.contentView.setTextViewText(R.id.textView1, showname);
notification.contentIntent = contentIntent;
notification.contentView.setProgressBar(R.id.progressBar1, 100, 0, false);
notificationManager.notify(1, notification);
if (Constants.DEBUG) {
Log.i("FOO", "Notification started");
}
if (showname.length() > 18) {
showname = showname.substring(0, 17);
}
if (DownloadAssets.TOTAL_ASSET_COUNT == 0) {
downloadSetofAssets(OFFSET, LIMIT, url);
if (DownloadAssets.TOTAL_ASSET_COUNT > LIMIT) {
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 8 " + "if(DownloadAssets.TOTAL_ASSET_COUNT > LIMIT)");
}
for (OFFSET = LIMIT; OFFSET < DownloadAssets.TOTAL_ASSET_COUNT; ) {
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 8.1 " + "if(DownloadAssets.TOTAL_ASSET_COUNT > LIMIT)");
}
downloadSetofAssets(OFFSET, LIMIT, url);
OFFSET = OFFSET + LIMIT;
}
}
}
if (i > 1) {
result = DownloadService.COMPLETED;
notification.setLatestEventInfo(DownloadService.this, "Downloaded Successfully", "", contentIntent);
Message msg = Message.obtain();
msg.arg1 = result;
try {
messenger.send(msg);
} catch (android.os.RemoteException e1) {
if (Constants.DEBUG) {
Log.w(getClass().getName(), "Exception sending message", e1);
}
}
} else {
result = DownloadService.FAILED;
notification.setLatestEventInfo(DownloadService.this, "Downloaded Failed", "", contentIntent);
if (Constants.DEBUG) {
Log.e(TAG, "Download Failed...");
}
}
notification.contentView.setImageViewResource(R.id.image, R.drawable.icon);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(1, notification);
}
private void downloadSetofAssets(int OFFSET, int LIMIT, String url) {
// TODO Auto-generated method stub
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 7 " + "downloadSetofAssets");
}
try {
url = url.replace("value1", URLEncoder.encode("" + OFFSET, "UTF-8"));
url = url.replace("value2", URLEncoder.encode("" + LIMIT, "UTF-8"));
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (Constants.DEBUG) {
Log.i(TAG, "Show offline -- Asset URL: " + url);
}
showAssetList = DownloadAssets.hit(getApplicationContext(), url);
for (HashMap<String, String> asset : showAssetList) {
String thumbUrl = asset.get("thumb_url");
String normalUrl = asset.get("normal_url");
String mp4Url = asset.get("mp4_url");
String fileType = asset.get("filetype");
String assetID = asset.get("id");
String assetType = asset.get("asset_type");
if (Constants.DEBUG) {
Log.d(TAG, "Thumb Url :" + thumbUrl);
}
if (Constants.DEBUG) {
Log.d(TAG, "Normal Url :" + normalUrl);
}
if (Constants.DEBUG) {
Log.d(TAG, "Asset ID : " + assetID);
}
if (Constants.DEBUG) {
Log.d(TAG, "Asset Type : " + assetType);
}
if (Constants.DEBUG) {
Log.d(TAG, "MP4 Url : " + mp4Url);
}
if (Constants.DEBUG) {
Log.d(TAG, "FileType : " + fileType);
}
boolean isDownloaded = false;
if (assetType.equals("1")) { // Image
File assetDirectory = createAssetDirectory(showId, showname, data, assetID, assetType);
if (assetDirectory != null) {
File thumb = new File(assetDirectory.getAbsolutePath(), "/Thumb");
thumb.mkdirs();
// Thumbnail
File thumbFile = new File(thumb.getAbsolutePath(), "/Thumb." + getExtention(thumbUrl));
if (Constants.DEBUG) {
Log.d(TAG, "Thumb File ath : " + thumbFile.getAbsolutePath());
}
isDownloaded = doInBackground(this, thumbUrl, thumbFile.getAbsolutePath(), messenger);
File normal = new File(assetDirectory.getAbsolutePath(), "/Normal");
normal.mkdirs();
// Normal
File normalFile = new File(normal.getAbsolutePath(), "/Normal." + getExtention(normalUrl));
if (Constants.DEBUG) {
Log.d(TAG, "Normal File path: " + normalFile.getAbsolutePath());
}
isDownloaded = doInBackground(this, normalUrl, normalFile.getAbsolutePath(), messenger);
}
} else if (assetType.equals("2")) { // Video
File assetDirectory = createAssetDirectory(showId, showname, data, assetID, assetType);
if (assetDirectory != null) {
if (!fileType.equals("Youtube")) { // via AddLink
File thumb = new File(assetDirectory.getAbsolutePath(), "/Thumb");
thumb.mkdirs();
// Thumbnail
File thumbFile = new File(thumb.getAbsolutePath(), "/Thumb." + getExtention(thumbUrl));
if (Constants.DEBUG) {
Log.d(TAG, "Thumb File ath : " + thumbFile.getAbsolutePath());
}
isDownloaded = doInBackground(this, thumbUrl, thumbFile.getAbsolutePath(), messenger);
File mp4url = new File(assetDirectory.getAbsolutePath(), "/Normal");
mp4url.mkdirs();
// mp4_Url
File mp4File = new File(mp4url.getAbsolutePath(), "/Normal." + getExtention(mp4Url));
if (Constants.DEBUG) {
Log.d(TAG, "Normal File path: " + mp4File.getAbsolutePath());
}
isDownloaded = doInBackground(this, mp4Url, mp4File.getAbsolutePath(), messenger);
} else if (Constants.DEBUG) {
Log.d(TAG, "Asset type is video but is Youtube link. So not proceeding for offline");
}
}
} else if (assetType.equals("3")) { // Audio
File assetDirectory = createAssetDirectory(showId, showname, data, assetID, assetType);
if (assetDirectory != null) {
File thumb = new File(assetDirectory.getAbsolutePath(), "/Thumb");
thumb.mkdirs();
// Thumbnail
File thumbFile = new File(thumb.getAbsolutePath(), "/Thumb." + getExtention(thumbUrl));
if (Constants.DEBUG) {
Log.d(TAG, "Thumb File ath : " + thumbFile.getAbsolutePath());
}
isDownloaded = doInBackground(this, thumbUrl, thumbFile.getAbsolutePath(), messenger);
File normal = new File(assetDirectory.getAbsolutePath(), "/Normal");
normal.mkdirs();
// Normal
File normalFile = new File(normal.getAbsolutePath(), "/Normal." + getExtention(normalUrl));
if (Constants.DEBUG) {
Log.d(TAG, "Normal File path: " + normalFile.getAbsolutePath());
}
isDownloaded = doInBackground(this, normalUrl, normalFile.getAbsolutePath(), messenger);
}
} else {
if (!assetType.equals("5")) {
File assetDirectory = createAssetDirectory(showId, showname, data, assetID, assetType);
if (assetDirectory != null) {
File thumb = new File(assetDirectory.getAbsolutePath(), "/Thumb");
thumb.mkdirs();
// Thumbnail
File thumbFile = new File(thumb.getAbsolutePath(), "/Thumb." + getExtention(thumbUrl));
if (Constants.DEBUG) {
Log.d(TAG, "Thumb File ath : " + thumbFile.getAbsolutePath());
}
isDownloaded = doInBackground(this, thumbUrl, thumbFile.getAbsolutePath(), messenger);
File normal = new File(assetDirectory.getAbsolutePath(), "/Normal");
normal.mkdirs();
// Normal
File normalFile = new File(normal.getAbsolutePath(), "/Normal." + getExtention(normalUrl));
if (Constants.DEBUG) {
Log.d(TAG, "Normal File path: " + normalFile.getAbsolutePath());
}
isDownloaded = doInBackground(this, normalUrl, normalFile.getAbsolutePath(), messenger);
} else { //"5" Link
if (Constants.DEBUG) {
Log.d(TAG, "This is Web Link");
}
isDownloaded = true;
}
}
}
}
}
private String getLoginFolders() {
// TODO Auto-generated method stub
File file = null;
int status = Constants.getSDCardStatus();
if (status == Constants.MOUNTED) {
File f = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"/SOTC_OFF/.nomedia");
f.mkdirs();
file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),
"/SOTC_OFF/" + sotcPref.getString("domain", "") + "/" + sotcPref.getString("user_id", ""));
file.mkdirs();
}
return file.getAbsolutePath();
}
private File createAssetDirectory(String showid, String showname,
String data, String assetID, String assetType) {
// TODO Auto-generated method stub
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 10 " + "createAssetDirectory");
}
File file = null;
int status = Constants.getSDCardStatus();
if (status == Constants.MOUNTED) {
if (DownloadAssets.TOTAL_ASSET_COUNT != 0) {
/**
* From to concept here is to avoid duplication of new
* offline shows when show is updated. So, we are here
* renaming previous offline show's folder name with
* updated asset count.
*/
boolean isRenameSuccess = false;
File f = new File(getLoginFolders());
if (!f.exists()) {
f.mkdirs();
}
File[] fileArray = f.listFiles();
File f2 = new File(getLoginFolders(), "/"
+ showid.trim() + ","
+ showname.trim() + ","
+ data);
for (File from : fileArray) {
String s1 = from.getName().substring(0, from.getName().lastIndexOf(","));
if (Constants.DEBUG) {
Log.i(TAG, "s1: " + s1);
}
if (f2.getName().equalsIgnoreCase(s1)) {
//Rename
File to = new File(getLoginFolders(), "/"
+ showid.trim() + ","
+ showname.trim() + ","
+ data + ","
+ noofFiles);
if (Constants.DEBUG) {
Log.i(TAG, "from existence: " + from.exists());
}
try {
isRenameSuccess = from.renameTo(to);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (Constants.DEBUG) {
Log.i(TAG, "isRenameSuccess: " + isRenameSuccess);
}
break;
}
}
file = new File(getLoginFolders(), "/"
+ showid.trim() + ","
+ showname.trim() + ","
+ data + ","
+ noofFiles +
"/File_"
+ assetID + ","
+ assetType.trim());
}
if (file != null) {
if (!file.exists()) {
file.mkdirs();
}
}
}
return file;
}
public static String getExtention(String url) {
String extension = MimeTypeMap.getFileExtensionFromUrl(url);
return extension;
}
#SuppressWarnings({"deprecation", "deprecation"})
boolean doInBackground(Context context, String urlPath, String destinationPath, Messenger messenger) {
boolean isDownloaded = false;
int lastPercent = 0;
File destination = new File(destinationPath);
if (!destination.exists()) {
if (chkConnectionStatus()) {
InputStream stream = null;
FileOutputStream fos = null;
try {
URL imageUrl = new URL(urlPath);
HttpURLConnection conn = (HttpURLConnection) imageUrl.openConnection();
conn.setConnectTimeout(30000);
conn.setReadTimeout(30000);
conn.setInstanceFollowRedirects(true);
stream = conn.getInputStream();
int contentLength = conn.getContentLength();
if (Constants.DEBUG) {
Log.i(TAG, "contentLength : " + contentLength);
}
if (contentLength == 0) {
result = DownloadService.NO_FILE;
destination.delete();
isDownloaded = false;
Toast.makeText(getApplicationContext(), getResources().getString(R.string.Text_NoFile), 1000).show();
} else if (contentLength > availablestorageOnExternalDir()) {
//No Space Available
result = DownloadService.LOW_SPACE;
destination.delete();
isDownloaded = false;
Toast.makeText(getApplicationContext(), getResources().getString(R.string.Text_NoSpaceShow), 1000).show();
} else {
fos = new FileOutputStream(destination.getPath());
long total = 0l;
final int buffer_size = 4 * 1024;
try {
byte[] bytes = new byte[buffer_size];
for (; ; ) {
int count = stream.read(bytes, 0, buffer_size);
if (count == -1) {
break;
}
fos.write(bytes, 0, count);
total += count;
int percent = (int) ((total * 100) / contentLength);
if (percent > lastPercent) {
notification.contentView.setProgressBar(R.id.progressBar1, 100, percent, false);
lastPercent = percent;
}
}
if (destination.length() < contentLength) {
result = DownloadService.PARTIALLY_DOWNLOADED;
destination.delete();
isDownloaded = false;
} else {
if (Constants.DEBUG) {
Log.e(TAG, "Sucessful downloaded-------------------------------------------------" + i++);
}
// Sucessful finished
//i++;
result = Activity.RESULT_OK;
isDownloaded = true;
}
} catch (Exception ex) {
}
}
conn.disconnect();
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = destination.getAbsolutePath();
try {
messenger.send(msg);
} catch (android.os.RemoteException e1) {
if (Constants.DEBUG) {
Log.w(getClass().getName(), "Exception sending message", e1);
}
}
if (Constants.DEBUG) {
Log.v(TAG, "Completed.............. ");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if (fos != null) {
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
} else {
/// no network connection
result = DownloadService.NETWORK_PROBLEM;
notification.setLatestEventInfo(context, "Please check your network connection", "", contentIntent);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
notificationManager.notify(1, notification);
isDownloaded = true;
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = destination.getAbsolutePath();
try {
messenger.send(msg);
} catch (android.os.RemoteException e1) {
if (Constants.DEBUG) {
Log.w(getClass().getName(), "Exception sending message", e1);
}
}
}
} else {
result = DownloadService.ASSERT_EXISIT;
Message msg = Message.obtain();
msg.arg1 = result;
msg.obj = destination.getAbsolutePath();
try {
messenger.send(msg);
} catch (android.os.RemoteException e1) {
if (Constants.DEBUG) {
Log.w(getClass().getName(), "Exception sending message", e1);
}
}
isDownloaded = true;
}
return isDownloaded;
}
public long availablestorageOnExternalDir() //Get Available space(in Bytes)
{
StatFs stat = new StatFs(Environment.getExternalStorageDirectory().getPath());
long bytesAvailable = (long) stat.getBlockSize() * (long) stat.getAvailableBlocks();
long megAvailable = bytesAvailable / (1024 * 1024);
if (Constants.DEBUG) {
Log.e("", "Available MB : " + megAvailable);
}
if (Constants.DEBUG) {
Log.e("", "Available Bytes : " + bytesAvailable);
}
return bytesAvailable;
}
public boolean chkConnectionStatus() {
final android.net.NetworkInfo wifi =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
final android.net.NetworkInfo mobile =
connMgr.getNetworkInfo(ConnectivityManager.TYPE_MOBILE);
if (wifi.isAvailable()) {
if (wifi.isConnected()) {
return true;
}
return false;
} else if (mobile.isAvailable()) {
if (mobile.isConnected()) {
return true;
}
return false;
} else {
return false;
}
}
}
DownloadAssets.java
//To download
//files into
//created folders
public class DownloadAssets {
private static final String TAG = "DownloadAssets";
public static int TOTAL_ASSET_COUNT;
static synchronized ArrayList<HashMap<String, String>> hit(Context context, String url) {
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 9 " + "hit url" + url);
}
ArrayList<HashMap<String, String>> mList = new ArrayList<HashMap<String, String>>();
String message = null;
String result = null;
try {
result = Constants.queryRESTurl(url);
if (result != null) {
if (result.equals("timeout")) {
message = context.getResources().getString(R.string.Text_TimeOut);
} else {
JSONObject json = Constants.convertStringtoJsonObject(result);
try {
JSONObject results = json.getJSONObject(ThumbnailFragment.JSON_RESPONSE_ATTR_RESULTSET);
String totalAssetCount = results.getString(ThumbnailFragment.JSON_RESPONSE_ATTR_ASSET_COUNT);
TOTAL_ASSET_COUNT = Integer.parseInt(totalAssetCount);
if (Constants.DEBUG) {
Log.i("5" + TAG, "totalAssetCount : " + totalAssetCount);
}
if (TOTAL_ASSET_COUNT != 0) {
JSONArray assetData = results.getJSONArray(ThumbnailFragment.JSON_RESPONSE_ATTR_ASSET_ARRAY);
if (Constants.DEBUG) {
Log.i(TAG, "6Madhu " + assetData.toString());
}
int nObjects = assetData.length();
if (Constants.DEBUG) {
Log.i(TAG, "7Madhu " + nObjects);
}
if (nObjects != 0) {
for (int i = 0; i < nObjects; i++) {
HashMap<String, String> map = new HashMap<String, String>();
JSONObject e = assetData.getJSONObject(i);
map.put("id", "" + e.getString("assets_id"));
map.put("asset_name", "" + e.getString("asset_name"));
map.put("thumb_url", "" + e.getString("thumb_url"));
map.put("asset_type", "" + e.getString("asset_type"));
map.put("large_url", "" + e.getString("large_url"));
map.put("mp4_url", "" + e.getString("mp4_url"));
map.put("normal_url", "" + e.getString("normal_url"));
map.put("description", "" + e.getString("description"));
map.put("filetype", "" + e.getString("filetype"));
map.put("filename", "" + e.getString("original_filename"));
map.put("filesize", "" + e.getString("filesize"));
mList.add(map);
if (Constants.DEBUG) {
Log.i(TAG, "Size in Loop " + mList.size());
}
}
} else if (Constants.DEBUG) {
Log.i(TAG, "EXECUTING ELSE nObjects");
}
} else if (Constants.DEBUG) {
Log.i(TAG, "EXECUTING ELSE count");
}
} catch (JSONException e) {
if (Constants.DEBUG) {
Log.e("8log_tag", "Error parsing data " + e.toString());
}
message = context.getResources().getString(R.string.Text_InvalidResponse);
} catch (Exception e) {
if (Constants.DEBUG) {
Log.e("8log_tag", "Error parsing data " + e.toString());
}
message = context.getResources().getString(R.string.Text_InvalidResponse);
e.printStackTrace();
}
}
} else {
if (Constants.DEBUG) {
Log.i(TAG, "EXECUTING ELSE result");
}
message = context.getResources().getString(R.string.Text_InvalidResponse);
}
} catch (Exception e) {
// TODO Auto-generated catch block
message = context.getResources().getString(R.string.Text_ServerProblem);
e.printStackTrace();
}
if (Constants.DEBUG) {
Log.e(TAG, "Message : " + message);
}
if (Constants.DEBUG) {
Log.d(TAG, "Offline step 9 End " + "hit return " + mList);
}
return mList;
}
}
My queries are
Files are downloading but not all files at first time from server.If I download more folders for example Folder1,Folder2 then Folder3, Folder1 and Folder2 interrupted(i.e 1 file is downloaded) but Folder3 downloaded fully...
How can I keep the queue of files/folders to be downloaded? !
For speed up and maintaining the queue of intent follow the below approach
protected void onHandleIntent(Intent intent) {
synchronized (intent) {
final Intent intentCpy=intent;
new Thread(new Runnable() {
#Override
public void run() {
//onHandleIntent code which is in question post
}
}
}
Use ConcurrentHashMap for Thread-Safty in following method
private synchronized void downloadSetofAssets(int OFFSET , int LIMIT , String url)
for more details about ConcurrentHashMap please visit
http://www.cs.umd.edu/class/spring2013/cmsc433/Notes/14-CMSC433-ConcurrentCollections.pdf
I am new to xmpp/asmack in android.
Can anyone please help me in getting the presence of the user's friends ( roster list)
I am using this :
Presence availability = roster.getPresence(user);
Mode userMode = availability.getMode();
What else should I do to get the availability status of each user listed in my roster.
Just use like this :
Presence availability = roster.getPresence(user);
Mode userMode = availability.getMode();
retrieveState_mode(availability.getMode(),availability.isAvailable());
public static int retrieveState_mode(Mode userMode, boolean isOnline) {
int userState = 0;
/** 0 for offline, 1 for online, 2 for away,3 for busy*/
if(userMode == Mode.dnd) {
userState = 3;
} else if (userMode == Mode.away || userMode == Mode.xa) {
userState = 2;
} else if (isOnline) {
userState = 1;
}
return userState;
}
Let me know if you have any problem regarding xmpp/asmack
use like this
userFromServer = con.getRoster().getPresence(userID);
userState = retrieveState(userFromServer.getMode(), userFromServer.isAvailable());
public int retrieveState(Mode userMode, boolean isOnline) {
int userState = XmppFriend.OFFLINE; // default return value
if (userMode == Mode.dnd) {
userState = XmppFriend.BUSY;
} else if (userMode == Mode.away || userMode == Mode.xa) {
userState = XmppFriend.AWAY;
} else if (isOnline) {
userState = XmppFriend.ONLINE;
}
return userState;
}
roster.addRosterListener(new RosterListener() {
public void entriesAdded(Collection<String> param) {}
public void entriesDeleted(Collection<String> addresses) {
}
public void entriesUpdated(Collection<String> addresses) {
}
public void presenceChanged(Presence presence) {
String user = presence.getFrom();
Presence bestPresence = roster.getPresence(user);
Log.d(TAG, "BestPresence: " + user + ": " + bestPresence);
String[] temp = presence.getFrom().split("\\#");
Log.d(TAG, "Presence: " + temp[0] + "-" + presence.toString());
String status = presence.toString();
// ShowInfoDialog(temp[0]+"is "+status);
for (int i = 0; i < friendslist.size(); i++) {
if (temp[0].equalsIgnoreCase(friendslist.get(i).getName())) {
friendslist.get(i).setStatus(status);
Log.d(TAG, "kilepet/belepet " + friendslist.get(i).getName() + " - " + friendslist.get(i).getStatus());
// ShowInfoDialog(friendslist.get(i).getName()+"is "+status);
Log.d(TAG, "WATERFAK");
}
}
}
If you use RosterListener, it updates the presence in real time, it works for me just fine.
ConnectToServer(){
final ProgressDialog dialog = ProgressDialog.show(ChatWindowFragmentActivity.this,
"Connecting...", "Please wait...", false);
Thread t = new Thread(new Runnable() {
#Override
public void run() {
// Object of XmppClient class
XmppClient mXmppClient = new XmppClient();
/*
* // Create a connection ConnectionConfiguration connConfig =
* new ConnectionConfiguration(HOST, PORT);
*/
XMPPConnection connection = null;
try {
SmackAndroid.init(ChatWindowFragmentActivity.this);
connection = mXmppClient.connectionToXmppServer();
} catch (XMPPException e) {
// TODO Auto-generated catch block
// setConnection(null, null);
}
try {
mXmppClient.loginUser(connection, USERNAME, PASSWORD);
Log.i("XMPPChatDemoActivity",
"Logged in as" + connection.getUser());
// Set the status to available
Presence presence = new Presence(Presence.Type.available);
connection.sendPacket(presence);
setConnection(connection);
Roster roster = connection.getRoster();
/*
Fetch USER availability
*/
switch (isUserAvailable(connection)){
case 0:
imgAvailability.setBackgroundColor(Color.GRAY);
break;
case 1:
imgAvailability.setBackgroundColor(Color.GREEN);
break;
case 2:
imgAvailability.setBackgroundColor(Color.YELLOW);
break;
case 3:
imgAvailability.setBackgroundColor(Color.RED);
break;
default:
break;
}
Collection<RosterEntry> entries = roster.getEntries();
for (RosterEntry entry : entries) {
Log.d("XMPPChatDemoActivity",
"--------------------------------------");
Log.d("XMPPChatDemoActivity", "RosterEntry " + entry);
Log.d("XMPPChatDemoActivity",
"User: " + entry.getUser());
Log.d("XMPPChatDemoActivity",
"Name: " + entry.getName());
Log.d("XMPPChatDemoActivity",
"Status: " + entry.getStatus());
Log.d("XMPPChatDemoActivity",
"Type: " + entry.getType());
Presence entryPresence = roster.getPresence(entry
.getUser());
Log.d("XMPPChatDemoActivity", "Presence Status: "
+ entryPresence.getStatus());
Log.d("XMPPChatDemoActivity", "Presence Type: "
+ entryPresence.getType());
Presence.Type type = entryPresence.getType();
if (type == Presence.Type.available)
Log.d("XMPPChatDemoActivity", "Presence AVAILABLE");
Log.d("XMPPChatDemoActivity", "Presence : "
+ entryPresence);
}
} catch (XMPPException e) {
e.printStackTrace();
Log.e("XMPPChatDemoActivity", "Failed to log in as "
+ USERNAME);
Log.e("XMPPChatDemoActivity", e.toString());
new ShowAlert(ChatWindowFragmentActivity.this,e.getMessage(), false).show(
getSupportFragmentManager(), TAG);
// setConnection(null, null);
}
dialog.dismiss();
}
});
t.start();
dialog.show();
}
And your method called inside it.
As my experience before you can see status and other from Presence you need to subscribe the user.
for example:
user A want to see status and available status from user B,
in this case, user A need to subscribe user B. after that user A can see the user B Presence.
Subscribe Code
try {
roster.setDefaultSubscriptionMode(Roster.SubscriptionMode.manual);
String userName = responders.getUsers().get(i).getUsername();
roster.createEntry("userB#domain", userName, null);
Presence pres = new Presence(Presence.Type.subscribe);
pres.setFrom("userA#domain");
connection.sendStanza(pres);
} catch (Exception e) {
android.util.Log.e("tag", "unable to add contact: ", e);
}
public void onCallStateChanged(int state,String incomingNumber)
{
System.out.print("\nState :- "+state);
switch(state){
case TelephonyManager.CALL_STATE_IDLE:
if(flag==true && ringflag == true)
{
flag=false;
ringflag=false;
System.out.print("\nflag = " + flag);
System.out.print("\nringflag = " + ringflag);
stop = System.currentTimeMillis();
System.out.println("\nTotal time : " +stop);
System.out.println("\nTotal time : " +(stop - start)/1000);
System.out.println("\nIDLE : " + incomingNumber);
long time = (stop - start) / 1000;
String path = Environment.getExternalStorageDirectory().getAbsolutePath();
f = new File(path + "/sms.txt");
if (f.exists()) {
try {
raf =new RandomAccessFile(f, "rw");
long pointer = raf.length();
raf.seek(pointer);
String data = ":-"+no+","+time;
raf.writeBytes(data);
raf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
try {
raf = new RandomAccessFile(f,"rw");
String data = ":-"+no+","+time;
raf.writeBytes(data);
raf.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
if(ringflag == true)
{
System.out.println("OFFHOOK :- " + incomingNumber);
start = System.currentTimeMillis();
System.out.print("\nStart is :-" + start);
flag=true;
}
break;
case TelephonyManager.CALL_STATE_RINGING:
no = incomingNumber;
System.out.println("Ringing : " + incomingNumber);
ringflag= true;
break;
}
}
I can answer the first part of your question
To get the call duration it is important to access the Call Logs.
Using the information given in CallLog.Calls, It can be done like below:
Uri allCalls = Uri.parse("content://call_log/calls");
Cursor c = managedQuery(allCalls, null, null, null, null);
for(String colName : c.getColumnNames())
Log.v(TAG, "Column Name: " + colName);
if (c.moveToFirst())
{
do{
String id = c.getString(c.getColumnIndex(CallLog.Calls._ID));
String num = c.getString(c.getColumnIndex(CallLog.Calls.NUMBER));
int type = Integer.parseInt(c.getString(c.getColumnIndex(CallLog.Calls.TYPE)));
String duration = c.getString(c.getColumnIndex(CallLog.Calls.DURATION));
System.out.println("call time duration is"+duration);
switch (type)
{
case 1: Log.v(TAG, id + ", " +num + ": INCOMING") ; break;
case 2: Log.v(TAG, id + ", " +num + ": OUTGOING") ;break;
case 3: Log.v(TAG, id + ", " +num + ": MISSED") ; break;
}
} while (c.moveToNext());
}
Refer this nice blog post for more information.