List of usage examples for android.content Context startService
@Nullable public abstract ComponentName startService(Intent service);
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.//from w w w .j a va 2 s . c o 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.kontalk.service.msgcenter.MessageCenterService.java
public static void sendGroupUploadedMedia(final Context context, String groupJid, String[] to, String mime, Uri localUri, long length, String previewPath, String fetchUrl, boolean encrypt, long msgId, String packetId) {/*from w w w.jav a 2s . co m*/ Intent i = new Intent(context, MessageCenterService.class); i.setAction(MessageCenterService.ACTION_MESSAGE); i.putExtra("org.kontalk.message.msgId", msgId); i.putExtra("org.kontalk.message.packetId", packetId); i.putExtra("org.kontalk.message.mime", mime); i.putExtra("org.kontalk.message.group.jid", groupJid); i.putExtra("org.kontalk.message.to", to); i.putExtra("org.kontalk.message.preview.uri", localUri.toString()); i.putExtra("org.kontalk.message.length", length); i.putExtra("org.kontalk.message.preview.path", previewPath); i.putExtra("org.kontalk.message.body", fetchUrl); i.putExtra("org.kontalk.message.fetch.url", fetchUrl); i.putExtra("org.kontalk.message.encrypt", encrypt); i.putExtra("org.kontalk.message.chatState", ChatState.active.name()); context.startService(i); }
From source file:net.sf.diningout.content.SyncAdapter.java
/** * Insert new system contacts, delete orphaned app contacts, and synchronise any changes to * existing./* www .j a v a 2s. c om*/ */ private void refreshContacts(Context context, ContentProviderClient cp) throws RemoteException { /* get system contacts */ String[] proj = { Email.ADDRESS, ContactsContract.Contacts.LOOKUP_KEY, RawContacts.CONTACT_ID, ContactsContract.Contacts.DISPLAY_NAME }; String sel = Email.IN_VISIBLE_GROUP + " = 1 AND " + Email.ADDRESS + " <> ?"; String[] args = { Accounts.selected().name }; EasyCursor sys = new EasyCursor(cr().query(Email.CONTENT_URI, proj, sel, args, Email.ADDRESS)); /* get app contacts */ proj = new String[] { Contacts.EMAIL, Contacts.ANDROID_LOOKUP_KEY, Contacts.ANDROID_ID, Contacts.NAME, _ID, Contacts.FOLLOWING, Contacts.STATUS_ID }; sel = Contacts.EMAIL + " IS NOT NULL"; EasyCursor app = new EasyCursor(cp.query(CONTACTS_URI, proj, sel, null, Contacts.EMAIL)); /* compare and sync */ ContentValues vals = new ContentValues(); for (CursorJoiner.Result result : new CursorJoiner(sys, new String[] { Email.ADDRESS }, app, new String[] { Contacts.EMAIL })) { switch (result) { case LEFT: // new system contact, insert into app contacts String email = sys.getString(Email.ADDRESS); String hash = BaseEncoding.base64() .encode(Hashing.sha512().hashString(email.toLowerCase(ENGLISH), UTF_8).asBytes()); long id = Contacts.idForHash(hash); // do we have this contact and not know it? /* insert or update values */ vals.put(Contacts.ANDROID_LOOKUP_KEY, sys.getString(ContactsContract.Contacts.LOOKUP_KEY)); vals.put(Contacts.ANDROID_ID, sys.getLong(RawContacts.CONTACT_ID)); String name = sys.getString(ContactsContract.Contacts.DISPLAY_NAME); vals.put(Contacts.NAME, name); vals.put(Contacts.NORMALISED_NAME, SQLite.normalise(name)); vals.put(Contacts.EMAIL, email); if (id <= 0) { vals.put(Contacts.EMAIL_HASH, hash); vals.put(Contacts.COLOR, Contacts.defaultColor()); id = ContentUris.parseId(cp.insert(CONTACTS_URI, vals)); } else { cp.update(ContentUris.withAppendedId(CONTACTS_URI, id), vals, null, null); } if (id > 0) { context.startService(new Intent(context, FriendColorService.class) .putExtra(FriendColorService.EXTRA_ID, id)); } break; case RIGHT: // orphaned app contact, delete unless user is following if (app.getInt(Contacts.FOLLOWING) == 0 && app.getInt(Contacts.STATUS_ID) == ACTIVE.id) { vals.put(Contacts.STATUS_ID, DELETED.id); vals.put(Contacts.DIRTY, 1); cp.update(Uris.appendId(CONTACTS_URI, app), vals, null, null); } break; case BOTH: // matching contacts, update details in app if needed String s = sys.getString(ContactsContract.Contacts.LOOKUP_KEY); if (!s.equals(app.getString(Contacts.ANDROID_LOOKUP_KEY))) { vals.put(Contacts.ANDROID_LOOKUP_KEY, s); } long l = sys.getLong(RawContacts.CONTACT_ID); if (l != app.getLong(Contacts.ANDROID_ID)) { vals.put(Contacts.ANDROID_ID, l); } s = sys.getString(ContactsContract.Contacts.DISPLAY_NAME); if (!s.equals(app.getString(Contacts.NAME))) { vals.put(Contacts.NAME, s); vals.put(Contacts.NORMALISED_NAME, SQLite.normalise(s)); } if (app.getInt(Contacts.STATUS_ID) == DELETED.id) { vals.put(Contacts.STATUS_ID, ACTIVE.id); vals.put(Contacts.DIRTY, 1); } if (vals.size() > 0) { cp.update(Uris.appendId(CONTACTS_URI, app), vals, null, null); context.startService(new Intent(context, FriendColorService.class) .putExtra(FriendColorService.EXTRA_ID, app.getLong(_ID))); } break; } vals.clear(); } sys.close(); app.close(); }
From source file:dev.ukanth.ufirewall.Api.java
/** * Purge and re-add all saved rules (not in-memory ones). * This is much faster than just calling "applyIptablesRules", since it don't need to read installed applications. * @param ctx application context (mandatory) * @param showErrors indicates if errors should be alerted * @param callback If non-null, use a callback instead of blocking the current thread *///from w ww .ja v a2 s .com public static boolean applySavedIptablesRules(Context ctx, boolean showErrors, RootCommand callback) { if (ctx == null) { return false; } initSpecial(); final String savedPkg_wifi_uid = G.pPrefs.getString(PREF_WIFI_PKG_UIDS, ""); final String savedPkg_3g_uid = G.pPrefs.getString(PREF_3G_PKG_UIDS, ""); final String savedPkg_roam_uid = G.pPrefs.getString(PREF_ROAMING_PKG_UIDS, ""); final String savedPkg_vpn_uid = G.pPrefs.getString(PREF_VPN_PKG_UIDS, ""); final String savedPkg_lan_uid = G.pPrefs.getString(PREF_LAN_PKG_UIDS, ""); boolean returnValue = false; List<String> cmds = new ArrayList<String>(); setIpTablePath(ctx, false); returnValue = applyIptablesRulesImpl(ctx, getListFromPref(savedPkg_wifi_uid), getListFromPref(savedPkg_3g_uid), getListFromPref(savedPkg_roam_uid), getListFromPref(savedPkg_vpn_uid), getListFromPref(savedPkg_lan_uid), showErrors, cmds); if (returnValue == false) { return false; } if (G.enableIPv6()) { setIpTablePath(ctx, true); returnValue = applyIptablesRulesImpl(ctx, getListFromPref(savedPkg_wifi_uid), getListFromPref(savedPkg_3g_uid), getListFromPref(savedPkg_roam_uid), getListFromPref(savedPkg_vpn_uid), getListFromPref(savedPkg_lan_uid), showErrors, cmds); if (returnValue == false) { return false; } } rulesUpToDate = true; if (G.logTarget().equals("NFLOG")) { Intent intent = new Intent(ctx.getApplicationContext(), NflogService.class); ctx.startService(intent); } if (callback != null) { callback.setRetryExitCode(IPTABLES_TRY_AGAIN).run(ctx, cmds); return true; } else { fixupLegacyCmds(cmds); try { final StringBuilder res = new StringBuilder(); int code = runScriptAsRoot(ctx, cmds, res); if (showErrors && code != 0) { String msg = res.toString(); // Remove unnecessary help message from output if (msg.indexOf("\nTry `iptables -h' or 'iptables --help' for more information.") != -1) { msg = msg.replace("\nTry `iptables -h' or 'iptables --help' for more information.", ""); } alert(ctx, ctx.getString(R.string.error_apply) + code + "\n\n" + msg.trim()); } else { return true; } } catch (Exception e) { Log.e(TAG, "Exception while applying rules: " + e.getMessage()); if (showErrors) alert(ctx, ctx.getString(R.string.error_refresh) + e); } return false; } }
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 w w .j a v a 2 s.c om 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.vanita5.twittnuker.util.Utils.java
public static void startRefreshServiceIfNeeded(final Context context) { final Intent refreshServiceIntent = new Intent(context, RefreshService.class); if (isNetworkAvailable(context) && hasAutoRefreshAccounts(context) && !isPushEnabled(context)) { if (isDebugBuild()) { Log.d(LOGTAG, "Start background refresh service"); }/*from w w w . j a v a 2 s. c o m*/ context.startService(refreshServiceIntent); } else { context.stopService(refreshServiceIntent); } }
From source file:com.liato.bankdroid.appwidget.AutoRefreshService.java
public static void showNotification(final Bank bank, final Account account, final BigDecimal diff, Context context) { final SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); if (!prefs.getBoolean("notify_on_change", true)) { return;/* w ww.j a va 2s . co m*/ } String text = String.format("%s: %s%s", account.getName(), ((diff.compareTo(new BigDecimal(0)) == 1) ? "+" : ""), Helpers.formatBalance(diff, account.getCurrency())); if (!prefs.getBoolean("notify_delta_only", false)) { text = String.format("%s (%s)", text, Helpers.formatBalance(account.getBalance(), account.getCurrency())); } final NotificationManager notificationManager = (NotificationManager) context .getSystemService(NOTIFICATION_SERVICE); final NotificationCompat.Builder notification = new NotificationCompat.Builder(context) .setSmallIcon(bank.getImageResource()).setContentTitle(bank.getDisplayName()).setContentText(text); // Remove notification from statusbar when clicked notification.setAutoCancel(true); // http://www.freesound.org/samplesViewSingle.php?id=75235 // http://www.freesound.org/samplesViewSingle.php?id=91924 if (prefs.getString("notification_sound", null) != null) { notification.setSound(Uri.parse(prefs.getString("notification_sound", null))); } if (prefs.getBoolean("notify_with_vibration", true)) { final long[] vib = { 0, 90, 130, 80, 350, 190, 20, 380 }; notification.setVibrate(vib); } if (prefs.getBoolean("notify_with_led", true)) { notification.setLights(prefs.getInt("notify_with_led_color", context.getResources().getColor(R.color.default_led_color)), 700, 200); } final PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(context, MainActivity.class), 0); notification.setContentIntent(contentIntent); String numNotifications = prefs.getString("num_notifications", "total"); int notificationId = (int) (numNotifications.equals("total") ? 0 : numNotifications.equals("bank") ? bank.getDbId() : numNotifications.equals("account") ? account.getId().hashCode() : SystemClock.elapsedRealtime()); notificationManager.notify(notificationId, notification.build()); // Broadcast to Remote Notifier if enabled // http://code.google.com/p/android-notifier/ if (prefs.getBoolean("notify_remotenotifier", false)) { final Intent i = new Intent(BROADCAST_REMOTE_NOTIFIER); i.putExtra("title", String.format("%s (%s)", bank.getName(), bank.getDisplayName())); i.putExtra("description", text); context.sendBroadcast(i); } // Broadcast to OpenWatch if enabled // http://forum.xda-developers.com/showthread.php?t=554551 if (prefs.getBoolean("notify_openwatch", false)) { Intent i; if (prefs.getBoolean("notify_openwatch_vibrate", false)) { i = new Intent(BROADCAST_OPENWATCH_VIBRATE); } else { i = new Intent(BROADCAST_OPENWATCH_TEXT); } i.putExtra("line1", String.format("%s (%s)", bank.getName(), bank.getDisplayName())); i.putExtra("line2", text); context.sendBroadcast(i); } // Broadcast to LiveView if enabled // http://www.sonyericsson.com/cws/products/accessories/overview/liveviewmicrodisplay if (prefs.getBoolean("notify_liveview", false)) { final Intent i = new Intent(context, LiveViewService.class); i.putExtra(LiveViewService.INTENT_EXTRA_ANNOUNCE, true); i.putExtra(LiveViewService.INTENT_EXTRA_TITLE, String.format("%s (%s)", bank.getName(), bank.getDisplayName())); i.putExtra(LiveViewService.INTENT_EXTRA_TEXT, text); context.startService(i); } }
From source file:org.kontalk.ui.ComposeMessageFragment.java
/** Sends a subscription request for the current peer. */ private void presenceSubscribe() { Context context = getActivity(); if (context != null) { // all of this shall be done only if there isn't a request from the other contact if (mConversation.getRequestStatus() != Threads.REQUEST_WAITING) { // request last presence Intent i = new Intent(context, MessageCenterService.class); i.setAction(MessageCenterService.ACTION_PRESENCE); i.putExtra(MessageCenterService.EXTRA_TO, mUserJID); i.putExtra(MessageCenterService.EXTRA_TYPE, Presence.Type.probe.name()); context.startService(i); }//w ww.j av a 2s . c om } }
From source file:org.yuttadhammo.BodhiTimer.TimerReceiver.java
@Override public void onReceive(Context context, Intent pintent) { Log.v(TAG, "ALARM: received alarm"); NotificationManager mNM = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE); if (player != null) { Log.v(TAG, "Releasing media player..."); try {//w w w . j a v a2s. c o m player.release(); player = null; } catch (Exception e) { e.printStackTrace(); player = null; } finally { // do nothing } } // Cancel notification and return... if (CANCEL_NOTIFICATION.equals(pintent.getAction())) { Log.v(TAG, "Cancelling notification..."); mNM.cancelAll(); return; } // ...or display a new one Log.v(TAG, "Showing notification..."); player = new MediaPlayer(); int setTime = pintent.getIntExtra("SetTime", 0); String setTimeStr = TimerUtils.time2humanStr(context, setTime); Log.v(TAG, "Time: " + setTime); CharSequence text = context.getText(R.string.Notification); CharSequence textLatest = String.format(context.getString(R.string.timer_for_x), setTimeStr); // Load the settings SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); boolean led = prefs.getBoolean("LED", true); boolean vibrate = prefs.getBoolean("Vibrate", true); String notificationUri = ""; boolean useAdvTime = prefs.getBoolean("useAdvTime", false); String advTimeString = prefs.getString("advTimeString", ""); String[] advTime = null; int advTimeIndex = 1; if (useAdvTime && advTimeString.length() > 0) { advTime = advTimeString.split("\\^"); advTimeIndex = prefs.getInt("advTimeIndex", 1); String[] thisAdvTime = advTime[advTimeIndex - 1].split("#"); // will be of format timeInMs#pathToSound if (thisAdvTime.length == 3) notificationUri = thisAdvTime[1]; if (notificationUri.equals("sys_def")) notificationUri = prefs.getString("NotificationUri", "android.resource://org.yuttadhammo.BodhiTimer/" + R.raw.bell); } else notificationUri = prefs.getString("NotificationUri", "android.resource://org.yuttadhammo.BodhiTimer/" + R.raw.bell); Log.v(TAG, "notification uri: " + notificationUri); if (notificationUri.equals("system")) notificationUri = prefs.getString("SystemUri", ""); else if (notificationUri.equals("file")) notificationUri = prefs.getString("FileUri", ""); else if (notificationUri.equals("tts")) { notificationUri = ""; final String ttsString = prefs.getString("tts_string", context.getString(R.string.timer_done)); Intent ttsIntent = new Intent(context, TTSService.class); ttsIntent.putExtra("spoken_text", ttsString); context.startService(ttsIntent); } NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(context.getApplicationContext()) .setSmallIcon(R.drawable.notification).setContentTitle(text).setContentText(textLatest); Uri uri = null; // Play a sound! if (!notificationUri.equals("")) uri = Uri.parse(notificationUri); // Vibrate if (vibrate && uri == null) { mBuilder.setDefaults(Notification.DEFAULT_VIBRATE); } // Have a light if (led) { mBuilder.setLights(0xff00ff00, 300, 1000); } mBuilder.setAutoCancel(true); // Creates an explicit intent for an Activity in your app Intent resultIntent = new Intent(context, TimerActivity.class); // The stack builder object will contain an artificial back stack for the // started Activity. // This ensures that navigating backward from the Activity leads out of // your application to the Home screen. TaskStackBuilder stackBuilder = TaskStackBuilder.create(context); // Adds the back stack for the Intent (but not the Intent itself) stackBuilder.addParentStack(TimerActivity.class); // Adds the Intent that starts the Activity to the top of the stack stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) context .getSystemService(Context.NOTIFICATION_SERVICE); // Create intent for cancelling the notification Context appContext = context.getApplicationContext(); Intent intent = new Intent(appContext, TimerReceiver.class); intent.setAction(CANCEL_NOTIFICATION); // Cancel the pending cancellation and create a new one PendingIntent pendingCancelIntent = PendingIntent.getBroadcast(appContext, 0, intent, PendingIntent.FLAG_CANCEL_CURRENT); if (uri != null) { //remove notification sound mBuilder.setSound(null); try { if (player != null && player.isPlaying()) { player.release(); player = new MediaPlayer(); } int currVolume = prefs.getInt("tone_volume", 0); if (currVolume != 0) { float log1 = (float) (Math.log(100 - currVolume) / Math.log(100)); player.setVolume(1 - log1, 1 - log1); } player.setDataSource(context, uri); player.prepare(); player.setLooping(false); player.setOnCompletionListener(new OnCompletionListener() { @Override public void onCompletion(MediaPlayer mp) { // TODO Auto-generated method stub mp.release(); } }); player.start(); if (vibrate) { Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(1000); } } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } if (prefs.getBoolean("AutoClear", false)) { // Determine duration of notification sound int duration = 5000; if (uri != null) { MediaPlayer cancelPlayer = new MediaPlayer(); try { cancelPlayer.setDataSource(context, uri); cancelPlayer.prepare(); duration = Math.max(duration, cancelPlayer.getDuration() + 2000); } catch (java.io.IOException ex) { Log.e(TAG, "Cannot get sound duration: " + ex); duration = 30000; // on error, default to 30 seconds } finally { cancelPlayer.release(); } cancelPlayer.release(); } Log.v(TAG, "Notification duration: " + duration + " ms"); // Schedule cancellation AlarmManager alarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); alarmMgr.set(AlarmManager.ELAPSED_REALTIME, SystemClock.elapsedRealtime() + duration, pendingCancelIntent); } if (useAdvTime && advTimeString.length() > 0) { Intent broadcast = new Intent(); SharedPreferences.Editor editor = prefs.edit(); if (advTimeIndex < advTime.length) { editor.putInt("advTimeIndex", advTimeIndex + 1); String[] thisAdvTime = advTime[advTimeIndex].split("#"); // will be of format timeInMs#pathToSound int time = Integer.parseInt(thisAdvTime[0]); broadcast.putExtra("time", time); // Save new time editor.putLong("TimeStamp", new Date().getTime() + time); editor.putInt("LastTime", time); // editor.putString("NotificationUri", thisAdvTime[1]); mNM.cancelAll(); Log.v(TAG, "Starting next iteration of the timer service ..."); Intent rintent = new Intent(context, TimerReceiver.class); rintent.putExtra("SetTime", time); PendingIntent mPendingIntent = PendingIntent.getBroadcast(context, 0, rintent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager mAlarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); mAlarmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + time, mPendingIntent); } else { broadcast.putExtra("stop", true); editor.putInt("advTimeIndex", 1); } broadcast.setAction(BROADCAST_RESET); context.sendBroadcast(broadcast); editor.apply(); } else if (prefs.getBoolean("AutoRestart", false)) { int time = pintent.getIntExtra("SetTime", 0); if (time != 0) { mNM.cancel(0); Log.v(TAG, "Restarting the timer service ..."); Intent rintent = new Intent(context, TimerReceiver.class); rintent.putExtra("SetTime", time); PendingIntent mPendingIntent = PendingIntent.getBroadcast(context, 0, rintent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager mAlarmMgr = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); mAlarmMgr.set(AlarmManager.RTC_WAKEUP, System.currentTimeMillis() + time, mPendingIntent); // Save new time SharedPreferences.Editor editor = prefs.edit(); editor.putLong("TimeStamp", new Date().getTime() + time); editor.putInt("LastTime", time); editor.apply(); Intent broadcast = new Intent(); broadcast.putExtra("time", time); broadcast.setAction(BROADCAST_RESET); context.sendBroadcast(broadcast); } } mNotificationManager.notify(0, mBuilder.build()); Log.d(TAG, "ALARM: alarm finished"); }
From source file:com.android.deskclock.timer.TimerReceiver.java
@Override public void onReceive(final Context context, final Intent intent) { if (Timers.LOGGING) { Log.v(TAG, "Received intent " + intent.toString()); }/* w w w. j ava 2 s . c o m*/ String actionType = intent.getAction(); // This action does not need the timers data if (Timers.NOTIF_IN_USE_CANCEL.equals(actionType)) { cancelInUseNotification(context); return; } // Get the updated timers data. if (mTimers == null) { mTimers = new ArrayList<>(); } SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context); TimerObj.getTimersFromSharedPrefs(prefs, mTimers); if (AlarmService.PRE_SHUTDOWN_ACTION.equals(actionType)) { // Stop Ringtone if all timers are not in times-up status TimerObj timerRing = Timers.findExpiredTimer(mTimers); if (timerRing != null) { timerRing.mState = TimerObj.STATE_STOPPED; stopRingtoneIfNoTimesup(context); } return; } // These actions do not provide a timer ID, but do use the timers data if (Timers.NOTIF_IN_USE_SHOW.equals(actionType)) { showInUseNotification(context); return; } else if (Timers.NOTIF_TIMES_UP_SHOW.equals(actionType)) { showTimesUpNotification(context); return; } else if (Timers.NOTIF_TIMES_UP_CANCEL.equals(actionType)) { cancelTimesUpNotification(context); return; } // Remaining actions provide a timer Id if (!intent.hasExtra(Timers.TIMER_INTENT_EXTRA)) { // No data to work with, do nothing Log.e(TAG, "got intent without Timer data"); return; } // Get the timer out of the Intent int timerId = intent.getIntExtra(Timers.TIMER_INTENT_EXTRA, -1); if (timerId == -1) { Log.d(TAG, "OnReceive:intent without Timer data for " + actionType); } TimerObj t = Timers.findTimer(mTimers, timerId); if (Timers.TIMES_UP.equals(actionType)) { // Find the timer (if it doesn't exists, it was probably deleted). if (t == null) { Log.d(TAG, " timer not found in list - do nothing"); return; } t.setState(TimerObj.STATE_TIMESUP); t.writeToSharedPref(prefs); Events.sendEvent(R.string.category_timer, R.string.action_fire, 0); /// M: We acquire the lock here because in some rare scenario, the wake lock is release /// by alarm before it could be acquired by Timer activity causing state to be suspended AlarmAlertWakeLock.acquireScreenCpuWakeLock(context); // Play ringtone by using TimerRingService service with a default alarm. Log.d(TAG, "playing ringtone"); Intent si = new Intent(); si.setClass(context, TimerRingService.class); context.startService(si); // Update the in-use notification if (getNextRunningTimer(mTimers, false, Utils.getTimeNow()) == null) { // Found no running timers. cancelInUseNotification(context); } else { showInUseNotification(context); } /** * M: To show time up notification to avoid the case: pausing the * current activity(eg: touch home key) when time is up, it cause * the TimerAlertFullScreen can not be started, and this cause no * notification in status bar but the timer has sound. @{ */ Utils.showTimesUpNotifications(context); /** @} */ // Start the TimerAlertFullScreen activity. Intent timersAlert = new Intent(context, TimerAlertFullScreen.class); timersAlert.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_NO_USER_ACTION); context.startActivity(timersAlert); } else if (Timers.RESET_TIMER.equals(actionType) || Timers.DELETE_TIMER.equals(actionType) || Timers.TIMER_DONE.equals(actionType)) { // Stop Ringtone if all timers are not in times-up status stopRingtoneIfNoTimesup(context); if (t != null) { cancelTimesUpNotification(context, t); } } else if (Timers.NOTIF_TIMES_UP_STOP.equals(actionType)) { // Find the timer (if it doesn't exists, it was probably deleted). if (t == null) { Log.d(TAG, "timer to stop not found in list - do nothing"); return; } else if (t.mState != TimerObj.STATE_TIMESUP) { Log.d(TAG, "action to stop but timer not in times-up state - do nothing"); return; } // Update timer state t.setState(t.getDeleteAfterUse() ? TimerObj.STATE_DELETED : TimerObj.STATE_RESTART); t.mTimeLeft = t.mOriginalLength = t.mSetupLength; t.writeToSharedPref(prefs); // Flag to tell DeskClock to re-sync with the database prefs.edit().putBoolean(Timers.REFRESH_UI_WITH_LATEST_DATA, true).apply(); cancelTimesUpNotification(context, t); // Done with timer - delete from data base if (t.getDeleteAfterUse()) { t.deleteFromSharedPref(prefs); } // Stop Ringtone if no timers are in times-up status stopRingtoneIfNoTimesup(context); } else if (Timers.NOTIF_TIMES_UP_PLUS_ONE.equals(actionType)) { // Find the timer (if it doesn't exists, it was probably deleted). if (t == null) { Log.d(TAG, "timer to +1m not found in list - do nothing"); return; } else if (t.mState != TimerObj.STATE_TIMESUP) { Log.d(TAG, "action to +1m but timer not in times up state - do nothing"); return; } // Restarting the timer with 1 minute left. t.setState(TimerObj.STATE_RUNNING); t.mStartTime = Utils.getTimeNow(); t.mTimeLeft = t.mOriginalLength = TimerObj.MINUTE_IN_MILLIS; t.writeToSharedPref(prefs); // Flag to tell DeskClock to re-sync with the database prefs.edit().putBoolean(Timers.REFRESH_UI_WITH_LATEST_DATA, true).apply(); cancelTimesUpNotification(context, t); // If the app is not open, refresh the in-use notification if (!prefs.getBoolean(Timers.NOTIF_APP_OPEN, false)) { showInUseNotification(context); } // Stop Ringtone if no timers are in times-up status stopRingtoneIfNoTimesup(context); } else if (Timers.TIMER_UPDATE.equals(actionType)) { // Find the timer (if it doesn't exists, it was probably deleted). if (t == null) { Log.d(TAG, " timer to update not found in list - do nothing"); return; } // Refresh buzzing notification if (t.mState == TimerObj.STATE_TIMESUP) { // Must cancel the previous notification to get all updates displayed correctly cancelTimesUpNotification(context, t); showTimesUpNotification(context, t); } } if (intent.getBooleanExtra(Timers.UPDATE_NEXT_TIMESUP, true)) { // Update the next "Times up" alarm unless explicitly told not to. updateNextTimesup(context); } }