Java Code Examples for android.app.Activity

The following are top voted examples for showing how to use android.app.Activity. These examples are extracted from open source projects. You can vote up the examples you like and your votes will be used in our system to product more good examples.

Example 1
Project: ExcusePro   File: ActionBarImpl.java View source code Vote up 7 votes
public ActionBarImpl(Activity activity, int features) {
    mActivity = activity;
    Window window = activity.getWindow();
    View decor = window.getDecorView();
    init(decor);

    //window.hasFeature() workaround for pre-3.0
    if ((features & (1 << Window.FEATURE_ACTION_BAR_OVERLAY)) == 0) {
        mContentView = (NineFrameLayout)decor.findViewById(android.R.id.content);
    }
}
 
Example 2
Project: hacktoolkit-android_lib   File: FileUtils.java View source code Vote up 7 votes
public static ArrayList<String> readLines(Activity activity, String filename) throws IOException {
	Context context = activity.getApplicationContext();
	ArrayList<String> lines = new ArrayList<String>();
	try {
		FileInputStream fin = context.openFileInput(filename);
		if (fin != null) {
			InputStreamReader inputStreamReader = new InputStreamReader(fin);
			BufferedReader bufferedReader = new BufferedReader(inputStreamReader);
			String line;
			while (( line = bufferedReader.readLine() ) != null) {
				lines.add(line);
			}
			fin.close();
		}
	} catch (FileNotFoundException fnfe) {
		fnfe.printStackTrace();
	}
	return lines;
}
 
Example 3
Project: phonegap-geolocation   File: CordovaActivity.java View source code Vote up 6 votes
@Override
    /**
     * Called when an activity you launched exits, giving you the requestCode you started it with,
     * the resultCode it returned, and any additional data from it.
     *
     * @param requestCode       The request code originally supplied to startActivityForResult(),
     *                          allowing you to identify who this result came from.
     * @param resultCode        The integer result code returned by the child activity through its setResult().
     * @param data              An Intent, which can return result data to the caller (various data can be attached to Intent "extras").
     */
    protected void onActivityResult(int requestCode, int resultCode, Intent intent) {
        LOG.d(TAG, "Incoming Result");
        super.onActivityResult(requestCode, resultCode, intent);
        Log.d(TAG, "Request code = " + requestCode);
        if (appView != null && requestCode == CordovaChromeClient.FILECHOOSER_RESULTCODE) {
        	ValueCallback<Uri> mUploadMessage = this.appView.getWebChromeClient().getValueCallback();
            Log.d(TAG, "did we get here?");
            if (null == mUploadMessage)
                return;
            Uri result = intent == null || resultCode != Activity.RESULT_OK ? null : intent.getData();
            Log.d(TAG, "result = " + result);
//            Uri filepath = Uri.parse("file://" + FileUtils.getRealPathFromURI(result, this));
//            Log.d(TAG, "result = " + filepath);
            mUploadMessage.onReceiveValue(result);
            mUploadMessage = null;
        }
        CordovaPlugin callback = this.activityResultCallback;
        if(callback == null && initCallbackClass != null) {
            // The application was restarted, but had defined an initial callback
            // before being shut down.
            this.activityResultCallback = appView.pluginManager.getPlugin(initCallbackClass);
            callback = this.activityResultCallback;
        }
        if(callback != null) {
            LOG.d(TAG, "We have a callback to send this result to");
            callback.onActivityResult(requestCode, resultCode, intent);
        }
    }
 
Example 4
Project: AmazeFileManager   File: Preferences.java View source code Vote up 6 votes
@Override
public void onBackPressed() {
    if(select==1 && changed==1)
        restartPC(this);
    else if(select==1 || select==2){selectItem(0);}
    else{
        Intent in = new Intent(Preferences.this, MainActivity.class);
        in.setAction(Intent.ACTION_MAIN);
        final int enter_anim = android.R.anim.fade_in;
        final int exit_anim = android.R.anim.fade_out;
        Activity activity = this;
        activity.overridePendingTransition(enter_anim, exit_anim);
        activity.finish();
        activity.overridePendingTransition(enter_anim, exit_anim);
        activity.startActivity(in);
    }
}
 
Example 5
Project: BLEConnect   File: DeviceScanActivity.java View source code Vote up 6 votes
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // User chose not to enable Bluetooth.
    if (requestCode == REQUEST_ENABLE_BT && resultCode == Activity.RESULT_CANCELED) {
        finish();
        return;
    }
    super.onActivityResult(requestCode, resultCode, data);
}
 
Example 6
Project: ExcusePro   File: Session.java View source code Vote up 6 votes
AuthorizationRequest(final Activity activity) {
    startActivityDelegate = new StartActivityDelegate() {
        @Override
        public void startActivityForResult(Intent intent, int requestCode) {
            activity.startActivityForResult(intent, requestCode);
        }

        @Override
        public Activity getActivityContext() {
            return activity;
        }
    };
}
 
Example 7
Project: BioWiki   File: MediaEditFragment.java View source code Vote up 6 votes
@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);

    try {
        mCallback = (MediaEditFragmentCallback) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString() + " must implement " + MediaEditFragmentCallback.class.getSimpleName());
    }
}
 
Example 8
Project: BioWiki   File: CommentsListFragment.java View source code Vote up 6 votes
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        // check that the containing activity implements our callback
        mOnCommentSelectedListener = (OnCommentSelectedListener) activity;
        mOnCommentChangeListener = (OnCommentChangeListener) activity;
    } catch (ClassCastException e) {
        activity.finish();
        throw new ClassCastException(activity.toString() + " must implement Callback");
    }
}
 
Example 9
Project: BioWiki   File: MessageBarUtils.java View source code Vote up 6 votes
public static void showMessageBar(final Activity activity,
                                  final String message,
                                  final MessageBarType messageBarType,
                                  final Runnable runnable) {
    if (activity == null)
        return;

    final TextView txtMessageBar = (TextView) activity.findViewById(R.id.text_message_bar);
    if (txtMessageBar == null)
        return;
    if (txtMessageBar.getVisibility() == View.VISIBLE)
        return;

    switch (messageBarType) {
        case INFO:
            txtMessageBar.setBackgroundResource(R.color.reader_message_bar_blue);
            break;
        case ALERT:
            txtMessageBar.setBackgroundResource(R.color.reader_message_bar_orange);
            break;
        default:
            return;
    }

    txtMessageBar.clearAnimation();
    txtMessageBar.setText(message);

    AniUtils.startAnimation(txtMessageBar, R.anim.reader_message_bar_in);
    txtMessageBar.setVisibility(View.VISIBLE);

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            hideMessageBar(activity, runnable, false);
        }
    }, DELAY_MILLIS);
}
 
Example 10
Project: Gui2Go   File: AbstractTreeViewAdapter.java View source code Vote up 6 votes
public AbstractTreeViewAdapter(final Activity activity, final TreeStateManager<T> treeStateManager,
        final int numberOfLevels) {
    this.activity = activity;
    this.treeStateManager = treeStateManager;
    this.layoutInflater = (LayoutInflater) activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    this.numberOfLevels = numberOfLevels;
    this.collapsedDrawable = null;
    this.expandedDrawable = null;
    this.rowBackgroundDrawable = null;
    this.indicatorBackgroundDrawable = null;
}
 
