Example usage for android.content Context sendBroadcast

List of usage examples for android.content Context sendBroadcast

Introduction

In this page you can find the example usage for android.content Context sendBroadcast.

Prototype

public abstract void sendBroadcast(@RequiresPermission Intent intent);

Source Link

Document

Broadcast the given intent to all interested BroadcastReceivers.

Usage

From source file:org.universAAL.android.proxies.ServiceCalleeProxy.java

@Override
public void handleRequest(BusMessage m) {
    ServiceCall call = (ServiceCall) m.getContent();
    // Extract the origin action and category from the call
    String fromAction = (String) call.getNonSemanticInput(AppConstants.UAAL_META_PROP_FROMACTION);
    String fromCategory = (String) call.getNonSemanticInput(AppConstants.UAAL_META_PROP_FROMCATEGORY);
    Boolean needsOuts = (Boolean) call.getNonSemanticInput(AppConstants.UAAL_META_PROP_NEEDSOUTPUTS);
    boolean isNonIntrusive = fromAction != null && fromAction.equals(action) && fromCategory != null
            && fromCategory.equals(category);
    // This means the serv Intent in the caller proxy is the same as the
    // serv Intent in destination native app. Therefore the destination will
    // already have received it and we must not send the intent to avoid
    // duplication or infinite loops.
    if (!isNonIntrusive) {
        // In this case the serv intents are different because the origin
        // action+cat is being used as a kind of API to call the SCaller.
        // In this case we have to relay the call to the destination native app.
        Context ctxt = contextRef.get();
        if (ctxt != null) {
            // Prepare an intent for sending to Android grounded service
            Intent serv = new Intent(action);
            serv.addCategory(category);/*from  w ww. j  a va 2  s  .c  o  m*/
            boolean expecting = false;
            // If a response is expected, prepare a callback receiver (which must be called by uaalized app)
            if ((replyAction != null && !replyAction.isEmpty())
                    && (replyCategory != null && !replyCategory.isEmpty())) {
                // Tell the destination where to send the reply
                serv.putExtra(AppConstants.ACTION_META_REPLYTOACT, replyAction);
                serv.putExtra(AppConstants.ACTION_META_REPLYTOCAT, replyCategory);
                // Register the receiver for the reply
                receiver = new ServiceCalleeProxyReceiver(m);// TODO Can only handle 1 call at a time per proxy
                IntentFilter filter = new IntentFilter(replyAction);
                filter.addCategory(replyCategory);
                ctxt.registerReceiver(receiver, filter);
                expecting = true;
            } else if (needsOuts != null && needsOuts.booleanValue()) {
                // No reply* fields set, but caller still needs a response,
                // lets build one (does not work for callers outside android MW)
                Random r = new Random();
                String action = AppConstants.ACTION_REPLY + r.nextInt();
                serv.putExtra(AppConstants.ACTION_META_REPLYTOACT, action);
                serv.putExtra(AppConstants.ACTION_META_REPLYTOCAT, Intent.CATEGORY_DEFAULT);
                // Register the receiver for the reply
                receiver = new ServiceCalleeProxyReceiver(m);
                IntentFilter filter = new IntentFilter(action);
                filter.addCategory(Intent.CATEGORY_DEFAULT);
                ctxt.registerReceiver(receiver, filter);
                expecting = true;
            }
            // Take the inputs from the call and put them in the intent
            if (inputURItoExtraKEY != null && !inputURItoExtraKEY.isEmpty()) {
                VariableSubstitution.putCallInputsAsIntentExtras(call, serv, inputURItoExtraKEY);
            }
            // Flag to avoid feeding back the intent to bus when intent is the same in app and in callerproxy 
            serv.putExtra(AppConstants.ACTION_META_FROMPROXY, true);
            // Send the intent to Android grounded service
            ComponentName started = ctxt.startService(serv);//Not allowed in Android 5.0 (fall back to broadcast)
            if (started == null) {
                // No android service was there, try with broadcast. Before, here it used to send failure response
                ctxt.sendBroadcast(serv); // No way to know if received. If no response, bus will timeout (?)
            } else if (!expecting) {
                // There is no receiver waiting a response, send success now
                ServiceResponse resp = new ServiceResponse(CallStatus.succeeded);
                sendResponse(m, resp);
            }
            //TODO Handle timeout
        }
    }
}

From source file:de.ub0r.android.websms.WebSMS.java

/**
 * Send a command as broadcast./*from  w  w  w  .  ja v a 2 s .c om*/
 *
 * @param context   Current context
 * @param connector {@link ConnectorSpec}
 * @param command   {@link ConnectorCommand}
 */
