Android : New IntentService is not running

on Friday, August 1, 2014


I stuck with a problem . I am trying to execute a delete SQLite script in every 10 minute for that i used following codes



public class DataCleaningService extends WakefulIntentService {

public DataCleaningService(String name) {
super(name);
// TODO Auto-generated constructor stub
}

int FIVE_MINUTES = 5*60*1000;

static Activity activity = null;
static DataCleaningListener cleanupListener = null;




/**
* register for callback after cleanup is complete
* */
static public void registerCleanupListener(DataCleaningListener cleanupListener,Activity activity){
DataCleaningService.cleanupListener = cleanupListener;
DataCleaningService.activity = activity;
}

/**
* unregister for callback after cleanup is complete
* */
static public void unregisterCleanupListener(){
DataCleaningService.cleanupListener = null;
DataCleaningService.activity = null;
}




/**
* Check if the sync is in progress
* */
public boolean IsSyncTriggered() {

boolean isActive = false;
AccountManager am = AccountManager.get(getBaseContext());
Account[] ac = am.getAccountsByType(Constants.ACCOUNT_TYPE);
if (ac.length > 0) {
isActive = ContentResolver.isSyncActive(ac[0], Constants.AUTHORITY);
}
return isActive;
}



//Some more stuff..........
//.....................
public void doCleanup() {
/**
* Set an array of table names
* */
String table_name[] = {
"invoice_item",
"invoice_role",
"invoice",
"order_role",
"order_adjustments",
"order_item",
"order",
// "order_item_temp", // No column called 'modified'
// "order_temp", // No column called 'modified'
"receipt_item",
"receipt",
"return_item",
"return_header",
"party_communication"
};

/**INDEX FOR THE LOOP*/
int index = 0;
/**
* Basic variables required
* */
//Database Instances and other stuff.............................
//..........................................................

Cursor device_info_cursor = databaseInstance.rawQuery("select * from device_info;",null);

int device_info_count = 0;
int user_login_count = 0;

if(device_info_cursor!=null){
device_info_count = device_info_cursor.getCount();
}else{
device_info_count = 0;
}

Cursor user_login_cursor = databaseInstance.rawQuery("select * from user_login;",null);

if(user_login_cursor!=null){
user_login_count = user_login_cursor.getCount();
}else{
user_login_count = 0;
}

/**
* Starting of the loop
* */
if(device_info_count>0 || user_login_count>0){
Cursor dC = null;
while(true){
if(!IsSyncTriggered()){
Toast.makeText(tarneaAndroidApplicationContext, "Clean up of "+table_name[index]+" in progress..", Toast.LENGTH_SHORT).show();
try {

String table_n=table_name[index++];
if(!table_n.equalsIgnoreCase("order")){
System.out.println("before delete@@@@");
String counttable = "SELECT count(*) FROM "+table_n;
Cursor tableCount = databaseInstance.rawQuery(counttable,null);
System.out.println("row before@@ delete "+table_n +"is :"+tableCount.getCount());
try{
String SQL = "DELETE FROM "+table_n+" WHERE modified <= date('now','-10 Minute') AND is_sync = '1'";
dC = databaseInstance.rawQuery(SQL,null);
}
catch(Exception e){
System.out.println("row error@@@");
}


if(index == (table_name.length-1)){
Toast.makeText(tarneaAndroidApplicationContext, "Clean up has finished.", Toast.LENGTH_SHORT).show();
break;
}
if(dC!=null && !dC.isClosed())
dC.close();
System.out.println("after delete@@@");
String counttable11 = "SELECT count(*) FROM "+table_n;
Cursor tableCount11 = databaseInstance.rawQuery(counttable11,null);
System.out.println("row aftre@@@ delete "+table_n +"is :"+tableCount11.getCount());

}else{
/**
* The reason to why this query throws an error
* is not known yet.
* */
// String SQL = "DELETE FROM order WHERE modified <= date('now','-30 days') AND is_sync = '1' ";
// Cursor dC = databaseInstance.rawQuery(SQL,null);
// if(dC!=null && !dC.isClosed())
// dC.close();

/**
* RAW Query was giving issues. therefore manually
* doing this
* */
OrderDao orderDao = daoSessionUni.getOrderDao();
List<Order> orderList = orderDao.loadAll();

ListIterator<Order> orderListIterator = orderList.listIterator();
if(orderList!=null && orderList.size()>0){
while(orderListIterator.hasNext()){
Order daoOrder = orderListIterator.next();
Date orderModifiedDate = daoOrder.getModified();
Boolean orderIsSync = daoOrder.getIsSync();
Long columnTime = orderModifiedDate.getTime();

Calendar date30daysback = Calendar.getInstance();
date30daysback.add(Calendar.DATE, -30);
Long toCheckAgainstTime = date30daysback.getTimeInMillis();

if (orderIsSync == true && (columnTime < toCheckAgainstTime)) {
daoOrder.delete();
}
}
}

}
} catch (Exception e) {
Log.d("DataCleaningService","ClearingException ",e);
e.printStackTrace();
}
}else{
/**
* If the sync is in progress
* wait for 5 minutes and try again
* */
try {
Thread.sleep(FIVE_MINUTES);
} catch (InterruptedException e) {
Log.d("DataCleaningService","SleepException ",e);
e.printStackTrace();
break;
}
}
}
}else{
/**
* Initial sync has not taken place in the device
* */
}

/**
* Closing all intialized cursors
* */
if(device_info_cursor!=null && !device_info_cursor.isClosed())
device_info_cursor.close();
if(user_login_cursor!=null && !user_login_cursor.isClosed())
user_login_cursor.close();
}

/**
* DEFAULT INTERFACE IMPLEMENTED, METHOD NOT USED
* */
/*@Override
public IBinder onBind(Intent intent) {
return null;
}
*/
@Override
void doWakefulWork(Intent intent) {
// TODO Auto-generated method stub
doCleanup();
try {
stopSelf();

}
catch (Exception e) {
Log.e("AppService", "Exception appending to log file", e);
}


}
}