Example 11
Project: Pure-File-Manager   File: PasteTaskExecutor.java View source code Vote up 6 votes
private void next() {
    final Activity activity = this.mActivityReference.get();
    if (activity != null) {
        if (mExisting.isEmpty()) {

            if (mToProcess.isEmpty()) {
                ClipBoard.clear();
            } else {
                final GenericFile[] files = new GenericFile[mToProcess.size()];
                mToProcess.toArray(files);

                OperationsService.paste(activity, mTargetFile, files, ClipBoard.isMove());
            }

        } else {
            final GenericFile key = mExisting.keySet().iterator().next();
            final GenericFile target = mExisting.get(key);
            mCurrentPair = new Pair<>(key, target);
            mExisting.remove(key);

            if (!activity.isFinishing()) {
                if (Looper.myLooper() == Looper.getMainLooper()) {
                    showExistsDialog(activity, key, target);
                } else {
                    activity.runOnUiThread(new Runnable() {
                        @Override
                        public void run() {
                            showExistsDialog(activity, key, target);
                        }
                    });
                }
            }
        }
    }
}
 
Example 12
Project: ExcusePro   File: PickerFragment.java View source code Vote up 6 votes
@Override
public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
    super.onInflate(activity, attrs, savedInstanceState);
    TypedArray a = activity.obtainStyledAttributes(attrs, R.styleable.com_facebook_picker_fragment);

    setShowPictures(a.getBoolean(R.styleable.com_facebook_picker_fragment_show_pictures, showPictures));
    String extraFieldsString = a.getString(R.styleable.com_facebook_picker_fragment_extra_fields);
    if (extraFieldsString != null) {
        String[] strings = extraFieldsString.split(",");
        setExtraFields(Arrays.asList(strings));
    }

    showTitleBar = a.getBoolean(R.styleable.com_facebook_picker_fragment_show_title_bar, showTitleBar);
    titleText = a.getString(R.styleable.com_facebook_picker_fragment_title_text);
    doneButtonText = a.getString(R.styleable.com_facebook_picker_fragment_done_button_text);
    titleBarBackground = a.getDrawable(R.styleable.com_facebook_picker_fragment_title_bar_background);
    doneButtonBackground = a.getDrawable(R.styleable.com_facebook_picker_fragment_done_button_background);

    a.recycle();
}
 
Example 13
Project: ExcusePro   File: ActionBarSherlockCompat.java View source code Vote up 6 votes
private static int loadUiOptionsFromManifest(Activity activity) {
    int uiOptions = 0;
    try {
        final String thisPackage = activity.getClass().getName();
        if (ActionBarSherlock.DEBUG) Log.i(TAG, "Parsing AndroidManifest.xml for " + thisPackage);

        final String packageName = activity.getApplicationInfo().packageName;
        final AssetManager am = activity.createPackageContext(packageName, 0).getAssets();
        final XmlResourceParser xml = am.openXmlResourceParser("AndroidManifest.xml");

        int eventType = xml.getEventType();
        while (eventType != XmlPullParser.END_DOCUMENT) {
            if (eventType == XmlPullParser.START_TAG) {
                String name = xml.getName();

                if ("application".equals(name)) {
                    //Check if the <application> has the attribute
                    if (ActionBarSherlock.DEBUG) Log.d(TAG, "Got <application>");

                    for (int i = xml.getAttributeCount() - 1; i >= 0; i--) {
                        if (ActionBarSherlock.DEBUG) Log.d(TAG, xml.getAttributeName(i) + ": " + xml.getAttributeValue(i));

                        if ("uiOptions".equals(xml.getAttributeName(i))) {
                            uiOptions = xml.getAttributeIntValue(i, 0);
                            break; //out of for loop
                        }
                    }
                } else if ("activity".equals(name)) {
                    //Check if the <activity> is us and has the attribute
                    if (ActionBarSherlock.DEBUG) Log.d(TAG, "Got <activity>");
                    Integer activityUiOptions = null;
                    String activityPackage = null;
                    boolean isOurActivity = false;

                    for (int i = xml.getAttributeCount() - 1; i >= 0; i--) {
                        if (ActionBarSherlock.DEBUG) Log.d(TAG, xml.getAttributeName(i) + ": " + xml.getAttributeValue(i));

                        //We need both uiOptions and name attributes
                        String attrName = xml.getAttributeName(i);
                        if ("uiOptions".equals(attrName)) {
                            activityUiOptions = xml.getAttributeIntValue(i, 0);
                        } else if ("name".equals(attrName)) {
                            activityPackage = cleanActivityName(packageName, xml.getAttributeValue(i));
                            if (!thisPackage.equals(activityPackage)) {
                                break; //out of for loop
                            }
                            isOurActivity = true;
                        }

                        //Make sure we have both attributes before processing
                        if ((activityUiOptions != null) && (activityPackage != null)) {
                            //Our activity, uiOptions specified, override with our value
                            uiOptions = activityUiOptions.intValue();
                        }
                    }
                    if (isOurActivity) {
                        //If we matched our activity but it had no logo don't
                        //do any more processing of the manifest
                        break;
                    }
                }
            }
            eventType = xml.nextToken();
        }
    } catch (Exception e) {
        e.printStackTrace();
    }
    if (ActionBarSherlock.DEBUG) Log.i(TAG, "Returning " + Integer.toHexString(uiOptions));
    return uiOptions;
}
 
Example 14
Project: ExcusePro   File: ActionBarWrapper.java View source code Vote up 6 votes
public ActionBarWrapper(Activity activity) {
    mActivity = activity;
    mActionBar = activity.getActionBar();
    if (mActionBar != null) {
        mActionBar.addOnMenuVisibilityListener(this);

        // Fixes issue #746
        int displayOptions = mActionBar.getDisplayOptions();
        mActionBar.setHomeButtonEnabled((displayOptions & DISPLAY_HOME_AS_UP) != 0);
    }
}
 
Example 15
Project: android_packages_apps_AeroControl   File: AppRate.java View source code Vote up 6 votes
public static AppRate with(Activity activity) {

        if (activity == null) {
            throw new IllegalStateException("Activity cannot be null");
        }

        AppRate instance = new AppRate(activity);
        instance.text = activity.getString(R.string.dra_rate_app);
        instance.settings = activity.getSharedPreferences(PREFS_NAME, 0);
        instance.editor = instance.settings.edit();
        return instance;
    }
 
Example 16
Project: devcoin-android   File: SendCoinsFragment.java View source code Vote up 6 votes
@Override
public void onAttach(final Activity activity)
{
	super.onAttach(activity);

	this.activity = (AbstractBindServiceActivity) activity;
	this.application = (WalletApplication) activity.getApplication();
	this.prefs = PreferenceManager.getDefaultSharedPreferences(activity);
	this.wallet = application.getWallet();
	this.contentResolver = activity.getContentResolver();
	this.loaderManager = getLoaderManager();
}
 
Example 17
Project: TrustedIntents   File: TrustedIntents.java View source code Vote up 6 votes
public Intent getIntentFromTrustedSender(Activity activity)
        throws NameNotFoundException, CertificateException {
    Intent intent = activity.getIntent();
    if (!isIntentSane(intent))
        throw new NameNotFoundException(
                "Intent incomplete or was sent using startActivity() instead of startActivityWithResult()");
    String packageName = intent.getPackage();
    if (TextUtils.isEmpty(packageName)) {
        packageName = intent.getComponent().getPackageName();
    }
    if (TextUtils.isEmpty(packageName))
        throw new NameNotFoundException(packageName);
    checkTrustedSigner(packageName);
    return intent;
}
 
Example 18
Project: Pure-File-Manager   File: FilePropertiesDialog.java View source code Vote up 6 votes
private PropertiesAdapter(@NonNull final Activity context,
                          @NonNull final GenericFile file) {
    mLayoutInflater = context.getLayoutInflater();
    mFile = file;
    //noinspection ConstantConditions
    mItems = new PagerItem[]{
            new FilePropertiesPagerItem(mFile, Settings.getInstance(context), context
                    .getApplicationContext().getResources()),
            new FilePermissionsPagerItem(mFile)
    };
}
 