static void runCommand(final Context context, final ConnectorSpec connector, final ConnectorCommand command) {
    connector.setErrorMessage((String) null);
    final Intent intent = command.setToIntent(null);
    short t = command.getType();
    boolean sendOrdered = false;
    switch (t) {
    case ConnectorCommand.TYPE_BOOTSTRAP:
        sendOrdered = true;
        intent.setAction(connector.getPackage() + Connector.ACTION_RUN_BOOTSTRAP);
        connector.addStatus(ConnectorSpec.STATUS_BOOTSTRAPPING);
        break;
    case ConnectorCommand.TYPE_SEND:
        sendOrdered = true;
        intent.setAction(connector.getPackage() + Connector.ACTION_RUN_SEND);
        connector.setToIntent(intent);
        connector.addStatus(ConnectorSpec.STATUS_SENDING);
        if (command.getResendCount() == 0) {
            WebSMSReceiver.saveMessage(me, connector, command, WebSMSReceiver.MESSAGE_TYPE_DRAFT);
        }
        break;
    case ConnectorCommand.TYPE_UPDATE:
        intent.setAction(connector.getPackage() + Connector.ACTION_RUN_UPDATE);
        connector.addStatus(ConnectorSpec.STATUS_UPDATING);
        break;
    default:
        break;
    }
    updateProgressBar();
    intent.setFlags(intent.getFlags() | Intent.FLAG_INCLUDE_STOPPED_PACKAGES);
    Log.d(TAG, "send broadcast: " + intent.getAction());
    if (sendOrdered) {
        context.sendOrderedBroadcast(intent, null, new BroadcastReceiver() {
            @Override
            public void onReceive(final Context context, final Intent intent) {
                if (this.getResultCode() != Activity.RESULT_OK) {
                    ConnectorCommand command = new ConnectorCommand(intent);
                    ConnectorSpec specs = new ConnectorSpec(intent);
                    specs.setErrorMessage(// TODO: localize
                            "Connector did not react on message");
                    WebSMSReceiver.handleSendCommand(context, specs, command);
                }
            }
        }, null, Activity.RESULT_CANCELED, null, null);
    } else {
        context.sendBroadcast(intent);
    }
}

From source file:org.universAAL.android.proxies.ServiceCalleeProxy.java

/**
 * This is an auxiliary method that invokes this proxy when a service
 * request matched in the R API server, and the ServiceCall was sent here
 * through GCM. We receive a ServiceCall not a BusMessage nor a
 * ServiceRequest. It sends the response back to the R API rather than
 * through the inner bus.// www .  j ava  2 s  .co  m
 * 
 * @param scall
 *            The ServiceCall as received from R API through GCM.
 * @param origincall
 *            The original ServiceCall URI as specified by the server. It is
 *            not the same as scall.getURI() since that object is created
 *            here in the client.
 */
public void handleCallFromGCM(ServiceCall scall, String origincall) {
    Boolean needsOuts = (Boolean) scall.getNonSemanticInput(AppConstants.UAAL_META_PROP_NEEDSOUTPUTS);
    Context ctxt = contextRef.get();
    if (ctxt != null) {
        // Prepare an intent for sending to Android grounded service
        Intent serv = new Intent(action);
        serv.addCategory(category);
        boolean expecting = false;
        // If a response is expected, prepare a callback receiver (which must be called by uaalized app)
        if ((replyAction != null && !replyAction.isEmpty())
                && (replyCategory != null && !replyCategory.isEmpty())) {
            // Tell the destination where to send the reply
            serv.putExtra(AppConstants.ACTION_META_REPLYTOACT, replyAction);
            serv.putExtra(AppConstants.ACTION_META_REPLYTOCAT, replyCategory);
            // Register the receiver for the reply
            receiver = new ServiceCalleeProxyReceiverGCM(origincall);
            IntentFilter filter = new IntentFilter(replyAction);
            filter.addCategory(replyCategory);
            ctxt.registerReceiver(receiver, filter);
            expecting = true;
        } else if (needsOuts != null && needsOuts.booleanValue()) {
            // No reply* fields set, but caller still needs a response, lets
            // build one (does not work for callers outside android MW)
            Random r = new Random();
            String action = AppConstants.ACTION_REPLY + r.nextInt();
            serv.putExtra(AppConstants.ACTION_META_REPLYTOACT, action);
            serv.putExtra(AppConstants.ACTION_META_REPLYTOCAT, Intent.CATEGORY_DEFAULT);
            // Register the receiver for the reply
            receiver = new ServiceCalleeProxyReceiverGCM(origincall);
            IntentFilter filter = new IntentFilter(action);
            filter.addCategory(Intent.CATEGORY_DEFAULT);
            ctxt.registerReceiver(receiver, filter);
            expecting = true;
        }
        // Take the inputs from the call and put them in the intent
        if (inputURItoExtraKEY != null && !inputURItoExtraKEY.isEmpty()) {
            VariableSubstitution.putCallInputsAsIntentExtras(scall, serv, inputURItoExtraKEY);
        }
        // Flag to avoid feeding back the intent to bus when intent is the same in app and in callerproxy 
        serv.putExtra(AppConstants.ACTION_META_FROMPROXY, true);
        // Send the intent to Android grounded service
        ComponentName started = null;
        try {
            // HACK: In android 5.0 it is forbidden to send implicit service intents like this one 
            started = ctxt.startService(serv);
        } catch (Exception e) {
            // Therefore if it fails, fail silently and try again with broadcast receivers
            started = null;
        }
        if (started == null) {
            // No android service was there, try with broadcast. Before, here it used to send failure response
            ctxt.sendBroadcast(serv); // No way to know if received. If no response, bus will timeout (?)
        } else if (!expecting) {
            // There is no receiver waiting a response, send success now
            ServiceResponse resp = new ServiceResponse(CallStatus.succeeded);
            sendResponseGCM(resp, origincall);
        }
        //TODO Handle timeout
    }
}