I called this above class as



public class OnAlarmReceiver extends BroadcastReceiver{
@Override
public void onReceive(Context context, Intent intent) {
WakefulIntentService.acquireStaticLock(context);

context.startService(new Intent(context, DataCleaningService.class));
}
}


Then i used



public class OnBootReceiver extends BroadcastReceiver{
private static final int PERIOD=30000*10;

@Override
public void onReceive(Context context, Intent intent) {
System.out.println("row 1@@@");
AlarmManager mgr=(AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent i=new Intent(context, OnAlarmReceiver.class);
PendingIntent pi=PendingIntent.getBroadcast(context, 0,
i, 0);
Calendar calendar = Calendar.getInstance();

calendar.setTimeInMillis(System.currentTimeMillis());

calendar.add(Calendar.SECOND, 10);


mgr.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, SystemClock.elapsedRealtime(), PERIOD, pi);
}


}


At last i used my IntentServices as follow



public abstract class WakefulIntentService extends IntentService{
abstract void doWakefulWork(Intent intent);

public static final String LOCK_NAME_STATIC="com.xxxx.DataCleaningService.Static";
private static PowerManager.WakeLock lockStatic=null;

public static void acquireStaticLock(Context context) {
getLock(context).acquire();
}

synchronized private static PowerManager.WakeLock getLock(Context context) {
if (lockStatic==null) {
PowerManager mgr=(PowerManager)context.getSystemService(Context.POWER_SERVICE);

lockStatic=mgr.newWakeLock(PowerManager.SCREEN_DIM_WAKE_LOCK
| PowerManager.ON_AFTER_RELEASE, LOCK_NAME_STATIC);
lockStatic.setReferenceCounted(true);
}

return(lockStatic);
}

public WakefulIntentService(String name) {
super(name);
}

@Override
final protected void onHandleIntent(Intent intent) {
try {
doWakefulWork(intent);
System.out.println("row wake@@");
}
finally {
getLock(this).release();
}
}
@Override
public void onDestroy() {
stopSelf();
super.onDestroy();
}
}


I declared all receiver and services in Manifest file as



<receiver android:name="com.xxx.dbcleanup.OnBootReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver android:name="com.xxxx.dbcleanup.OnAlarmReceiver" >
</receiver>

<service android:name="com.xxxx.dbcleanup.DataCleaningService" >
</service>


But problem is that still my previous code is running even i uninstalled previous apk from my device. Why this is happening i am not able to understand? Any help help is really appreciated. Thanks in advance to all.


0 comments:

Post a Comment