Example 19
Project: play-android   File: SongArtWrapper.java View source code Vote up 6 votes
/**
 * Create view wrapper to display art for a [email protected] Song}
 *
 * @param activity
 * @param service
 */
public SongArtWrapper(Activity activity,
		final AtomicReference<PlayService> service) {
	this.activity = activity;
	artFolder = getArtDirectory(activity);
	this.service = service;
	Resources resources = activity.getResources();
	maxSize = Math.round(resources.getDisplayMetrics().density
			* MAX_SIZE_DP + 0.5F);
}
 
Example 20
Project: deck_old   File: GameFragment.java View source code Vote up 6 votes
@Override
public void onServerDisconnect( String serverID )
{
    Activity activity = getActivity();
    if( activity != null )
    {
        activity.setResult( GameActivity.RESULT_DISCONNECTED_FROM_SERVER, new Intent( GameActivity.class.getName() ) );
        activity.finish();
    }
}
 
Example 21
Project: hacktoolkit-android_lib   File: ContactsUtils.java View source code Vote up 6 votes
public static ArrayList<HTKContact> getContactsWithPhone(Activity currentActivity) {
		ContentResolver contentResolver = currentActivity.getContentResolver();

		Uri uri = ContactsContract.Contacts.CONTENT_URI;
		String[] projection = {
				ContactsContract.Contacts._ID,
				ContactsContract.Contacts.DISPLAY_NAME,
				ContactsContract.Contacts.HAS_PHONE_NUMBER,
				ContactsContract.Contacts.STARRED,
				ContactsContract.Contacts.TIMES_CONTACTED,
				ContactsContract.Contacts.LAST_TIME_CONTACTED,
		};
		String selection = String.format("%s > 0", ContactsContract.Contacts.HAS_PHONE_NUMBER);
		String[] selectionArgs = null;
		String sortOrder = String.format(
				"%s DESC, %s DESC, %S DESC, UPPER(%s) ASC",
				ContactsContract.Contacts.STARRED,
				ContactsContract.Contacts.TIMES_CONTACTED,
				ContactsContract.Contacts.LAST_TIME_CONTACTED,
				ContactsContract.Contacts.DISPLAY_NAME
				);
		Cursor cursor = contentResolver.query(uri, projection, selection, selectionArgs, sortOrder);
		
		ArrayList<HTKContact> contacts = new ArrayList<HTKContact>();
		
		if (cursor.getCount() > 0) {
			while (cursor.moveToNext()) {
				HTKContact contact = new HTKContact();
				String contactId = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts._ID));
				String name = cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.DISPLAY_NAME));
				String phone = "";
				String phoneType = "";
				if (Integer.parseInt(cursor.getString(cursor.getColumnIndex(ContactsContract.Contacts.HAS_PHONE_NUMBER))) > 0) {
//					System.out.println("name : " + name + ", ID : " + id);

					String[] phoneData = getPhoneForContactId(contentResolver, contactId);
					phone = phoneData[0];
					phoneType = phoneData[1];

					contact.setData("id",  Integer.valueOf(contactId));
					contact.setData("name", name);
					contact.setData("phone", phone);
					contact.setData("phoneType", phoneType);
					contacts.add(contact);
				}
			}
			cursor.close();
		}
        return contacts;
	}
 
Example 22
Project: packages_apps_Launcher2   File: WidgetCursorAdapter.java View source code Vote up 6 votes
public static Cursor queryForNewContent(Activity a, ContentResolver cr, Intent intent) {

        Cursor cursor = null;
        if ((intent != null) && (a != null)) {
            cursor = a.managedQuery(Uri.parse(intent
                    .getStringExtra(LauncherIntent.Extra.Scroll.EXTRA_DATA_URI)), intent
                    .getStringArrayExtra(LauncherIntent.Extra.Scroll.EXTRA_PROJECTION), intent
                    .getStringExtra(LauncherIntent.Extra.Scroll.EXTRA_SELECTION), intent
                    .getStringArrayExtra(LauncherIntent.Extra.Scroll.EXTRA_SELECTION_ARGUMENTS),
                    intent.getStringExtra(LauncherIntent.Extra.Scroll.EXTRA_SORT_ORDER));

            if (cursor != null)
                cursor.setNotificationUri(cr, Uri.parse(intent
                        .getStringExtra(LauncherIntent.Extra.Scroll.EXTRA_DATA_URI)));
            else
                Log.d(LOG_TAG, "cursor null");

        } else {
            Log.d(LOG_TAG, "intent or activity null");
        }

        return cursor;
    }
 
Example 23
Project: my-ministry-assistant   File: HelpUtils.java View source code Vote up 6 votes
public static void showOpenSourceLicenses(Activity activity) {
    FragmentManager fm = activity.getFragmentManager();
    FragmentTransaction ft = fm.beginTransaction();
    Fragment prev = fm.findFragmentByTag("dialog_licenses");
    if (prev != null) {
        ft.remove(prev);
    }
    ft.addToBackStack(null);

    new OpenSourceLicensesDialog().show(ft, "dialog_licenses");
}
 