From source file:org.mythtv.service.content.v25.LiveStreamHelperV25.java

private int load(final Context context, final LocationProfile locationProfile, LiveStreamInfo[] liveStreams)
        throws RemoteException, OperationApplicationException {
    Log.d(TAG, "load : enter");

    if (null == context) {
        throw new RuntimeException("LiveStreamHelperV25 is not initialized");
    }//from   w ww  .j  a  v  a2  s  .co  m

    DateTime lastModified = new DateTime(DateTimeZone.UTC);

    int processed = -1;
    int count = 0;

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    for (LiveStreamInfo liveStream : liveStreams) {

        ContentValues values = convertLiveStreamInfoToContentValues(locationProfile, liveStream, lastModified,
                -1, null);

        String[] projection = new String[] { LiveStreamConstants.TABLE_NAME + "_" + LiveStreamConstants._ID };
        String selection = LiveStreamConstants.FIELD_ID + " = ?";
        String[] selectionArgs = new String[] { String.valueOf(liveStream.getId()) };

        selection = appendLocationHostname(context, locationProfile, selection, LiveStreamConstants.TABLE_NAME);

        Cursor cursor = context.getContentResolver().query(LiveStreamConstants.CONTENT_URI, projection,
                selection, selectionArgs, null);
        if (cursor.moveToFirst()) {
            Log.v(TAG, "load : updating existing liveStream info");
            long id = cursor.getLong(cursor
                    .getColumnIndexOrThrow(LiveStreamConstants.TABLE_NAME + "_" + LiveStreamConstants._ID));

            context.getContentResolver().update(ContentUris.withAppendedId(LiveStreamConstants.CONTENT_URI, id),
                    values, null, null);
        }
        cursor.close();
        count++;

        if (count > BATCH_COUNT_LIMIT) {
            Log.i(TAG, "load : applying batch for '" + count + "' transactions, processing programs");

            processBatch(context, ops, processed, count);

            count = 0;

        }

    }

    processBatch(context, ops, processed, count);

    Log.v(TAG, "load : remove deleted liveStreams");
    String deletedSelection = LiveStreamConstants.TABLE_NAME + "." + LiveStreamConstants.FIELD_LAST_MODIFIED
            + " < ?";
    String[] deletedSelectionArgs = new String[] { String.valueOf(lastModified.getMillis()) };

    deletedSelection = appendLocationHostname(context, locationProfile, deletedSelection,
            LiveStreamConstants.TABLE_NAME);

    ops.add(ContentProviderOperation.newDelete(LiveStreamConstants.CONTENT_URI)
            .withSelection(deletedSelection, deletedSelectionArgs).withYieldAllowed(true).build());

    processBatch(context, ops, processed, count);

    Intent progressIntent = new Intent(LiveStreamService.ACTION_PROGRESS);
    context.sendBroadcast(progressIntent);

    if (countLiveStreamsNotComplete(context, locationProfile) > 0) {
        Log.d(TAG, "load : further updates are required");

        try {
            Thread.sleep(15000);
        } catch (InterruptedException e) {
            Log.e(TAG, "load : error", e);
        }

        processed = load(context, locationProfile);
    }

    Log.d(TAG, "load : exit");
    return processed;
}

From source file:org.mythtv.service.content.v26.LiveStreamHelperV26.java

