List of usage examples for android.content.pm PackageManager getPackageInfo
public abstract PackageInfo getPackageInfo(VersionedPackage versionedPackage, @PackageInfoFlags int flags) throws NameNotFoundException;
From source file:com.lewa.crazychapter11.MainActivity.java
public boolean isLewaRom(Context context, Intent alarmIntent) { PackageManager pm = context.getPackageManager(); boolean isLewaRom = true; String version = ""; int versionCode = 0; PackageInfo pi = null;/*from w w w . j a v a2 s . c o m*/ String testsr = null; try { // com.lewa.permmanager // pm.getPackageInfo("com.lewa.deviceactivate",PackageManager.GET_ACTIVITIES); pm.getPackageInfo("com.lewa.permmanager", PackageManager.GET_ACTIVITIES); pi = pm.getPackageInfo(context.getPackageName(), 0); version = pi.versionName; versionCode = pi.versionCode; } catch (PackageManager.NameNotFoundException e) { isLewaRom = false; } Log.d("algerheMain00", "isLewaRom : " + isLewaRom); Log.i("algerheVersion", "versionname=" + version + " \n getPackageName()=" + getPackageName() + " \n versioncode=" + versionCode); Log.i("algerheStr", "TextUtils.isEmpty(testsr) = " + TextUtils.isEmpty(testsr)); // Log.i("algerheStr","testsr.length="+testsr.length()); ///alarm test Calendar calendar = Calendar.getInstance(); calendar.setTimeInMillis(System.currentTimeMillis()); calendar.set(Calendar.HOUR_OF_DAY, 16); calendar.set(Calendar.MINUTE, 0); calendar.set(Calendar.SECOND, 0); calendar.set(Calendar.MILLISECOND, 0); alarmIntent.setAction("com.lewa.alarm.test"); PendingIntent pipi = PendingIntent.getBroadcast(context, 3359, alarmIntent, PendingIntent.FLAG_UPDATE_CURRENT); AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE); Log.i("algerheAlarm", "send alarm message in time=" + System.currentTimeMillis()); // alarmManager.setExact(AlarmManager.RTC_WAKEUP, System.currentTimeMillis()+5000, pipi); alarmManager.setExact(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), pipi); // final Timer timer = new Timer(); // timer.schedule(new TimerTask() { // @Override // public void run() { // Message msg = new Message(); // msg.what = 0x2789; // handler.sendMessage(msg); // timer.cancel(); // } // }, 0, 5000); return isLewaRom; }
From source file:com.github.michalbednarski.intentslab.browser.ComponentFetcher.java
@Override Object getEntries(Context context) { PackageManager pm = context.getPackageManager(); int requestedPackageInfoFlags = type | PackageManager.GET_DISABLED_COMPONENTS | (requireMetaDataSubstring != null ? PackageManager.GET_META_DATA : 0); boolean workAroundSmallBinderBuffer = false; List<PackageInfo> allPackages = null; try {//from w w w. j a v a2 s.co m allPackages = pm.getInstalledPackages(requestedPackageInfoFlags); } catch (Exception e) { Log.w(TAG, "Loading all apps at once failed, retrying separately", e); } if (allPackages == null || allPackages.isEmpty()) { workAroundSmallBinderBuffer = true; allPackages = pm.getInstalledPackages(0); } ArrayList<Category> selectedApps = new ArrayList<Category>(); for (PackageInfo pack : allPackages) { // Filter out non-applications if (pack.applicationInfo == null) { continue; } // System app filter if ((((pack.applicationInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0 ? APP_TYPE_SYSTEM : APP_TYPE_USER) & appType) == 0) { continue; } // Load component information separately if they were to big to send them all at once if (workAroundSmallBinderBuffer) { try { pack = pm.getPackageInfo(pack.packageName, requestedPackageInfoFlags); } catch (PackageManager.NameNotFoundException e) { Log.w(TAG, "getPackageInfo() thrown NameNotFoundException for " + pack.packageName, e); continue; } } // Scan components ArrayList<Component> selectedComponents = new ArrayList<Component>(); if ((type & PackageManager.GET_ACTIVITIES) != 0) { scanComponents(pm, pack.activities, selectedComponents); } if ((type & PackageManager.GET_RECEIVERS) != 0) { scanComponents(pm, pack.receivers, selectedComponents); } if ((type & PackageManager.GET_SERVICES) != 0) { scanComponents(pm, pack.services, selectedComponents); } if ((type & PackageManager.GET_PROVIDERS) != 0) { scanComponents(pm, pack.providers, selectedComponents); } // Check if we filtered out all components and skip whole app if so if (selectedComponents.isEmpty()) { continue; } // Build and add app descriptor Category app = new Category(); app.title = String.valueOf(pack.applicationInfo.loadLabel(pm)); app.subtitle = pack.packageName; app.components = selectedComponents.toArray(new Component[selectedComponents.size()]); selectedApps.add(app); // Allow cancelling task if (Thread.interrupted()) { return null; } } return selectedApps.toArray(new Category[selectedApps.size()]); }
From source file:com.grass.caishi.cc.activity.main.MainActivity.java
public void Update(Map<String, Object> data) { if (data != null) { int code = Integer.valueOf(data.get("code").toString()); PackageManager pm = getPackageManager();// context?Activity PackageInfo pi;/* ww w . j ava 2s . c o m*/ try { pi = pm.getPackageInfo(getPackageName(), 0); if (code > pi.versionCode) { String name = data.get("name").toString(); String text = data.get("text").toString(); String url = data.get("url").toString(); String time = data.get("time").toString(); Toast.makeText(this, "" + name, Toast.LENGTH_SHORT).show(); MyUpdataInfoView myup = new MyUpdataInfoView(this); if (this.getParent() != null) myup = new MyUpdataInfoView(this.getParent()); myup.setTitle(name); myup.setTime(time); myup.setInfo(text); if (code - pi.versionCode > 9) { myup.setMustUp(true); } myup.setDownloadUrl(url); myup.show(MainActivity.this.findViewById(R.id.fragment_container)); } } catch (NameNotFoundException e) { // e.printStackTrace(); } } }
From source file:study.tdcc.act.MainCalendar.java
/** * ?//w w w .jav a 2 s. c o m * */ private void setCustomTitle() { Log.d("DEBUG", "MainCalendar setCustomTitle Start"); tvCustomTitle.setText(getString(R.string.act_name1)); StringBuilder sbObj = new StringBuilder(); sbObj.append(getString(R.string.title_version)); PackageManager pmObj = this.getPackageManager(); try { PackageInfo piObj = pmObj.getPackageInfo(this.getPackageName(), PackageManager.GET_ACTIVITIES); sbObj.append(piObj.versionName); } catch (NameNotFoundException e) { Log.e("ERROR", "MainCalendar setCustomTitle NameNotFoundException", e); } tvCustomTitleVersion.setText(sbObj.toString()); Log.d("DEBUG", "MainCalendar setCustomTitle End"); }
From source file:com.t2.compassionMeditation.Graphs1Activity.java
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i(TAG, this.getClass().getSimpleName() + ".onCreate()"); // We don't want the screen to timeout in this activity getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); this.requestWindowFeature(Window.FEATURE_NO_TITLE); // This needs to happen BEFORE setContentView setContentView(R.layout.graphs_activity_layout); mInstance = this; sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); mLoggingEnabled = SharedPref.getBoolean(this, "enable_logging", true); mDatabaseEnabled = SharedPref.getBoolean(this, "database_enabled", false); mAntHrmEnabled = SharedPref.getBoolean(this, "enable_ant_hrm", false); mInternalSensorMonitoring = SharedPref.getBoolean(this, "inernal_sensor_monitoring_enabled", false); if (mAntHrmEnabled) { mHeartRateSource = HEARTRATE_ANT; } else {//from ww w . j av a 2 s. c o m mHeartRateSource = HEARTRATE_ZEPHYR; } // The session start time will be used as session id // Note this also sets session start time // **** This session ID will be prepended to all JSON data stored // in the external database until it's changed (by the start // of a new session. Calendar cal = Calendar.getInstance(); SharedPref.setBioSessionId(sharedPref, cal.getTimeInMillis()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.US); String sessionDate = sdf.format(new Date()); String userId = SharedPref.getString(this, "SelectedUser", ""); long sessionId = SharedPref.getLong(this, "bio_session_start_time", 0); mDataOutHandler = new DataOutHandler(this, userId, sessionDate, mAppId, DataOutHandler.DATA_TYPE_EXTERNAL_SENSOR, sessionId); if (mDatabaseEnabled) { TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); String myNumber = telephonyManager.getLine1Number(); String remoteDatabaseUri = SharedPref.getString(this, "database_sync_name", getString(R.string.database_uri)); // remoteDatabaseUri += myNumber; Log.d(TAG, "Initializing database at " + remoteDatabaseUri); // TODO: remove try { mDataOutHandler.initializeDatabase(dDatabaseName, dDesignDocName, dDesignDocId, byDateViewName, remoteDatabaseUri); } catch (DataOutHandlerException e) { Log.e(TAG, e.toString()); e.printStackTrace(); } mDataOutHandler.setRequiresAuthentication(false); } mBioDataProcessor.initialize(mDataOutHandler); if (mLoggingEnabled) { mDataOutHandler.enableLogging(this); } if (mLogCatEnabled) { mDataOutHandler.enableLogCat(); } // Log the version try { PackageManager packageManager = getPackageManager(); PackageInfo info = packageManager.getPackageInfo(getPackageName(), 0); mApplicationVersion = info.versionName; String versionString = mAppId + " application version: " + mApplicationVersion; DataOutPacket packet = new DataOutPacket(); packet.add(DataOutHandlerTags.version, versionString); try { mDataOutHandler.handleDataOut(packet); } catch (DataOutHandlerException e) { Log.e(TAG, e.toString()); e.printStackTrace(); } } catch (NameNotFoundException e) { Log.e(TAG, e.toString()); } // Set up UI elements Resources resources = this.getResources(); AssetManager assetManager = resources.getAssets(); mPauseButton = (Button) findViewById(R.id.buttonPause); mAddMeasureButton = (Button) findViewById(R.id.buttonAddMeasure); mTextInfoView = (TextView) findViewById(R.id.textViewInfo); mMeasuresDisplayText = (TextView) findViewById(R.id.measuresDisplayText); // Don't actually show skin conductance meter unless we get samples ImageView image = (ImageView) findViewById(R.id.imageView1); image.setImageResource(R.drawable.signal_bars0); // Check to see of there a device configured for EEG, if so then show the skin conductance meter String tmp = SharedPref.getString(this, "EEG", null); if (tmp != null) { image.setVisibility(View.VISIBLE); } else { image.setVisibility(View.INVISIBLE); } // Initialize SPINE by passing the fileName with the configuration properties try { mManager = SPINEFactory.createSPINEManager("SPINETestApp.properties", resources); } catch (InstantiationException e) { Log.e(TAG, "Exception creating SPINE manager: " + e.toString()); e.printStackTrace(); } try { currentMindsetData = new MindsetData(this); } catch (Exception e1) { Log.e(TAG, "Exception creating MindsetData: " + e1.toString()); e1.printStackTrace(); } // Establish nodes for BSPAN // Create a broadcast receiver. Note that this is used ONLY for command messages from the service // All data from the service goes through the mail SPINE mechanism (received(Data data)). // See public void received(Data data) this.mCommandReceiver = new SpineReceiver(this); int itemId = 0; eegPos = itemId; // eeg always comes first mBioParameters.clear(); // First create GraphBioParameters for each of the EEG static params (ie mindset) for (itemId = 0; itemId < MindsetData.NUM_BANDS + 2; itemId++) { // 2 extra, for attention and meditation GraphBioParameter param = new GraphBioParameter(itemId, MindsetData.spectralNames[itemId], "", true); param.isShimmer = false; mBioParameters.add(param); } // Now create all of the potential dynamic GBraphBioParameters (GSR, EMG, ECG, EEG, HR, Skin Temp, Resp Rate // String[] paramNamesStringArray = getResources().getStringArray(R.array.parameter_names); String[] paramNamesStringArray = getResources().getStringArray(R.array.parameter_names_less_eeg); for (String paramName : paramNamesStringArray) { if (paramName.equalsIgnoreCase("not assigned")) continue; GraphBioParameter param = new GraphBioParameter(itemId, paramName, "", true); if (paramName.equalsIgnoreCase("gsr")) { gsrPos = itemId; param.isShimmer = true; param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_GSR_SENSOR; param.shimmerNode = getShimmerNode(); } if (paramName.equalsIgnoreCase("emg")) { emgPos = itemId; param.isShimmer = true; param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_EMG_SENSOR; param.shimmerNode = getShimmerNode(); } if (paramName.equalsIgnoreCase("ecg")) { ecgPos = itemId; param.isShimmer = true; param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_ECG_SENSOR; param.shimmerNode = getShimmerNode(); } if (paramName.equalsIgnoreCase("heart rate")) { heartRatePos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("resp rate")) { respRatePos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("skin temp")) { skinTempPos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth Airflow")) { eHealthAirFlowPos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth Temp")) { eHealthTempPos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth SpO2")) { eHealthSpO2Pos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth Heartrate")) { eHealthHeartRatePos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth GSR")) { eHealthGSRPos = itemId; param.isShimmer = false; } itemId++; mBioParameters.add(param); } // Since These are static nodes (Non-spine) we have to manually put them in the active node list Node mindsetNode = null; mindsetNode = new Node(new Address("" + Constants.RESERVED_ADDRESS_MINDSET)); // Note that the sensor id 0xfff1 (-15) is a reserved id for this particular sensor mManager.getActiveNodes().add(mindsetNode); Node zepherNode = null; zepherNode = new Node(new Address("" + Constants.RESERVED_ADDRESS_ZEPHYR)); mManager.getActiveNodes().add(zepherNode); // The arduino node is programmed to look like a static Spine node // Note that currently we don't have to turn it on or off - it's always streaming // Since Spine (in this case) is a static node we have to manually put it in the active node list // Since the final int RESERVED_ADDRESS_ARDUINO_SPINE = 1; // 0x0001 mSpineNode = new Node(new Address("" + RESERVED_ADDRESS_ARDUINO_SPINE)); mManager.getActiveNodes().add(mSpineNode); final String sessionName; // Check to see if we were requested to play back a previous session try { Bundle bundle = getIntent().getExtras(); if (bundle != null) { sessionName = bundle.getString(BioZenConstants.EXTRA_SESSION_NAME); AlertDialog.Builder alert = new AlertDialog.Builder(this); alert.setTitle("Replay Session " + sessionName + "?"); alert.setMessage("Make sure to turn off all Bluetooth Sensors!"); alert.setPositiveButton(R.string.alert_dialog_ok, new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { try { mDataOutHandler.logNote("Replaying data from session " + sessionName); } catch (DataOutHandlerException e) { Log.e(TAG, e.toString()); e.printStackTrace(); } replaySessionData(sessionName); AlertDialog.Builder alert1 = new AlertDialog.Builder(mInstance); alert1.setTitle("INFO"); alert1.setMessage("Replay of session complete!"); alert1.show(); } }); alert.show(); } } catch (Exception e) { Log.e(TAG, e.toString()); e.printStackTrace(); } if (mInternalSensorMonitoring) { // IntentSender Launches our service scheduled with with the alarm manager mBigBrotherService = PendingIntent.getService(Graphs1Activity.this, 0, new Intent(Graphs1Activity.this, BigBrotherService.class), 0); long firstTime = SystemClock.elapsedRealtime(); // Schedule the alarm! AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, mPollingPeriod * 1000, mBigBrotherService); // Tell the user about what we did. Toast.makeText(Graphs1Activity.this, R.string.service_scheduled, Toast.LENGTH_LONG).show(); } //testFIRFilter(); // testHR(); }
From source file:es.javocsoft.android.lib.toolbox.ToolBox.java
/** * Tells if an application is installed or not. * // w ww . j av a2 s . co m * @param context Your application context * @param appPackage The application package. * @return */ public static boolean system_isAppInstalled(Context context, String appPackage) { PackageManager pm = context.getPackageManager(); boolean app_installed = false; try { pm.getPackageInfo(appPackage, PackageManager.GET_ACTIVITIES); app_installed = true; } catch (PackageManager.NameNotFoundException e) { app_installed = false; } return app_installed; }
From source file:es.javocsoft.android.lib.toolbox.ToolBox.java
/** * Creates a application informative dialog with options to * uninstall/launch or cancel.// w w w.jav a 2s. c o m * * @param context * @param appPackage */ public static void appInfo_getLaunchUninstallDialog(final Context context, String appPackage) { try { final PackageManager packageManager = context.getPackageManager(); final PackageInfo app = packageManager.getPackageInfo(appPackage, PackageManager.GET_META_DATA); AlertDialog dialog = new AlertDialog.Builder(context).create(); dialog.setTitle(app.applicationInfo.loadLabel(packageManager)); String description = null; if (app.applicationInfo.loadDescription(packageManager) != null) { description = app.applicationInfo.loadDescription(packageManager).toString(); } String msg = app.applicationInfo.loadLabel(packageManager) + "\n\n" + "Version " + app.versionName + " (" + app.versionCode + ")" + "\n" + (description != null ? (description + "\n") : "") + app.applicationInfo.sourceDir + "\n" + appInfo_getSize(app.applicationInfo.sourceDir); dialog.setMessage(msg); dialog.setCancelable(true); dialog.setButton(AlertDialog.BUTTON_NEUTRAL, "Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.dismiss(); } }); dialog.setButton(AlertDialog.BUTTON_NEGATIVE, "Uninstall", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Intent intent = new Intent(Intent.ACTION_DELETE); intent.setData(Uri.parse("package:" + app.packageName)); context.startActivity(intent); } }); dialog.setButton(AlertDialog.BUTTON_POSITIVE, "Launch", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { Intent i = packageManager.getLaunchIntentForPackage(app.packageName); context.startActivity(i); } }); dialog.show(); } catch (Exception e) { if (LOG_ENABLE) { Log.e(TAG, "Dialog could not be made for the specified application '" + appPackage + "'. [" + e.getMessage() + "].", e); } } }
From source file:com.t2.dataouthandler.DataOutHandler.java
/** * Enables logging to external log file of entries sent to the database * /*from www .ja va 2 s. c om*/ * @param context Calling party's context */ public void enableLogging(Context context) { try { mLogWriter = new LogWriter(context); String logFileName = mUserId + "_" + mSessionDate + ".log"; mLogWriter.open(logFileName, true); mLoggingEnabled = true; SimpleDateFormat sdf = new SimpleDateFormat("HH:mm:ss.SSSZ", Locale.US); String timeId = sdf.format(new Date()); PackageManager packageManager = context.getPackageManager(); PackageInfo info = packageManager.getPackageInfo(context.getPackageName(), 0); mApplicationVersion = info.versionName; if (mLogFormat == GlobalH2.LOG_FORMAT_JSON) { String preamble = String.format( "{\"userId\" : \"%s\",\n" + "\"sessionDate\" : \"%s\",\n" + "\"timeId\" : \"%s\",\n" + "\"versionId\" : \"%s\",\n" + "\"data\":[", mUserId, mSessionDate, timeId, mApplicationVersion); mLogWriter.write(preamble); } } catch (Exception e) { Log.e(TAG, "Exception enabling logging: " + e.toString()); } }
From source file:com.strathclyde.highlightingkeyboard.SoftKeyboardService.java
/** * This method is called when the keyboard is shown * /*from ww w . ja v a 2s . co m*/ * reset errors & suggestion picked counters * get dots and colourbar prefs * get injection prefs * update engine core prefs * prepare database for writing * create a new typing session * apply selected keyboard to input view * switch core engine dictionaries according to keyboard */ @Override public void onStartInputView(EditorInfo attribute, boolean restarting) { //Log.i("OnStartInputView","Keyboard about to be shown"); nInjections = 0; SharedPreferences sharedPrefs = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); mInputView.dots = sharedPrefs.getBoolean("dots", false); mInputView.colorbar = sharedPrefs.getString("colorbar", "top"); mInputView.ycoords.clear(); mInputView.xcoords.clear(); mInputView.resetBackground(); errorInjection = sharedPrefs.getBoolean("errorinjection", false); errorInjectionThreshold = Integer.parseInt(sharedPrefs.getString("injectionThreshold", "20")); errorInjectionSound = sharedPrefs.getBoolean("errorinjectionsound", true); if (coreEngine != null) updateCorePrefs(); if (currentSession != null) { endSession(); } //open the database for writing if (dbm == null) dbm = new DBmanager(getApplicationContext()); dbm.open(); //get connection to editor field //ic = getCurrentInputConnection(); if (extractedText != null) { if (ic.deleteSurroundingText(9999, 0)) { ic.commitText(extractedText.text, 1); //extractedText=null; //Log.i("onStartInputView", "Text Replaced"); } else { //Log.i("onStartInputView", "IC not valid"); } } //create a new typing session UserPreferences up = new UserPreferences(); up.autocorrect = (sharedPrefs.getBoolean("autocorrect", true)) ? 1 : 0; up.sound = (sharedPrefs.getBoolean("audio", false)) ? 1 : 0; up.haptic = (sharedPrefs.getBoolean("vibrator", false)) ? 1 : 0; up.visual = (sharedPrefs.getBoolean("highlightwords", true)) ? 1 : 0; up.sugg_highlight = (sharedPrefs.getBoolean("suggestion_highlight", false)) ? 1 : 0; up.dots = (sharedPrefs.getBoolean("dots", false)) ? 1 : 0; currentSession = new TypingSession(up); currentSession.sess_height = mInputView.getHeight(); currentSession.sess_width = mInputView.getWidth(); currentSession.events.add(new TypingEvent(1, "Keyboard shown")); currentSession.user = userid; //find out what application has invoked the keyboard ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE); if (android.os.Build.VERSION.SDK_INT < 21) //works only on Android <5, retrieve the app name { RunningTaskInfo foregroundTaskInfo = am.getRunningTasks(1).get(0); String foregroundTaskPackageName = foregroundTaskInfo.topActivity.getPackageName(); PackageManager pm = this.getPackageManager(); PackageInfo foregroundAppPackageInfo; try { foregroundAppPackageInfo = pm.getPackageInfo(foregroundTaskPackageName, 0); currentSession.app = foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString(); //Log.i("OnStartInputView", "ForeGround app is "+foregroundAppPackageInfo.applicationInfo.loadLabel(pm).toString()); } catch (NameNotFoundException e) { e.printStackTrace(); } } else //retrieve the package name { List<RunningAppProcessInfo> ps = am.getRunningAppProcesses(); //Log.i("OnStartInput", "Running apps "+ps.size()); for (int x = 0; x < ps.size(); x++) { RunningAppProcessInfo p = ps.get(x); //Log.i("OnStartInput", "App is "+p.processName+p.importance); if (p.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { //Log.i("OnStartInput", "ForeGround app is "+p.processName); currentSession.app = p.processName; break; //the first one is the foreground app } } } // Apply the selected keyboard to the input view. //set the new keyboard options based on the temporary one created during OnStartInput if (mCurKeyboard != null) { //Log.i("onStartInputView","setting new keyboard to temp settings"); mInputView.setShifted(mCurKeyboard.isShifted()); mInputView.imeOptions = mCurKeyboard.imeOptions; } else { //Log.i("onStartInputView","mCurKeyboard is null"); } mInputView.currentKeyboard = startingKeyboard; mInputView.switchKeyboard(); if (coreEngine != null) { switch (mInputView.currentKeyboard) { case KeyboardViews.QWERTY_EL: coreEngine.activateLanguageKeymap(131092, null); coreEngine.setDictionaryPriority(131092, 0); break; case KeyboardViews.QWERTY_EN: coreEngine.activateLanguageKeymap(131081, null); coreEngine.setDictionaryPriority(131092, 1); break; } coreEngine.resetCoreString(); updateCandidates(); //KPTkeymapInfo(); } super.onStartInputView(attribute, restarting); }
From source file:com.t2.compassionMeditation.MeditationActivity.java
/** Called when the activity is first created. */ @Override/* www.ja v a 2s. c o m*/ public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); Log.i(TAG, this.getClass().getSimpleName() + ".onCreate()"); mInstance = this; mRateOfChange = new RateOfChange(mRateOfChangeSize); mIntroFade = 255; // We don't want the screen to timeout in this activity getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON); getWindow().addFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN); this.requestWindowFeature(Window.FEATURE_NO_TITLE); // This needs to happen BEFORE setContentView setContentView(R.layout.buddah_activity_layout); sharedPref = PreferenceManager.getDefaultSharedPreferences(getBaseContext()); currentMindsetData = new MindsetData(this); mSaveRawWave = SharedPref.getBoolean(this, BioZenConstants.PREF_SAVE_RAW_WAVE, BioZenConstants.PREF_SAVE_RAW_WAVE_DEFAULT); mShowAGain = SharedPref.getBoolean(this, BioZenConstants.PREF_SHOW_A_GAIN, BioZenConstants.PREF_SHOW_A_GAIN_DEFAULT); mAllowComments = SharedPref.getBoolean(this, BioZenConstants.PREF_COMMENTS, BioZenConstants.PREF_COMMENTS_DEFAULT); mShowForeground = SharedPref.getBoolean(this, "show_lotus", true); mShowToast = SharedPref.getBoolean(this, "show_toast", true); mAudioTrackResourceName = SharedPref.getString(this, "audio_track", "None"); mBaseImageResourceName = SharedPref.getString(this, "background_images", "Sunset"); mBioHarnessParameters = getResources().getStringArray(R.array.bioharness_parameters_array); setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT); String s = SharedPref.getString(this, BioZenConstants.PREF_SESSION_LENGTH, "10"); mSecondsRemaining = Integer.parseInt(s) * 60; mSecondsTotal = mSecondsRemaining; s = SharedPref.getString(this, BioZenConstants.PREF_ALPHA_GAIN, "5"); mAlphaGain = Float.parseFloat(s); mMovingAverage = new TMovingAverageFilter(mMovingAverageSize); mMovingAverageROC = new TMovingAverageFilter(mMovingAverageSizeROC); View v1 = findViewById(R.id.buddahView); v1.setOnTouchListener(this); Resources resources = this.getResources(); AssetManager assetManager = resources.getAssets(); // Set up member variables to UI Elements mTextInfoView = (TextView) findViewById(R.id.textViewInfo); mTextBioHarnessView = (TextView) findViewById(R.id.textViewBioHarness); mCountdownTextView = (TextView) findViewById(R.id.countdownTextView); mCountdownImageView = (ImageView) findViewById(R.id.imageViewCountdown); mPauseButton = (ImageButton) findViewById(R.id.buttonPause); mSignalImage = (ImageView) findViewById(R.id.imageView1); mTextViewInstructions = (TextView) findViewById(R.id.textViewInstructions); // Note that the seek bar is a debug thing - used only to set the // alpha of the buddah image manually for visual testing mSeekBar = (SeekBar) findViewById(R.id.seekBar1); mSeekBar.setOnSeekBarChangeListener(this); // Scale such that values to the right of center are scaled 1 - 10 // and values to the left of center are scaled 0 = .99999 if (mAlphaGain > 1.0) { mSeekBar.setProgress(50 + (int) (mAlphaGain * 5)); } else { int i = (int) (mAlphaGain * 50); mSeekBar.setProgress(i); } // mSeekBar.setProgress((int) mAlphaGain * 10); // Controls start as invisible, need to touch screen to activate them mCountdownTextView.setVisibility(View.INVISIBLE); mCountdownImageView.setVisibility(View.INVISIBLE); mTextInfoView.setVisibility(View.INVISIBLE); mTextBioHarnessView.setVisibility(View.INVISIBLE); mPauseButton.setVisibility(View.INVISIBLE); mPauseButton.setVisibility(View.VISIBLE); mSeekBar.setVisibility(View.INVISIBLE); mBackgroundImage = (ImageView) findViewById(R.id.buddahView); mForegroundImage = (ImageView) findViewById(R.id.lotusView); mBaseImage = (ImageView) findViewById(R.id.backgroundView); if (!mShowForeground) { mForegroundImage.setVisibility(View.INVISIBLE); } int resource = 0; if (mBaseImageResourceName.equalsIgnoreCase("Buddah")) { mBackgroundImage.setImageResource(R.drawable.buddha); mForegroundImage.setImageResource(R.drawable.lotus_flower); mBaseImage.setImageResource(R.drawable.none_bg); } else if (mBaseImageResourceName.equalsIgnoreCase("Bob")) { mBackgroundImage.setImageResource(R.drawable.bigbob); mForegroundImage.setImageResource(R.drawable.red_nose); mBaseImage.setImageResource(R.drawable.none_bg); } else if (mBaseImageResourceName.equalsIgnoreCase("Sunset")) { mBackgroundImage.setImageResource(R.drawable.eeg_layer); mForegroundImage.setImageResource(R.drawable.breathing_rate); mBaseImage.setImageResource(R.drawable.meditation_bg); } // Initialize SPINE by passing the fileName with the configuration properties try { mManager = SPINEFactory.createSPINEManager("SPINETestApp.properties", resources); } catch (InstantiationException e) { Log.e(TAG, "Exception creating SPINE manager: " + e.toString()); e.printStackTrace(); } // Since Mindset is a static node we have to manually put it in the active node list // Note that the sensor id 0xfff1 (-15) is a reserved id for this particular sensor Node mindsetNode = null; mindsetNode = new Node(new Address("" + Constants.RESERVED_ADDRESS_MINDSET)); mManager.getActiveNodes().add(mindsetNode); Node zepherNode = null; zepherNode = new Node(new Address("" + Constants.RESERVED_ADDRESS_ZEPHYR)); mManager.getActiveNodes().add(zepherNode); // The arduino node is programmed to look like a static Spine node // Note that currently we don't have to turn it on or off - it's always streaming // Since Spine (in this case) is a static node we have to manually put it in the active node list // Since the final int RESERVED_ADDRESS_ARDUINO_SPINE = 1; // 0x0001 mSpineNode = new Node(new Address("" + RESERVED_ADDRESS_ARDUINO_SPINE)); mManager.getActiveNodes().add(mSpineNode); // Create a broadcast receiver. Note that this is used ONLY for command messages from the service // All data from the service goes through the mail SPINE mechanism (received(Data data)). // See public void received(Data data) this.mCommandReceiver = new SpineReceiver(this); try { PackageManager packageManager = this.getPackageManager(); PackageInfo info = packageManager.getPackageInfo(this.getPackageName(), 0); mApplicationVersion = info.versionName; Log.i(TAG, "BioZen Application Version: " + mApplicationVersion + ", Activity Version: " + mActivityVersion); } catch (NameNotFoundException e) { Log.e(TAG, e.toString()); } // First create GraphBioParameters for each of the ECG static params (ie mindset) int itemId = 0; eegPos = itemId; // eeg always comes first mBioParameters.clear(); for (itemId = 0; itemId < MindsetData.NUM_BANDS + 2; itemId++) { // 2 extra, for attention and meditation GraphBioParameter param = new GraphBioParameter(itemId, MindsetData.spectralNames[itemId], "", true); param.isShimmer = false; mBioParameters.add(param); } // Now create all of the potential dynamic GBraphBioParameters (GSR, EMG, ECG, HR, Skin Temp, Resp Rate String[] paramNamesStringArray = getResources().getStringArray(R.array.parameter_names); for (String paramName : paramNamesStringArray) { if (paramName.equalsIgnoreCase("not assigned")) continue; if (paramName.equalsIgnoreCase("EEG")) continue; GraphBioParameter param = new GraphBioParameter(itemId, paramName, "", true); if (paramName.equalsIgnoreCase("gsr")) { gsrPos = itemId; param.isShimmer = true; param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_GSR_SENSOR; param.shimmerNode = getShimmerNode(); } if (paramName.equalsIgnoreCase("emg")) { emgPos = itemId; param.isShimmer = true; param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_EMG_SENSOR; param.shimmerNode = getShimmerNode(); } if (paramName.equalsIgnoreCase("ecg")) { ecgPos = itemId; param.isShimmer = true; param.shimmerSensorConstant = SPINESensorConstants.SHIMMER_ECG_SENSOR; param.shimmerNode = getShimmerNode(); } if (paramName.equalsIgnoreCase("heart rate")) { heartRatePos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("resp rate")) { respRatePos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("skin temp")) { skinTempPos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth Airflow")) { eHealthAirFlowPos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth Temp")) { eHealthTempPos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth SpO2")) { eHealthSpO2Pos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth Heartrate")) { eHealthHeartRatePos = itemId; param.isShimmer = false; } if (paramName.equalsIgnoreCase("EHealth GSR")) { eHealthGSRPos = itemId; param.isShimmer = false; } itemId++; mBioParameters.add(param); } // The session start time will be used as session id // Note this also sets session start time // **** This session ID will be prepended to all JSON data stored // in the external database until it's changed (by the start // of a new session. Calendar cal = Calendar.getInstance(); SharedPref.setBioSessionId(sharedPref, cal.getTimeInMillis()); SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd_HH-mm-ss", Locale.US); String sessionDate = sdf.format(new Date()); long sessionId = SharedPref.getLong(this, "bio_session_start_time", 0); mUserId = SharedPref.getString(this, "SelectedUser", ""); // Now get the database object associated with this user try { mBioUserDao = getHelper().getBioUserDao(); mBioSessionDao = getHelper().getBioSessionDao(); QueryBuilder<BioUser, Integer> builder = mBioUserDao.queryBuilder(); builder.where().eq(BioUser.NAME_FIELD_NAME, mUserId); builder.limit(1); // builder.orderBy(ClickCount.DATE_FIELD_NAME, false).limit(30); List<BioUser> list = mBioUserDao.query(builder.prepare()); if (list.size() == 1) { mCurrentBioUser = list.get(0); } else if (list.size() == 0) { try { mCurrentBioUser = new BioUser(mUserId, System.currentTimeMillis()); mBioUserDao.create(mCurrentBioUser); } catch (SQLException e1) { Log.e(TAG, "Error creating user " + mUserId, e1); } } else { Log.e(TAG, "General Database error" + mUserId); } } catch (SQLException e) { Log.e(TAG, "Can't find user: " + mUserId, e); } mSignalImage.setImageResource(R.drawable.signal_bars0); // Check to see of there a device configured for EEG, if so then show the skin conductance meter String tmp = SharedPref.getString(this, "EEG", null); if (tmp != null) { mSignalImage.setVisibility(View.VISIBLE); mTextViewInstructions.setVisibility(View.VISIBLE); } else { mSignalImage.setVisibility(View.INVISIBLE); mTextViewInstructions.setVisibility(View.INVISIBLE); } mDataOutHandler = new DataOutHandler(this, mUserId, sessionDate, mAppId, DataOutHandler.DATA_TYPE_EXTERNAL_SENSOR, sessionId); if (mDatabaseEnabled) { TelephonyManager telephonyManager = (TelephonyManager) this.getSystemService(Context.TELEPHONY_SERVICE); String myNumber = telephonyManager.getLine1Number(); String remoteDatabaseUri = SharedPref.getString(this, "database_sync_name", getString(R.string.database_uri)); // remoteDatabaseUri += myNumber; Log.d(TAG, "Initializing database at " + remoteDatabaseUri); // TODO: remove try { mDataOutHandler.initializeDatabase(dDatabaseName, dDesignDocName, dDesignDocId, byDateViewName, remoteDatabaseUri); } catch (DataOutHandlerException e) { Log.e(TAG, e.toString()); e.printStackTrace(); } mDataOutHandler.setRequiresAuthentication(false); } mBioDataProcessor.initialize(mDataOutHandler); mLoggingEnabled = SharedPref.getBoolean(this, "enable_logging", true); mDatabaseEnabled = SharedPref.getBoolean(this, "database_enabled", false); mAntHrmEnabled = SharedPref.getBoolean(this, "enable_ant_hrm", false); mInternalSensorMonitoring = SharedPref.getBoolean(this, "inernal_sensor_monitoring_enabled", false); if (mAntHrmEnabled) { mHeartRateSource = HEARTRATE_ANT; } else { mHeartRateSource = HEARTRATE_ZEPHYR; } if (mLoggingEnabled) { mDataOutHandler.enableLogging(this); } if (mLogCatEnabled) { mDataOutHandler.enableLogCat(); } // Log the version try { PackageManager packageManager = getPackageManager(); PackageInfo info = packageManager.getPackageInfo(getPackageName(), 0); mApplicationVersion = info.versionName; String versionString = mAppId + " application version: " + mApplicationVersion; DataOutPacket packet = new DataOutPacket(); packet.add(DataOutHandlerTags.version, versionString); try { mDataOutHandler.handleDataOut(packet); } catch (DataOutHandlerException e) { Log.e(TAG, e.toString()); e.printStackTrace(); } } catch (NameNotFoundException e) { Log.e(TAG, e.toString()); } if (mInternalSensorMonitoring) { // IntentSender Launches our service scheduled with with the alarm manager mBigBrotherService = PendingIntent.getService(MeditationActivity.this, 0, new Intent(MeditationActivity.this, BigBrotherService.class), 0); long firstTime = SystemClock.elapsedRealtime(); // Schedule the alarm! AlarmManager am = (AlarmManager) getSystemService(ALARM_SERVICE); am.setRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, firstTime, mPollingPeriod * 1000, mBigBrotherService); // Tell the user about what we did. Toast.makeText(MeditationActivity.this, R.string.service_scheduled, Toast.LENGTH_LONG).show(); } }