Example 24
Project: dlna   File: YouPlayerAppFrame.java View source code Vote up 6 votes
public void setFullScreen(Activity context){
    if(context != null){
        try {
        	fullPlayerControler.getView().setKeepScreenOn(true);
            context.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
            context.setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
 
Example 25
Project: flow-android   File: MainFlowActivity.java View source code Vote up 6 votes
/**
 * @param activity The activity that's requesting dispatch
 * @param adapter NfcAdapter for the current context
 */
private void enableForegroundDispatch(Activity activity, NfcAdapter adapter) {
    final Intent intent = new Intent(activity.getApplicationContext(), activity.getClass());
    intent.setFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP);

    final PendingIntent pendingIntent = PendingIntent.getActivity(activity.getApplicationContext(), 0, intent, 0);

    IntentFilter[] filters = new IntentFilter[1];
    String[][] techList = new String[][]{};

    // Notice that this is the same filter as in our manifest.
    filters[0] = new IntentFilter();
    filters[0].addAction(NfcAdapter.ACTION_NDEF_DISCOVERED);
    filters[0].addCategory(Intent.CATEGORY_DEFAULT);
    filters[0].addDataScheme("https");
    filters[0].addDataAuthority(Constants.FLOW_DOMAIN, null);
    filters[0].addDataPath(".*", PatternMatcher.PATTERN_SIMPLE_GLOB);

    adapter.enableForegroundDispatch(activity, pendingIntent, filters, techList);
}
 
Example 26
Project: android-transition   File: MenuItemTransition.java View source code Vote up 6 votes
@Override
public void stopTransition() {
    for (int i = 0, size = mTransittingMenuItems.size(); i < size; i++) {
        mTransittingMenuItems.get(i).end();
    }
    if (menuItemList == null) {
        return;
    }
    for (int i = 0, size = menuItemList.size(); i < size; i++) {
        menuItemList.get(i).setActionView(null);
    }
    mTransittingMenuItems.clear();
    if (mInvalidateOptionOnStopTransition) {
        Activity activity = getActivity();
        if (activity != null) {
            activity.invalidateOptionsMenu();
        }
    }
    mStarted = false;
}
 
Example 27
Project: DashClock_K-9   File: AboutDialogFragment.java View source code Vote up 6 votes
private String getVersionName() {
    String version = "?";
    try {
        Activity context = getActivity();
        String packageName = context.getPackageName();
        PackageInfo pi = context.getPackageManager().getPackageInfo(packageName, 0);
        version = pi.versionName;
    } catch (PackageManager.NameNotFoundException e) {
        // do nothing
    }
    return version;
}
 
Example 28
Project: climbers   File: LoginActivity.java View source code Vote up 6 votes
public static void onLogin(Activity activity, String accessToken, LoginProvider provider) {
	SharedPreferences sharedPref = activity.getPreferences(Activity.MODE_PRIVATE);
	SharedPreferences.Editor editor = sharedPref.edit();
	editor.putString("accessToken", accessToken);
	editor.putString("loginProvider", provider.name());
	editor.commit();
	
	authenticate(activity, accessToken, provider);
}
 
Example 29
Project: Android_ShareSDK_Example_OAuth   File: EditPage.java View source code Vote up 6 votes
public void setActivity(Activity activity) {
	super.setActivity(activity);
	if (dialogMode) {
		activity.setTheme(android.R.style.Theme_Dialog);
		activity.requestWindowFeature(Window.FEATURE_NO_TITLE);
	}
	activity.getWindow().setSoftInputMode(
		       WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);
}
 
Example 30
Project: packages_apps_Mms   File: InterceptSendSms.java View source code Vote up 6 votes
@Override
protected void setUp() throws Exception {
    Activity activity = getActivity();
    super.setUp();
    mRecipientsView = (TextView)activity.findViewById(R.id.recipients_editor);
    mTextEditor = (EditText)activity.findViewById(R.id.embedded_text_editor);

    // Setup our receiver to listen for SMS's about to be sent.
    mInterceptReceiver = new InterceptSmsReceiver();
    IntentFilter filter = new IntentFilter(WorkingMessage.ACTION_SENDING_SMS);
    activity.registerReceiver(mInterceptReceiver, filter);
}
 
Example 31
Project: devcoin-android   File: BitcoinIntegration.java View source code Vote up 6 votes
private static void startForResult(final Activity activity, final int requestCode, final Intent intent)
{
	final PackageManager pm = activity.getPackageManager();
	if (pm.resolveActivity(intent, 0) != null)
		activity.startActivityForResult(intent, requestCode);
	else
		redirectToDownload(activity);
}
 
Example 32
Project: PictureProcess   File: Util.java View source code Vote up 6 votes
public static void closeKeyboard(Activity ac) {
if(ac == null){
	return;
}
      InputMethodManager imm = (InputMethodManager) ac.getSystemService(Context.INPUT_METHOD_SERVICE);
      if(ac.getCurrentFocus() != null) { 
          imm.hideSoftInputFromWindow(ac.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
      }
  }
 
Example 33
Project: dubsar_android   File: MainActivityTest.java View source code Vote up 6 votes
protected void setUp() {
	Activity activity = getActivity();
	
	/* Start the service with mock data */
	Intent serviceIntent = new Intent(activity, DubsarService.class);
	serviceIntent.setAction(DubsarService.ACTION_WOTD_MOCK);
	serviceIntent.putExtra(BaseColumns._ID, 25441);
	serviceIntent.putExtra(DubsarService.WOTD_TEXT, "resourcefully (adv.)");
	serviceIntent.putExtra(DubsarContentProvider.WORD_NAME_AND_POS,
			"resourcefully (adv.)");
	activity.startService(serviceIntent);

	activity.finish();
}
 
Example 34
Project: PaintDrip   File: AppEventsLogger.java View source code Vote up 6 votes
/**
 * Source Application setters and getters
 */
private static void setSourceApplication(Activity activity) {

    ComponentName callingApplication = activity.getCallingActivity();
    if (callingApplication != null) {
        String callingApplicationPackage = callingApplication.getPackageName();
        if (callingApplicationPackage.equals(activity.getPackageName())) {
            // open by own app.
            resetSourceApplication();
            return;
        }
        sourceApplication = callingApplicationPackage;
    }

    // Tap icon to open an app will still get the old intent if the activity was opened by an intent before.
    // Introduce an extra field in the intent to force clear the sourceApplication.
    Intent openIntent = activity.getIntent();
    if (openIntent == null || openIntent.getBooleanExtra(SOURCE_APPLICATION_HAS_BEEN_SET_BY_THIS_INTENT, false)) {
        resetSourceApplication();
        return;
    }

    Bundle applinkData = AppLinks.getAppLinkData(openIntent);

    if (applinkData == null) {
        resetSourceApplication();
        return;
    }

    isOpenedByApplink = true;

    Bundle applinkReferrerData = applinkData.getBundle("referer_app_link");

    if (applinkReferrerData == null) {
        sourceApplication = null;
        return;
    }

    String applinkReferrerPackage = applinkReferrerData.getString("package");
    sourceApplication = applinkReferrerPackage;

    // Mark this intent has been used to avoid use this intent again and again.
    openIntent.putExtra(SOURCE_APPLICATION_HAS_BEEN_SET_BY_THIS_INTENT, true);

    return;
}
 
Example 35
Project: tuberun_android   File: SlidingBehaviour.java View source code Vote up 6 votes
private void init(Activity activity,int mainLayout) {
   	//Prepare the menu
   	menu = new SlidingMenu(activity);
       menu.setMode(SlidingMenu.LEFT);
       menu.setTouchModeAbove(SlidingMenu.TOUCHMODE_NONE);
       menu.setFadeDegree(0.35f);
       menu.setBehindOffsetRes(R.dimen.slidingmenu_offset);
       menu.setMenu(new MainMenu(activity, menu));
       
       //find the menu buttons in the layout.
	LayoutInflater inflater = LayoutInflater.from(activity);
	View app = inflater.inflate(mainLayout, null);
       ViewGroup tabBar = (ViewGroup) app.findViewById(R.id.main_layout);
       Button showMenuButton1 = (Button) tabBar.findViewById(R.id.logo_button);
       Button showMenuButton2 = (Button) tabBar.findViewById(R.id.back_button);
       MenuClickListener l=new MenuClickListener();
       showMenuButton1.setOnClickListener(l);
       showMenuButton2.setOnClickListener(l);
       
       activity.setContentView(app);
       menu.attachToActivity(activity, SlidingMenu.SLIDING_CONTENT);
}
 
Example 36
Project: CeaselessAndroid   File: FragmentUtils.java View source code Vote up 6 votes
public static void loadFragment(Activity activity, FragmentManager fragmentManager, NavigationView navigation,
                                int resourceId, Bundle loadingFragmentState /* state of the fragment being loaded */,
                                FragmentState backStackInfo) {
    Fragment fragment = getFragmentForResourceId(resourceId);
    String fragmentTag = getFragmentTagForResourceId(activity, resourceId);
    Fragment fragmentForTag = fragmentManager.findFragmentByTag(fragmentTag);
    if (fragment != null && (fragmentForTag == null || !fragmentForTag.isVisible())) {
        if (backStackInfo != null) {
            ((MainActivity) activity).getFragmentBackStackManager().add(backStackInfo);
        }
        fragment.setArguments(loadingFragmentState);
        fragmentManager.beginTransaction().replace(R.id.fragment, fragment, fragmentTag).commit();
        if (navigation != null && fragmentTag != null) {
            navigation.setCheckedItem(getNavigationItemIdForFragmentName(activity, fragmentTag));
        }
        activity.setTitle(fragmentTag);
    } else {
        Log.d(TAG, String.format("Required fragment %s already visible, not reloading", fragmentTag));
    }
}
 
Example 37
Project: astrid   File: FilterListFragment.java View source code Vote up 6 votes
@Override
public void onResume() {
    super.onResume();
    StatisticsService.sessionStart(getActivity());
    if(adapter != null)
        adapter.registerRecevier();

    // also load sync actions
    Activity activity = getActivity();

    Intent broadcastIntent = new Intent(AstridApiConstants.BROADCAST_REQUEST_SYNC_ACTIONS);
    activity.sendOrderedBroadcast(broadcastIntent, AstridApiConstants.PERMISSION_READ);

    if (activity instanceof TaskListActivity) {
        ((TaskListActivity) activity).setupPopoverWithFilterList(this);
    }

    activity.registerReceiver(refreshReceiver,
            new IntentFilter(AstridApiConstants.BROADCAST_EVENT_REFRESH));

}
 
Example 38
Project: quick-settings   File: VolumeDialog.java View source code Vote up 6 votes
public void onClick(View v) {
	switch (v.getId()) {
		case R.id.button1: {
			

			AudioManager manager = mManager; Dialog dialog = mDialog;
			int size = STREAM_TYPES.length; SeekBar seek;
			for (int i=size; i-->0;) {
				//if (i == 1 && mChecked) continue; // ignore notification volume - we use ringer volume instead
				seek = (SeekBar) dialog.findViewById(SLIDER_IDS[i]);
				manager.setStreamVolume(STREAM_TYPES[i], seek.getProgress(), 0);
			}
			
			Activity activity = mActivity;
			
			// check if we have to switch silent / not silen mode
			int ringerVolume = manager.getStreamVolume(AudioManager.STREAM_RING);
			int notifVolume = manager.getStreamVolume(AudioManager.STREAM_NOTIFICATION);
			int ringerMode = manager.getRingerMode();
			if (ringerVolume > 0 && ringerMode == AudioManager.RINGER_MODE_SILENT) {
				Toast.makeText(activity, activity.getString(R.string.msg_not_silent_warning, ringerVolume), Toast.LENGTH_LONG).show();
			} else if (ringerVolume == 0 && ringerMode == AudioManager.RINGER_MODE_NORMAL) {
				Toast.makeText(activity, R.string.msg_zero_ringer_warning, Toast.LENGTH_LONG).show();
			} else if (notifVolume == 0 && ringerMode == AudioManager.RINGER_MODE_NORMAL) {
				Toast.makeText(activity, R.string.msg_zero_notification_warning, Toast.LENGTH_LONG).show();
			}
			
			// send internal volume changed notification
			activity.sendBroadcast(new Intent(Constants.ACTION_VOLUME_UPDATED));
			
			hide();
			break;
		}
		case R.id.button2: {

			// revert initial checked state
			if (mChecked != mInitialChecked) setUseRingerVolume(mInitialChecked);
			
			hide();
			break;
		}
	}
}
 
Example 39
Project: deck_old   File: DeviceListActivity.java View source code Vote up 6 votes
@Override
public void onPause()
{
    super.onPause();

    final Activity activity = getActivity();
    if( activity != null )
    {
        Crouton.clearCroutonsForActivity( getActivity() );

        if( mRegisteredReceiver )
        {
            activity.unregisterReceiver( mReceiver );
        }
    }
}
 
Example 40
Project: aLogMyNight   File: Dispatcher.java View source code Vote up 6 votes
public Dispatcher(Activity activity) {
    this.activity = activity;
    handlers = new HashMap<String, Class>();
    layout = new LinearLayout(activity);
    activity.addContentView(
            layout, new LayoutParams(
                    LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
    isWebViewShown = false;
    showWebView();
}
 
Example 41
Project: rss   File: ListFragmentTag.java View source code Vote up 6 votes
@Override
public
void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo)
{
    super.onCreateContextMenu(menu, v, menuInfo);

    boolean hasImage = ((ViewFeedItem) ((AdapterView.AdapterContextMenuInfo) menuInfo).targetView).m_hasImage;

    // Inflate the context menu from the xml file.
    Activity activity = getActivity();
    MenuInflater inflater = activity.getMenuInflater();
    inflater.inflate(R.menu.context_menu, menu);

    // Show the 'Save image' option only when the view has an image.
    menu.findItem(R.id.save_image).setVisible(hasImage);

    // Set the title of the context menu to the feed item's title.
    AdapterView.AdapterContextMenuInfo info = (AdapterView.AdapterContextMenuInfo) menuInfo;
    FeedItem view = (FeedItem) ((AdapterView<ListAdapter>) v).getAdapter()
            .getItem(info.position);
    menu.setHeaderTitle(view.m_title);
}
 
Example 42
Project: chbosync4android   File: AndroidDisplayManager.java View source code Vote up 6 votes
/**
 * Create a native alert dialog with the 2 options "Yes" and "No".
 * This kind of alert are managed by the activity owner when the call to
 * onCreateDialog is done.
 * @param screen the native alert dialog owner Screen
 * @param question the question to be displayed
 * @param yesAction the runnable that defines the yes option
 * @param noAction the runnable that defines the no option
 * @param timeToWait to be defined
 */
public void askYesNoQuestion(Screen screen, String question,
        Runnable yesAction,
        Runnable noAction, long timeToWait) {

    int dialogId = getNextDialogId();
    Activity activity = (Activity) screen.getUiScreen();

    AlertDialog.Builder alert = new AlertDialog.Builder(activity);
    alert.setMessage(question);
    alert.setCancelable(false);
    OnButtonListener yesListener = new OnButtonListener(yesAction);
    OnButtonListener noListener = new OnButtonListener(noAction);
    alert.setPositiveButton(android.R.string.ok, yesListener);
    alert.setNegativeButton(android.R.string.cancel, noListener);

    holdingDialogs.put(dialogId, alert);

    activity.showDialog(dialogId);
}
 
Example 43
Project: kanqiu_letv   File: UIs.java View source code Vote up 6 votes
public static void call(Activity activity, int messageId, DialogInterface.OnClickListener yes) {

		if (activity == null) {
			return;
		}

		Dialog dialog = new AlertDialog.Builder(activity).setTitle(R.string.dialog_default_title).setIcon(R.drawable.dialog_icon).setMessage(messageId)
				.setPositiveButton(R.string.dialog_default_ok, yes).create();

		if (!activity.isFinishing() && !activity.isRestricted()) {
			dialog.show();
		}
	}
 
Example 44
Project: AndroidBinding   File: FilterCursorList.java View source code Vote up 6 votes
public FilterCursorList(Activity activity) {
	mContext = activity;
	CursorSrc = new TrackedCursorCollection<FilteredCursorRowModel>(FilteredCursorRowModel.class);
	mCursorSrc = mContext.getContentResolver().query(mTrackingUri, new String[]{"_ID", "Name", "detailsCount"}, null, null, null);
	activity.startManagingCursor(mCursorSrc);
	CursorSrc.setCursor(mCursorSrc);
	CursorSrc.setContentObserverTrackingUri(mContext, mTrackingUri, false);
}
 
Example 45
Project: slide_android   File: DisplayUtils.java View source code Vote up 6 votes
private static void buildDisplaySizes(Activity pActivity) {
	if(!pActivity.equals(sActivity)) {
		setDisplayParameters(pActivity);
	}
	
	sDisplaySizes = new ArrayList<Point>();
	
	int xMax = (sDisplayWidth - 160) / 100;
	int yMax = (sDisplayHeight - 160) / 100;
	
	int min = 3;
	int max = xMax < yMax ? xMax : yMax;
	int alt = xMax < yMax ? yMax : xMax;
	
	for(int i = min; i<=max; i++) {
		if(i > alt)
			break;
		
		sDisplaySizes.add(new Point(i,i));
		
		if(i+1 <= alt)
			sDisplaySizes.add(new Point(i, i+1));
	}
}
 
Example 46
Project: ExcusePro   File: ExcuseListActivity.java View source code Vote up 6 votes
private void showDemo() {
	final Activity activity = ExcuseListActivity.this;
	Handler handler = new Handler();
	WindowManager manager = activity.getWindowManager();
	DisplayMetrics displayMetrics = new DisplayMetrics();
	manager.getDefaultDisplay().getMetrics(displayMetrics);
	handler.postDelayed(new Runnable() {
		
		@SuppressLint("Recycle")
		@Override
		public void run() {
			// TODO Auto-generated method stub
			showcaseView = new ShowcaseView(activity);
			View view = ((ExcuseListAdapter)swipeListView.getAdapter()).getViewHolder(0, swipeListView).getFrontView();
			int[] location = new int[2];
			view.getLocationInWindow(location);
			logger.debug("Coords - " + location[0] + "--" + location[1]);
			int viewHeight = view.getHeight()/2;
			MotionEvent motionEvent1 = MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis() + 100, MotionEvent.ACTION_DOWN, location[0] + view.getWidth(), location[1] + viewHeight, 1, 1, 0, 1, 1, 0, 0);
			MotionEvent motionEvent2 = MotionEvent.obtain(SystemClock.uptimeMillis() + 100, SystemClock.uptimeMillis() + 150, MotionEvent.ACTION_MOVE, location[0] + view.getWidth(), location[1] + viewHeight, 1, 1, 0, 1, 1, 0, 0);
			MotionEvent motionEvent3 = MotionEvent.obtain(SystemClock.uptimeMillis() + 500, SystemClock.uptimeMillis() + 1000, MotionEvent.ACTION_UP, location[0]+ 100, location[1] + viewHeight, 1, 1, 0, 1, 1, 0, 0);
			swipeListView.dispatchTouchEvent(motionEvent1);
			logger.debug("Dispatched first event");
			swipeListView.dispatchTouchEvent(motionEvent2);
			logger.debug("Dispatched second event");
			swipeListView.dispatchTouchEvent(motionEvent3);
			logger.debug("Dispatched third event");
			ConfigOptions configOptions = new ConfigOptions();
			configOptions.hideOnClickOutside = true;
			configOptions.block = true;
			showcaseView = ShowcaseView.insertShowcaseView(view, activity);
			showcaseView.animateGesture(location[0] + view.getWidth(), location[1] + viewHeight, 0, location[1] + viewHeight);
			preferences.setIsDemoDone(true);
		}
	}, 500);
}
 
Example 47
Project: kdeconnect-android   File: SendFileActivity.java View source code Vote up 6 votes
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    mDeviceId = getIntent().getStringExtra("deviceId");

    Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    intent.setType("*/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);
    try {
        startActivityForResult(
                Intent.createChooser(intent, getString(R.string.send_files)), Activity.RESULT_FIRST_USER);
    } catch (android.content.ActivityNotFoundException ex) {
        Toast.makeText(this, R.string.no_file_browser, Toast.LENGTH_SHORT).show();
        finish();
    }
}
 
Example 48
Project: cardslib   File: MultiChoiceAdapterHelperBase.java View source code Vote up 6 votes
public boolean startActionMode(Activity activity) {
    if (activity!=null){
        if (!isActionModeStarted())
            activity.startActionMode(mMultiChoiceModeListener);
    }
    return false;
}
 
Example 49
Project: Mortar-architect   File: ActivityArchitector.java View source code Vote up 6 votes
public static MortarScope onCreateScope(Activity activity, Bundle savedInstanceState, Architected architected) {
    String scopeName = activity.getLocalClassName() + "-task-" + activity.getTaskId();
    MortarScope scope = MortarScope.findChild(activity.getApplicationContext(), scopeName);
    if (scope == null) {
        MortarScope parentScope = MortarScope.getScope(activity.getApplicationContext());

        MortarScope.Builder builder = parentScope.buildChild()
                .withService(BundleServiceRunner.SERVICE_NAME, new BundleServiceRunner());
        architected.configureScope(builder, parentScope);
        scope = builder.build(scopeName);

        architected.createNavigator(scope);
    }

    BundleServiceRunner.getBundleServiceRunner(scope).onCreate(savedInstanceState);

    return scope;
}
 
Example 50
Project: PARWorks-Android-MARS   File: MapImageManager.java View source code Vote up 6 votes
public MapImageManager(String siteId, ImageView mapImageView, ImageView mapShadowImageView, ProgressBar mapImageProgressBar, Activity activity) {
	mMapImageView = mapImageView;
	mMapShadowImageView = mapShadowImageView;
	mMapImageView.setAdjustViewBounds(true);
	mMapImageView.setScaleType(ScaleType.CENTER_CROP);
	mMapImageProgressBar = mapImageProgressBar;
	mActivity = activity;
	mContext = activity.getBaseContext();
	mSiteId = siteId;
	mViewDimensionCalculator = new ViewDimensionCalculator(mActivity);

}
 
Example 51
Project: platform-android   File: AboutActivity.java View source code Vote up 6 votes
/**
 * Show the activity as an popup
 *
 * @param activity The calling activity
 */
public void showAsPopup(Activity activity) {
    // To show activity as dialog and dim the background, you need to declare
    // android:theme="@style/PopupTheme" on for the chosen activity on the manifest
    activity.getWindow().setFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND,
            WindowManager.LayoutParams.FLAG_DIM_BEHIND);
    WindowManager.LayoutParams params = activity.getWindow().getAttributes();
    params.dimAmount = 0.5f;
    if (activity.getRequestedOrientation() == ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE) {
        params.height = WindowManager.LayoutParams.MATCH_PARENT;
    } else {
        params.height = 700;
    }
    params.width = 680; //fixed width
    params.alpha = 1.0f;
    params.dimAmount = 0.5f;
    activity.getWindow().setAttributes((params));
}
 
Example 52
Project: cordova-androidwear   File: AndroidWearPlugin.java View source code Vote up 6 votes
@Override
public void onDestroy() {
	Log.d(TAG, "onDestroy");

	try {
		Activity context = cordova.getActivity();
		
		if (api != null)
			api.removeListener(messageListener);

		context.unbindService(serviceConnection);
		context.stopService(serviceIntent);
	} catch (Throwable t) {
		// catch any issues, typical for destroy routines
		// even if we failed to destroy something, we need to continue
		// destroying
		Log.w(TAG, "Failed to unbind from the service", t);
	}

	super.onDestroy();
}
 
Example 53
Project: property-db   File: NfcAdapter.java View source code Vote up 6 votes
/**
 * Enable foreground dispatch to the given Activity.
 *
 * <p>This will give give priority to the foreground activity when
 * dispatching a discovered [email protected] Tag} to an application.
 *
 * <p>If any IntentFilters are provided to this method they are used to match dispatch Intents
 * for both the [email protected] NfcAdapter#ACTION_NDEF_DISCOVERED} and
 * [email protected] NfcAdapter#ACTION_TAG_DISCOVERED}. Since [email protected] NfcAdapter#ACTION_TECH_DISCOVERED}
 * relies on meta data outside of the IntentFilter matching for that dispatch Intent is handled
 * by passing in the tech lists separately. Each first level entry in the tech list represents
 * an array of technologies that must all be present to match. If any of the first level sets
 * match then the dispatch is routed through the given PendingIntent. In other words, the second
 * level is ANDed together and the first level entries are ORed together.
 *
 * <p>If you pass [email protected] null} for both the [email protected] filters} and [email protected] techLists} parameters
 * that acts a wild card and will cause the foreground activity to receive all tags via the
 * [email protected] NfcAdapter#ACTION_TAG_DISCOVERED} intent.
 *
 * <p>This method must be called from the main thread, and only when the activity is in the
 * foreground (resumed). Also, activities must call [email protected] #disableForegroundDispatch} before
 * the completion of their [email protected] Activity#onPause} callback to disable foreground dispatch
 * after it has been enabled.
 *
 * <p class="note">Requires the [email protected] android.Manifest.permission#NFC} permission.
 *
 * @param activity the Activity to dispatch to
 * @param intent the PendingIntent to start for the dispatch
 * @param filters the IntentFilters to override dispatching for, or null to always dispatch
 * @param techLists the tech lists used to perform matching for dispatching of the
 *      [email protected] NfcAdapter#ACTION_TECH_DISCOVERED} intent
 * @throws IllegalStateException if the Activity is not currently in the foreground
 */
public void enableForegroundDispatch(Activity activity, PendingIntent intent,
        IntentFilter[] filters, String[][] techLists) {
    if (activity == null || intent == null) {
        throw new NullPointerException();
    }
    if (!activity.isResumed()) {
        throw new IllegalStateException("Foreground dispatch can only be enabled " +
                "when your activity is resumed");
    }
    try {
        TechListParcel parcel = null;
        if (techLists != null && techLists.length > 0) {
            parcel = new TechListParcel(techLists);
        }
        ActivityThread.currentActivityThread().registerOnActivityPausedListener(activity,
                mForegroundDispatchListener);
        sService.setForegroundDispatch(intent, filters, parcel);
    } catch (RemoteException e) {
        attemptDeadServiceRecovery(e);
    }
}
 
Example 54
Project: property-db   File: ShareCompat.java View source code Vote up 6 votes
/**
 * Retrieve the name of the package that launched calledActivity from a share intent.
 * Apps that provide social sharing functionality can use this to provide attribution
 * for the app that shared the content.
 *
 * <p><em>Note:</em> This data may have been provided voluntarily by the calling
 * application. As such it should not be trusted for accuracy in the context of
 * security or verification.</p>
 *
 * @param calledActivity Current activity that was launched to share content
 * @return Name of the calling package
 */
public static String getCallingPackage(Activity calledActivity) {
    String result = calledActivity.getCallingPackage();
    if (result == null) {
        result = calledActivity.getIntent().getStringExtra(EXTRA_CALLING_PACKAGE);
    }
    return result;
}
 
Example 55
Project: jdroid   File: UriMapper.java View source code Vote up 6 votes
public void handleUri(Activity activity, Bundle savedInstanceState, UriHandler uriHandler) {
	if (savedInstanceState == null) {

		Uri uri = activity.getIntent().getData();
		if (uri != null && uri.toString() != null && !uri.toString().startsWith(NotificationBuilder.NOTIFICATION_URI)) {

			if (uriHandler.matches(uri)) {
				Intent intent = uriHandler.getStartIntent(activity, uri);
				if (intent != null) {
					activity.setIntent(intent);
				}
			} else {
				AbstractApplication.get().getExceptionHandler().logWarningException("Uri doesn't match with the handler: " + uri.toString());
			}

			AppLoadingSource appLoadingSource;
			if (uri.getScheme() == null) {
				appLoadingSource = AppLoadingSource.NORMAL;
				AbstractApplication.get().getExceptionHandler().logWarningException("Uri with null scheme: " + uri.toString());
			} else if (uri.getScheme().startsWith("http")) {
				appLoadingSource = AppLoadingSource.URL;
				AbstractApplication.get().getAnalyticsSender().trackUriOpened(appLoadingSource.getName(), activity.getClass().getSimpleName());
			} else {
				appLoadingSource = AppLoadingSource.DEEPLINK;
				AbstractApplication.get().getAnalyticsSender().trackUriOpened(appLoadingSource.getName(), activity.getClass().getSimpleName());
			}
			appLoadingSource.flagIntent(activity.getIntent());

		}
	}
}
 
Example 56
Project: MaterialPreferenceLibrary   File: SettingsActivity.java View source code Vote up 6 votes
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static void restartActivity(final Activity activity)
  {
  if(android.os.Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB)
    activity.recreate();
  else
    {
    new Handler().post(new Runnable()
    {
    @Override
    public void run()
      {
      activity.overridePendingTransition(0,0);
      activity.startActivity(activity.getIntent());
      }
    });
    activity.finish();
    }
  }
 
Example 57
Project: DJDPlayer   File: MusicUtils.java View source code Vote up 6 votes
public static ServiceToken bindToService(Activity context, ServiceConnection callback) {
    Activity realActivity = context.getParent();
    if (realActivity == null) {
        realActivity = context;
    }
    ContextWrapper cw = new ContextWrapper(realActivity);
    cw.startService(new Intent(cw, MediaPlaybackService.class));
    ServiceBinder sb = new ServiceBinder(callback);
    if (cw.bindService((new Intent()).setClass(cw, MediaPlaybackService.class), sb, 0)) {
        sConnectionMap.put(cw, sb);
        return new ServiceToken(cw);
    }
    Log.e(LOGTAG, "Failed to bind to service");
    return null;
}
 
Example 58
Project: WearPomodoro   File: RecentTasksStyler.java View source code Vote up 6 votes
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
public static void styleRecentTasksEntry(Activity activity, int colorPrimary) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        return;
    }

    Resources resources = activity.getResources();
    String label = resources.getString(activity.getApplicationInfo().labelRes);

    if (sIcon == null) {
        // Cache to avoid decoding the same bitmap on every Activity change
        sIcon = BitmapFactory.decodeResource(resources, R.drawable.ic_stat_pomodoro);
    }

    activity.setTaskDescription(new ActivityManager.TaskDescription(label, sIcon, colorPrimary));
}
 