private int load(final Context context, final LocationProfile locationProfile, LiveStreamInfo[] liveStreams)
        throws RemoteException, OperationApplicationException {
    Log.d(TAG, "load : enter");

    if (null == context) {
        throw new RuntimeException("LiveStreamHelperV26 is not initialized");
    }//from w ww .  j  av  a2  s  . c o  m

    DateTime lastModified = new DateTime(DateTimeZone.UTC);

    int processed = -1;
    int count = 0;

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    for (LiveStreamInfo liveStream : liveStreams) {

        ContentValues values = convertLiveStreamInfoToContentValues(locationProfile, liveStream, lastModified,
                -1, null);

        String[] projection = new String[] { LiveStreamConstants.TABLE_NAME + "_" + LiveStreamConstants._ID };
        String selection = LiveStreamConstants.FIELD_ID + " = ?";
        String[] selectionArgs = new String[] { String.valueOf(liveStream.getId()) };

        selection = appendLocationHostname(context, locationProfile, selection, LiveStreamConstants.TABLE_NAME);

        Cursor cursor = context.getContentResolver().query(LiveStreamConstants.CONTENT_URI, projection,
                selection, selectionArgs, null);
        if (cursor.moveToFirst()) {
            Log.v(TAG, "load : updating existing liveStream info");
            long id = cursor.getLong(cursor
                    .getColumnIndexOrThrow(LiveStreamConstants.TABLE_NAME + "_" + LiveStreamConstants._ID));

            context.getContentResolver().update(ContentUris.withAppendedId(LiveStreamConstants.CONTENT_URI, id),
                    values, null, null);
        }
        cursor.close();
        count++;

        if (count > BATCH_COUNT_LIMIT) {
            Log.i(TAG, "load : applying batch for '" + count + "' transactions, processing programs");

            processBatch(context, ops, processed, count);

            count = 0;

        }

    }

    processBatch(context, ops, processed, count);

    Log.v(TAG, "load : remove deleted liveStreams");
    String deletedSelection = LiveStreamConstants.TABLE_NAME + "." + LiveStreamConstants.FIELD_LAST_MODIFIED
            + " < ?";
    String[] deletedSelectionArgs = new String[] { String.valueOf(lastModified.getMillis()) };

    deletedSelection = appendLocationHostname(context, locationProfile, deletedSelection,
            LiveStreamConstants.TABLE_NAME);

    ops.add(ContentProviderOperation.newDelete(LiveStreamConstants.CONTENT_URI)
            .withSelection(deletedSelection, deletedSelectionArgs).withYieldAllowed(true).build());

    processBatch(context, ops, processed, count);

    Intent progressIntent = new Intent(LiveStreamService.ACTION_PROGRESS);
    context.sendBroadcast(progressIntent);

    if (countLiveStreamsNotComplete(context, locationProfile) > 0) {
        Log.d(TAG, "load : further updates are required");

        try {
            Thread.sleep(15000);
        } catch (InterruptedException e) {
            Log.e(TAG, "load : error", e);
        }

        processed = load(context, locationProfile);
    }

    Log.d(TAG, "load : exit");
    return processed;
}

From source file:org.mythtv.service.content.v27.LiveStreamHelperV27.java

private int load(final Context context, final LocationProfile locationProfile, LiveStreamInfo[] liveStreams)
        throws RemoteException, OperationApplicationException {
    Log.d(TAG, "load : enter");

    if (null == context) {
        throw new RuntimeException("LiveStreamHelperV27 is not initialized");
    }//from w  w w  . j av a2s . co m

    DateTime lastModified = new DateTime(DateTimeZone.UTC);

    int processed = -1;
    int count = 0;

    ArrayList<ContentProviderOperation> ops = new ArrayList<ContentProviderOperation>();

    for (LiveStreamInfo liveStream : liveStreams) {

        ContentValues values = convertLiveStreamInfoToContentValues(locationProfile, liveStream, lastModified,
                -1, null);

        String[] projection = new String[] { LiveStreamConstants.TABLE_NAME + "_" + LiveStreamConstants._ID };
        String selection = LiveStreamConstants.FIELD_ID + " = ?";
        String[] selectionArgs = new String[] { String.valueOf(liveStream.getId()) };

        selection = appendLocationHostname(context, locationProfile, selection, LiveStreamConstants.TABLE_NAME);

        Cursor cursor = context.getContentResolver().query(LiveStreamConstants.CONTENT_URI, projection,
                selection, selectionArgs, null);
        if (cursor.moveToFirst()) {
            Log.v(TAG, "save : updating existing liveStream info");
            long id = cursor.getLong(cursor
                    .getColumnIndexOrThrow(LiveStreamConstants.TABLE_NAME + "_" + LiveStreamConstants._ID));

            context.getContentResolver().update(ContentUris.withAppendedId(LiveStreamConstants.CONTENT_URI, id),
                    values, null, null);
        }
        cursor.close();
        count++;

        if (count > BATCH_COUNT_LIMIT) {
            Log.i(TAG, "load : applying batch for '" + count + "' transactions, processing programs");

            processBatch(context, ops, processed, count);

            count = 0;

        }

    }

    processBatch(context, ops, processed, count);

    Log.v(TAG, "load : remove deleted liveStreams");
    String deletedSelection = LiveStreamConstants.TABLE_NAME + "." + LiveStreamConstants.FIELD_LAST_MODIFIED
            + " < ?";
    String[] deletedSelectionArgs = new String[] { String.valueOf(lastModified.getMillis()) };

    deletedSelection = appendLocationHostname(context, locationProfile, deletedSelection,
            LiveStreamConstants.TABLE_NAME);

    ops.add(ContentProviderOperation.newDelete(LiveStreamConstants.CONTENT_URI)
            .withSelection(deletedSelection, deletedSelectionArgs).withYieldAllowed(true).build());

    processBatch(context, ops, processed, count);

    Intent progressIntent = new Intent(LiveStreamService.ACTION_PROGRESS);
    context.sendBroadcast(progressIntent);

    if (countLiveStreamsNotComplete(context, locationProfile) > 0) {
        Log.d(TAG, "load : further updates are required");

        try {
            Thread.sleep(15000);
        } catch (InterruptedException e) {
            Log.e(TAG, "load : error", e);
        }

        processed = load(context, locationProfile);
    }

    Log.d(TAG, "load : exit");
    return processed;
}

From source file:com.openerp.services.ExpenseSyncService.java

/**
 * Perform sync.// ww  w .j a  va 2 s . c  o  m
 *
 * @param context    the context
 * @param account    the account
 * @param extras     the extras
 * @param authority  the authority
 * @param provider   the provider
 * @param syncResult the sync result
 */
public void performSync(Context context, Account account, Bundle extras, String authority,
        ContentProviderClient provider, SyncResult syncResult) {

    Log.d(TAG, "ExpenseSyncService->performSync()");
    Intent intent = new Intent();
    Intent updateWidgetIntent = new Intent();
    updateWidgetIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
    intent.setAction(SyncFinishReceiver.SYNC_FINISH);
    OEUser user = OpenERPAccountManager.getAccountDetail(context, account.name);
    try {
        ExpenseDBHelper expense_db = new ExpenseDBHelper(context);
        expense_db.setAccountUser(user);
        OEHelper oe = expense_db.getOEInstance();
        if (oe == null) {
            return;
        }
        int user_id = user.getUser_id();

        // Updating User Context for OE-JSON-RPC
        JSONObject newContext = new JSONObject();
        //newContext.put("default_model", "res.users");
        //newContext.put("default_res_id", user_id);

        OEArguments arguments = new OEArguments();
        // Param 1 : domain
        //OEDomain domain = new OEDomain();
        //arguments.add(domain);
        // Param 2 : context
        arguments.add(oe.updateContext(newContext));

        //???
        List<Integer> ids = expense_db.ids();
        if (oe.syncWithMethod("get_waiting_audit_expenses", arguments, true)) {
            int affected_rows = oe.getAffectedRows();
            Log.d(TAG, "ExpenseSyncService[arguments]:" + arguments.toString());
            Log.d(TAG, "ExpenseSyncService->affected_rows:" + affected_rows);
            List<Integer> affected_ids = oe.getAffectedIds();
            boolean notification = true;
            ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equalsIgnoreCase("com.openerp")) {
                notification = false;
            }
            if (notification && affected_rows > 0) {
                OENotificationHelper mNotification = new OENotificationHelper();
                Intent mainActiivty = new Intent(context, MainActivity.class);
                mainActiivty.setAction("EXPENSES");
                mNotification.setResultIntent(mainActiivty, context);

                String notify_title = context.getResources().getString(R.string.expenses_sync_notify_title);
                notify_title = String.format(notify_title, affected_rows);

                String notify_body = context.getResources().getString(R.string.expenses_sync_notify_body);
                notify_body = String.format(notify_body, affected_rows);

                mNotification.showNotification(context, notify_title, notify_body, authority,
                        R.drawable.ic_oe_notification);
            }
            intent.putIntegerArrayListExtra("new_ids", (ArrayList<Integer>) affected_ids);
        }
        //?expense?
        List<Integer> updated_ids = updateOldExpenses(expense_db, oe, user, ids);

    } catch (Exception e) {
        e.printStackTrace();
    }
    if (user.getAndroidName().equals(account.name)) {
        context.sendBroadcast(intent);
        //context.sendBroadcast(updateWidgetIntent);
    }
}

From source file:com.openerp.services.VoucherSyncService.java