Example 59
Project: spikes   File: Binder.java View source code Vote up 6 votes
public void unbindCustomTabsService(@NonNull Activity activity) {
    if (isDisconnected()) {
        return;
    }

    activity.unbindService(serviceConnection);
    serviceConnection.onServiceDisconnected(null);
    serviceConnection = null;
}
 
Example 60
Project: rss   File: FragmentWebView.java View source code Vote up 6 votes
@Override
public
boolean onOptionsItemSelected(MenuItem item)
{
    // If the back button in the ActionBar is selected, call the Activity's onBackPressed().
    if(android.R.id.home == item.getItemId())
    {
        Activity activity = getActivity();
        activity.onBackPressed();
        return true;
    }
    return super.onOptionsItemSelected(item);
}
 
Example 61
Project: tuberun_android   File: Favorite.java View source code Vote up 6 votes
public static void storeToFile(Activity activity) {

		FileOutputStream fos;
		try {
			activity.deleteFile(FILENAME);
			fos = activity.openFileOutput(FILENAME, Context.MODE_PRIVATE);
			ObjectOutputStream oo = new ObjectOutputStream(fos);
			for (Favorite f : favorites) {
				oo.writeObject(f);
			}
			oo.close();
		} catch (Exception e) {
			Log.w("Favorite.java", e);
		}

	}
 