/**
 * Perform sync./* w w w.  j a  v  a  2  s. c  o  m*/
 *
 * @param context    the context
 * @param account    the account
 * @param extras     the extras
 * @param authority  the authority
 * @param provider   the provider
 * @param syncResult the sync result
 */
public void performSync(Context context, Account account, Bundle extras, String authority,
        ContentProviderClient provider, SyncResult syncResult) {

    Log.d(TAG, "VoucherSyncService->performSync()");
    Intent intent = new Intent();
    Intent updateWidgetIntent = new Intent();
    updateWidgetIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
    intent.setAction(SyncFinishReceiver.SYNC_FINISH);
    OEUser user = OpenERPAccountManager.getAccountDetail(context, account.name);
    try {
        VoucherDB voucherDb = new VoucherDB(context);
        voucherDb.setAccountUser(user);
        OEHelper oe = voucherDb.getOEInstance();
        if (oe == null) {
            return;
        }
        int user_id = user.getUser_id();

        // Updating User Context for OE-JSON-RPC
        JSONObject newContext = new JSONObject();
        //newContext.put("default_model", "res.users");
        //newContext.put("default_res_id", user_id);

        OEArguments arguments = new OEArguments();
        // Param 1 : domain
        OEDomain domain = new OEDomain();
        //type = payment
        arguments.add(domain);
        // Param 2 : context
        arguments.add(oe.updateContext(newContext));

        //???
        List<Integer> ids = voucherDb.ids();
        if (oe.syncWithMethod("get_waiting_audit_vouchers", arguments, true)) {
            int affected_rows = oe.getAffectedRows();
            Log.d(TAG, "VoucherSyncService[arguments]:" + arguments.toString());
            Log.d(TAG, "VoucherSyncService->affected_rows:" + affected_rows);
            List<Integer> affected_ids = oe.getAffectedIds();
            boolean notification = true;
            ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equalsIgnoreCase("com.openerp")) {
                notification = false;
            }
            if (notification && affected_rows > 0) {
                OENotificationHelper mNotification = new OENotificationHelper();
                Intent mainActiivty = new Intent(context, MainActivity.class);
                mainActiivty.setAction("VOUCHERS");
                mNotification.setResultIntent(mainActiivty, context);

                String notify_title = context.getResources().getString(R.string.vouchers_sync_notify_title);
                notify_title = String.format(notify_title, affected_rows);

                String notify_body = context.getResources().getString(R.string.vouchers_sync_notify_body);
                notify_body = String.format(notify_body, affected_rows);

                mNotification.showNotification(context, notify_title, notify_body, authority,
                        R.drawable.ic_oe_notification);
            }
            intent.putIntegerArrayListExtra("new_ids", (ArrayList<Integer>) affected_ids);
        }
        //?expense?
        List<Integer> updated_ids = updateOldVouchers(voucherDb, oe, user, ids);

    } catch (Exception e) {
        e.printStackTrace();
    }
    if (user.getAndroidName().equals(account.name)) {
        context.sendBroadcast(intent);
        //context.sendBroadcast(updateWidgetIntent);
    }
}

From source file:net.geniecode.ttr.ScheduleReceiver.java

@SuppressWarnings("deprecation")
@SuppressLint({ "Recycle", "NewApi", "InlinedApi" })
@Override/*from  www.j  a  v  a 2  s.c o m*/
public void onReceive(Context context, Intent intent) {
    if (!Schedules.SCHEDULE_ACTION.equals(intent.getAction())) {
        // Unknown intent, bail.
        return;
    }

    Schedule schedule = null;
    // Grab the schedule from the intent. Since the remote AlarmManagerService
    // fills in the Intent to add some extra data, it must unparcel the
    // Schedule object. It throws a ClassNotFoundException when unparcelling.
    // To avoid this, do the marshalling ourselves.
    final byte[] data = intent.getByteArrayExtra(Schedules.SCHEDULE_RAW_DATA);
    if (data != null) {
        Parcel in = Parcel.obtain();
        in.unmarshall(data, 0, data.length);
        in.setDataPosition(0);
        schedule = Schedule.CREATOR.createFromParcel(in);
    }

    if (schedule == null) {
        // Make sure we set the next schedule if needed.
        Schedules.setNextSchedule(context);
        return;
    }

    // Disable this schedule if it does not repeat.
    if (!schedule.daysOfWeek.isRepeatSet()) {
        Schedules.enableSchedule(context, schedule.id, false);
    } else {
        // Enable the next schedule if there is one. The above call to
        // enableSchedule will call setNextSchedule so avoid calling it twice.
        Schedules.setNextSchedule(context);
    }

    long now = System.currentTimeMillis();

    if (now > schedule.time + STALE_WINDOW) {
        return;
    }

    // Get telephony service
    mTelephonyManager = (TelephonyManager) context.getSystemService(Context.TELEPHONY_SERVICE);

    // Execute only for devices with versions of Android less than 4.2
    if (android.os.Build.VERSION.SDK_INT < 17) {
        // Get flight mode state
        boolean isEnabled = Settings.System.getInt(context.getContentResolver(),
                Settings.System.AIRPLANE_MODE_ON, 0) == 1;

        // Get Wi-Fi service
        mWifiManager = (WifiManager) context.getSystemService(Context.WIFI_SERVICE);

        if ((schedule.aponoff) && (!isEnabled) && (schedule.mode.equals("1"))
                && (mTelephonyManager.getCallState() == TelephonyManager.CALL_STATE_IDLE)) {
            // Enable flight mode
            Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON,
                    isEnabled ? 0 : 1);

            // Get Wi-Fi state and disable that one too, just in case
            // (On some devices it doesn't get disabled when the flight mode is
            // turned on, so we do it here)
            boolean isWifiEnabled = mWifiManager.isWifiEnabled();

            SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);

            if (isWifiEnabled) {
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean(WIFI_STATE, isWifiEnabled);
                editor.commit();
                mWifiManager.setWifiEnabled(false);
            } else {
                SharedPreferences.Editor editor = settings.edit();
                editor.putBoolean(WIFI_STATE, isWifiEnabled);
                editor.commit();
            }

            // Post an intent to reload
            Intent relintent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
            relintent.putExtra("state", !isEnabled);
            context.sendBroadcast(relintent);
        } else if ((!schedule.aponoff) && (isEnabled) && (schedule.mode.equals("1"))) {
            // Disable flight mode
            Settings.System.putInt(context.getContentResolver(), Settings.System.AIRPLANE_MODE_ON,
                    isEnabled ? 0 : 1);

            // Restore previously remembered Wi-Fi state
            SharedPreferences settings = context.getSharedPreferences(PREFS_NAME, 0);
            Boolean WiFiState = settings.getBoolean(WIFI_STATE, true);

            if (WiFiState) {
                mWifiManager.setWifiEnabled(true);
            }

            // Post an intent to reload
            Intent relintent = new Intent(Intent.ACTION_AIRPLANE_MODE_CHANGED);
            relintent.putExtra("state", !isEnabled);
            context.sendBroadcast(relintent);
        }
        // Check whether there are ongoing phone calls, and if so
        // show notification instead of just enabling the flight mode
        else if ((schedule.aponoff) && (!isEnabled) && (schedule.mode.equals("1"))
                && (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE)) {
            setNotification(context);
        }
        // Execute for devices with Android 4.2   or higher
    } else {
        // Get flight mode state
        String result = Settings.Global.getString(context.getContentResolver(),
                Settings.Global.AIRPLANE_MODE_ON);

        if ((schedule.aponoff) && (result.equals("0")) && (schedule.mode.equals("1"))
                && (mTelephonyManager.getCallState() == TelephonyManager.CALL_STATE_IDLE)) {
            // Keep the device awake while enabling flight mode
            Intent service = new Intent(context, ScheduleIntentService.class);
            startWakefulService(context, service);
        } else if ((!schedule.aponoff) && (result.equals("1")) && (schedule.mode.equals("1"))) {
            // Keep the device awake while enabling flight mode
            Intent service = new Intent(context, ScheduleIntentService.class);
            startWakefulService(context, service);
        } else if ((schedule.aponoff) && (result.equals("0")) && (schedule.mode.equals("1"))
                && (mTelephonyManager.getCallState() != TelephonyManager.CALL_STATE_IDLE)) {
            setNotification(context);
        }
    }

    // Get audio service
    mAudioManager = (AudioManager) context.getSystemService(Context.AUDIO_SERVICE);

    // Get current ringer mode and set silent or normal mode accordingly
    switch (mAudioManager.getRingerMode()) {
    case AudioManager.RINGER_MODE_SILENT:
        if ((!schedule.silentonoff) && (schedule.mode.equals("2"))) {
            mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        }
        break;
    case AudioManager.RINGER_MODE_NORMAL:
        if ((schedule.silentonoff) && (schedule.mode.equals("2"))) {
            mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
        }
        break;
    case AudioManager.RINGER_MODE_VIBRATE:
        // If the phone is set to vibrate let's make it completely silent
        if ((schedule.silentonoff) && (schedule.mode.equals("2"))) {
            mAudioManager.setRingerMode(AudioManager.RINGER_MODE_SILENT);
        }
        // or restore the regular sounds on it if that's scheduled
        else if ((!schedule.silentonoff) && (schedule.mode.equals("2"))) {
            mAudioManager.setRingerMode(AudioManager.RINGER_MODE_NORMAL);
        }
        break;
    }
}