Example 62
Project: packages_apps_Calendar   File: EditEventFragment.java View source code Vote up 6 votes
@Override
public void onPause() {
    Activity act = getActivity();
    if (mSaveOnDetach && act != null && !mIsReadOnly && !act.isChangingConfigurations()
            && mView.prepareForSave()) {
        mOnDone.setDoneCode(Utils.DONE_SAVE);
        mOnDone.run();
    }
    super.onPause();
}
 
Example 63
Project: RajawaliOpenAL   File: OpenAlBridge.java View source code Vote up 6 votes
public static String getWavPath(Activity activity, String name)
		throws IOException {

	String filename = name + ".wav";
	File file = new File(activity.getFilesDir() , filename);

	if (!file.exists()) {
		Log.w(TAG, file + " not found, copying from assets");
		retrieveFromAssets(activity, filename);
	} else {
	}

	return file.getAbsolutePath();
}
 
Example 64
Project: DungeonSketch   File: TagNavigator.java View source code Vote up 6 votes
private TagTreeLineItem createTextView() {
	TagTreeLineItem view = new TagTreeLineItem(this.getContext());
	view.setOnClickListener(new TagLineItemClickedListener());
	view.setTextSize(this.mTextSize);
	view.setPadding(0, VERTICAL_PADDING, 0, VERTICAL_PADDING);
	if (mAllowContextMenu) {
		Activity activity = (Activity) this.getContext();
        activity.registerForContextMenu(view);
	}
       if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
           view.setOnDragListener(new OnDragListener());
       }
	view.setVisibility(View.GONE);
	
	return view;
}
 
Example 65
Project: CareAndroid   File: Renren.java View source code Vote up 6 votes
private void authorize(Activity activity, String[] permissions,
		final RenrenDialogListener listener, String redirectUrl,
		String responseType) {
	// ??CookieManager.getInstance??
	// ?????CookieSyncManager.createInstance
	CookieSyncManager.createInstance(activity);

	Bundle params = new Bundle();
	params.putString("client_id", apiKey);
	params.putString("redirect_uri", redirectUrl);
	params.putString("response_type", responseType);
	params.putString("display", "touch");
	
	//???????????????????????
	if(permissions == null) {
		permissions = DEFAULT_PERMISSIONS;
	}
	
	if (permissions != null && permissions.length > 0) {
		String scope = TextUtils.join(" ", permissions);
		params.putString("scope", scope);
	}

	String url = AUTHORIZE_URL + "?" + Util.encodeUrl(params);
	if (activity.checkCallingOrSelfPermission(Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
		Util.showAlert(activity, "????", "????????????");
	} else {
		new RenrenDialog(activity, url, listener).show();
	}
}
 
Example 66
Project: WordPress-Android   File: Utils.java View source code Vote up 6 votes
public static String getHtmlFromFile(Activity activity, String filename) {
    try {
        AssetManager assetManager = activity.getAssets();
        InputStream in = assetManager.open(filename);
        return getStringFromInputStream(in);
    } catch (IOException e) {
        AppLog.e(AppLog.T.EDITOR, e.getMessage());
        return null;
    }
}
 
Example 67
Project: chbosync4android   File: AndroidDisplayManager.java View source code Vote up 6 votes
/**
 * Dismiss an alert dialog from a screen given its id
 * @param screen the native alert dialog owner Screen
 * @param id the id of the dialog to be dismissed
 */
public void dismissProgressDialog(Screen screen, int id) {
    if (Log.isLoggable(Log.DEBUG)) {
        Log.debug(TAG, "Dismissing progress dialog " + id);
    }
    if(screen == null) {
        if (Log.isLoggable(Log.TRACE)) {
            Log.trace(TAG, "Cannot dismiss progress dialog, the screen "
                    + "reference is null");
        }
        return;
    }
    Activity activity = (Activity) screen.getUiScreen();
    try {
        activity.dismissDialog(id);
        activity.removeDialog(id);
    } catch (Exception e) {
        Log.error(TAG, "Failed at dismissing dialog " + id, e);
    }
    holdingDialogs.remove(id);
}
 
Example 68
Project: explor   File: FileIO.java View source code Vote up 6 votes
/**
 * Read the contents of the file indicated by fileName
 * 
 * @param activity
 * @param fileName
 * @return the contents
 * @throws IOException
 */
public static String read(Activity activity, String fileName) 
        throws IOException {
    FileInputStream is = activity.openFileInput(fileName);
    BufferedReader br = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();
    while (br.ready()) {
        String line = br.readLine();
        sb.append(line);
    }
    String data = sb.toString();
    return data;
}
 
Example 69
Project: viaja-facil   File: ViajaFacilActivity.java View source code Vote up 6 votes
public Account getStoredAccount() {
	final SharedPreferences preferences = getSharedPreferences(PREFS_ACCOUNT_PREFS, Activity.MODE_PRIVATE);
	String accountname = preferences.getString(PREFS_ACCOUNT_NAME, null);
	AccountManager accountManager = AccountManager.get(getApplicationContext());
	Account account = null;
	if(accountname != null) {
		Account[] accounts = accountManager.getAccountsByType("com.google");
		for(Account a : accounts) {
			if(a.toString().equalsIgnoreCase(accountname)) {
				account = a;
			}
		}
	}
	return account;
}
 
Example 70
Project: android_packages_apps   File: VoicemailPlaybackFragment.java View source code Vote up 6 votes
@Override
public void setVolumeControlStream(int streamType) {
    Activity activity = mActivityReference.get();
    if (activity != null) {
        activity.setVolumeControlStream(streamType);
    }
}
 
Example 71
Project: ARKOST   File: PluginLoader.java View source code Vote up 6 votes
/**
 * Initializes the services from the loaded plugins and stores them in the pluginmap
 */
private void initService(List<ResolveInfo> list, Activity activity, PluginType pluginType){
	for (int i = 0; i < list.size(); ++i) {
		ResolveInfo info = list.get(i);
		ServiceInfo sinfo = info.serviceInfo;
		if (sinfo != null) {
			Intent serviceIntent = new Intent();
			serviceIntent.setClassName(sinfo.packageName, sinfo.name);
			activity.startService(serviceIntent);
			activity.bindService(serviceIntent, (ServiceConnection)pluginType.getPluginConnection(),
					Context.BIND_AUTO_CREATE);
			checkForPendingActivity(pluginType);
		}
	}
}
 
Example 72
Project: andlytics   File: MainListAdapter.java View source code Vote up 6 votes
public MainListAdapter(Activity activity, String accountname, StatsMode statsMode) {
	BLACK_TEXT = activity.getResources().getColor(R.color.blackText);
	BLUE_TEXT = activity.getResources().getColor(R.color.lightBlue);
	this.setAppInfos(new ArrayList<AppInfo>());
	this.layoutInflater = activity.getLayoutInflater();
	this.activity = activity;
	this.spacerIcon = activity.getResources().getDrawable(R.drawable.app_icon_spacer);
	this.accountname = accountname;
	this.cachDir = activity.getCacheDir();
	this.inMemoryCache = AppIconInMemoryCache.getInstance();
	this.animationList = Collections.synchronizedList(new ArrayList<Integer>());
	this.upInterpolator = new AccelerateInterpolator(1.7f);
	this.downInterpolator = new BounceInterpolator();

	displayMetrics = new DisplayMetrics();
	activity.getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
	this.expandViewHeight = Math.round(displayMetrics.scaledDensity * 150);
	this.expandMargin = Math.round(displayMetrics.scaledDensity * 5);
	this.iconDown = activity.getResources().getDrawable(R.drawable.icon_down);
	this.iconUp = activity.getResources().getDrawable(R.drawable.icon_up);

	this.setStatsMode(statsMode);
}
 
Example 73
Project: androidquery   File: Common.java View source code Vote up 5 votes
public static void showProgress(Object p, String url, boolean show){
	
	if(p != null){
		
		if(p instanceof View){				

			View pv = (View) p;
			
			ProgressBar pbar = null;
			
			if(p instanceof ProgressBar){
				pbar = (ProgressBar) p;
			}
			
			if(show){
				pv.setTag(AQuery.TAG_URL, url);
				pv.setVisibility(View.VISIBLE);
				if(pbar != null){
					pbar.setProgress(0);	
					pbar.setMax(100);
				}
				
			}else{
				Object tag = pv.getTag(AQuery.TAG_URL);
				if(tag == null || tag.equals(url)){
					pv.setTag(AQuery.TAG_URL, null);	
					
					if(pbar == null || pbar.isIndeterminate()){
						pv.setVisibility(View.GONE);						
					}
				}
			}
		}else if(p instanceof Dialog){
			
			Dialog pd = (Dialog) p;
			
			AQuery aq = new AQuery(pd.getContext());
			
			if(show){
				aq.show(pd);
			}else{
				aq.dismiss(pd);
			}
			
		}else if(p instanceof Activity){
			
			Activity act = (Activity) p;;
			act.setProgressBarIndeterminateVisibility(show);
			act.setProgressBarVisibility(show);
		
			if(show){
				act.setProgress(0);
			}
		}
	}
	
}