From source file:com.openerp.services.MessageSyncService.java

/**
 * Perform sync./*from ww w  . ja  v a2s. com*/
 *
 * @param context    the context
 * @param account    the account
 * @param extras     the extras
 * @param authority  the authority
 * @param provider   the provider
 * @param syncResult the sync result
 */
public void performSync(Context context, Account account, Bundle extras, String authority,
        ContentProviderClient provider, SyncResult syncResult) {
    Intent intent = new Intent();
    Intent updateWidgetIntent = new Intent();
    updateWidgetIntent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
    updateWidgetIntent.putExtra(MessageWidget.ACTION_MESSAGE_WIDGET_UPDATE, true);
    intent.setAction(SyncFinishReceiver.SYNC_FINISH);
    OEUser user = OpenERPAccountManager.getAccountDetail(context, account.name);
    try {
        MessageDB msgDb = new MessageDB(context);
        msgDb.setAccountUser(user);
        OEHelper oe = msgDb.getOEInstance();
        if (oe == null) {
            return;
        }
        int user_id = user.getUser_id();

        // Updating User Context for OE-JSON-RPC
        JSONObject newContext = new JSONObject();
        newContext.put("default_model", "res.users");
        newContext.put("default_res_id", user_id);

        OEArguments arguments = new OEArguments();
        // Param 1 : ids
        arguments.addNull();
        // Param 2 : domain
        OEDomain domain = new OEDomain();

        // Data limit.
        PreferenceManager mPref = new PreferenceManager(context);
        int data_limit = mPref.getInt("sync_data_limit", 60);
        domain.add("create_date", ">=", OEDate.getDateBefore(data_limit));

        if (!extras.containsKey("group_ids")) {
            // Last id
            JSONArray msgIds = new JSONArray();
            for (OEDataRow row : msgDb.select()) {
                msgIds.put(row.getInt("id"));
            }
            domain.add("id", "not in", msgIds);

            domain.add("|");
            // Argument for check partner_ids.user_id is current user
            domain.add("partner_ids.user_ids", "in", new JSONArray().put(user_id));

            domain.add("|");
            // Argument for check notification_ids.partner_ids.user_id
            // is
            // current user
            domain.add("notification_ids.partner_id.user_ids", "in", new JSONArray().put(user_id));

            // Argument for check author id is current user
            domain.add("author_id.user_ids", "in", new JSONArray().put(user_id));

        } else {
            JSONArray group_ids = new JSONArray(extras.getString("group_ids"));

            // Argument for group model check
            domain.add("model", "=", "mail.group");

            // Argument for group model res id
            domain.add("res_id", "in", group_ids);
        }

        arguments.add(domain.getArray());
        // Param 3 : message_unload_ids
        arguments.add(new JSONArray());
        // Param 4 : thread_level
        arguments.add(true);
        // Param 5 : context
        arguments.add(oe.updateContext(newContext));
        // Param 6 : parent_id
        arguments.addNull();
        // Param 7 : limit
        arguments.add(50);
        List<Integer> ids = msgDb.ids();
        if (oe.syncWithMethod("message_read", arguments)) {
            int affected_rows = oe.getAffectedRows();
            List<Integer> affected_ids = oe.getAffectedIds();
            boolean notification = true;
            ActivityManager am = (ActivityManager) context.getSystemService(ACTIVITY_SERVICE);
            List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
            ComponentName componentInfo = taskInfo.get(0).topActivity;
            if (componentInfo.getPackageName().equalsIgnoreCase("com.openerp")) {
                notification = false;
            }
            if (notification && affected_rows > 0) {
                OENotificationHelper mNotification = new OENotificationHelper();
                Intent mainActiivty = new Intent(context, MainActivity.class);
                mNotification.setResultIntent(mainActiivty, context);

                String notify_title = context.getResources().getString(R.string.messages_sync_notify_title);
                notify_title = String.format(notify_title, affected_rows);

                String notify_body = context.getResources().getString(R.string.messages_sync_notify_body);
                notify_body = String.format(notify_body, affected_rows);

                mNotification.showNotification(context, notify_title, notify_body, authority,
                        R.drawable.ic_oe_notification);
            }
            intent.putIntegerArrayListExtra("new_ids", (ArrayList<Integer>) affected_ids);
        }
        List<Integer> updated_ids = updateOldMessages(msgDb, oe, user, ids);
        intent.putIntegerArrayListExtra("updated_ids", (ArrayList<Integer>) updated_ids);
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (user.getAndroidName().equals(account.name)) {
        context.sendBroadcast(intent);
        context.sendBroadcast(updateWidgetIntent);
    }
}