Example usage for android.content ComponentName ComponentName

List of usage examples for android.content ComponentName ComponentName

Introduction

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

Prototype

private ComponentName(String pkg, Parcel in) 

Source Link

Usage

From source file:br.org.funcate.dynamicforms.markers.MarkersUtilities.java

private static Intent prepareIntent(Context context, File image, double[] gpsLocation) {
    Intent sketchIntent = null;//from  w w  w .  j a  va 2 s. c om
    if (MARKERS_IS_INTEGRATED) {
        try {
            sketchIntent = new Intent(context, Class.forName(APP_MAIN_ACTIVITY));
        } catch (ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    } else {
        sketchIntent = new Intent();
        sketchIntent.setComponent(
                new ComponentName(MarkersUtilities.APP_PACKAGE, MarkersUtilities.APP_MAIN_ACTIVITY));
    }
    sketchIntent.putExtra(MarkersUtilities.EXTRA_KEY, image.getAbsolutePath());
    if (gpsLocation != null) {
        sketchIntent.putExtra(LibraryConstants.LATITUDE, gpsLocation[1]);
        sketchIntent.putExtra(LibraryConstants.LONGITUDE, gpsLocation[0]);
        sketchIntent.putExtra(LibraryConstants.ELEVATION, gpsLocation[2]);
    }
    return sketchIntent;
}

From source file:com.svpino.longhorn.MarketCollectorService.java

@Override
protected void onHandleIntent(Intent intent) {
    SharedPreferences sharedPreferences = getSharedPreferences(Constants.PREFERENCES, Context.MODE_PRIVATE);
    long lastUpdate = sharedPreferences.getLong(Constants.PREFERENCE_COLLECTOR_LAST_UPDATE, 0);
    boolean retrying = sharedPreferences.getBoolean(Constants.PREFERENCE_COLLECTOR_RETRYING, false);
    int retries = sharedPreferences.getInt(Constants.PREFERENCE_COLLECTOR_RETRIES, 0);
    boolean wereWeWaitingForConnectivity = sharedPreferences
            .getBoolean(Constants.PREFERENCE_STATUS_WAITING_FOR_CONNECTIVITY, false);

    boolean isGlobalCollection = intent.getExtras() == null
            || (intent.getExtras() != null && !intent.getExtras().containsKey(EXTRA_TICKER));

    if (wereWeWaitingForConnectivity) {
        Editor editor = sharedPreferences.edit();
        editor.putBoolean(Constants.PREFERENCE_STATUS_WAITING_FOR_CONNECTIVITY, false);
        editor.commit();/* w  w  w.ja  v a2s .c  o m*/
    }

    if (retrying && isGlobalCollection) {
        Editor editor = sharedPreferences.edit();
        editor.putBoolean(Constants.PREFERENCE_COLLECTOR_RETRYING, false);
        editor.putInt(Constants.PREFERENCE_COLLECTOR_RETRIES, 0);
        editor.commit();

        ((AlarmManager) getSystemService(Context.ALARM_SERVICE))
                .cancel(Extensions.createPendingIntent(this, Constants.SCHEDULE_RETRY));
    }

    long currentTime = System.currentTimeMillis();
    if (retrying || wereWeWaitingForConnectivity || !isGlobalCollection
            || (isGlobalCollection && currentTime - lastUpdate > Constants.COLLECTOR_MIN_REFRESH_INTERVAL)) {
        String[] tickers = null;

        if (isGlobalCollection) {
            Log.d(LOG_TAG, "Executing global market information collection...");
            tickers = DataProvider.getStockDataTickers(this);
        } else {
            String ticker = intent.getExtras().containsKey(EXTRA_TICKER)
                    ? intent.getExtras().getString(EXTRA_TICKER)
                    : null;

            Log.d(LOG_TAG, "Executing market information collection for ticker " + ticker + ".");

            tickers = new String[] { ticker };
        }

        try {
            collect(tickers);

            if (isGlobalCollection) {
                Editor editor = sharedPreferences.edit();
                editor.putLong(Constants.PREFERENCE_COLLECTOR_LAST_UPDATE, System.currentTimeMillis());
                editor.commit();
            }

            DataProvider.notifyDataCollectionIsFinished(this, tickers);

            Log.d(LOG_TAG, "Market information collection was successfully completed");
        } catch (Exception e) {
            Log.e(LOG_TAG, "Market information collection failed.", e);

            if (Extensions.areWeOnline(this)) {
                Log.d(LOG_TAG, "Scheduling an alarm for retrying a global market information collection...");

                retries++;

                Editor editor = sharedPreferences.edit();
                editor.putBoolean(Constants.PREFERENCE_COLLECTOR_RETRYING, true);
                editor.putInt(Constants.PREFERENCE_COLLECTOR_RETRIES, retries);
                editor.commit();

                long interval = Constants.COLLECTOR_MIN_RETRY_INTERVAL * retries;
                if (interval > Constants.COLLECTOR_MAX_REFRESH_INTERVAL) {
                    interval = Constants.COLLECTOR_MAX_REFRESH_INTERVAL;
                }

                ((AlarmManager) getSystemService(Context.ALARM_SERVICE)).set(AlarmManager.RTC,
                        System.currentTimeMillis() + interval,
                        Extensions.createPendingIntent(this, Constants.SCHEDULE_RETRY));
            } else {
                Log.d(LOG_TAG,
                        "It appears that we are not online, so let's start listening for connectivity updates.");

                Editor editor = sharedPreferences.edit();
                editor.putBoolean(Constants.PREFERENCE_STATUS_WAITING_FOR_CONNECTIVITY, true);
                editor.commit();

                ComponentName componentName = new ComponentName(this, ConnectivityBroadcastReceiver.class);
                getPackageManager().setComponentEnabledSetting(componentName,
                        PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
            }
        }
    } else if (isGlobalCollection && currentTime - lastUpdate <= Constants.COLLECTOR_MIN_REFRESH_INTERVAL) {
        Log.d(LOG_TAG, "Global market information collection will be skipped since it was performed less than "
                + (Constants.COLLECTOR_MIN_REFRESH_INTERVAL / 60 / 1000) + " minutes ago.");
    }

    stopSelf();
}

From source file:co.edu.uniajc.vtf.content.SwipeContentActivity.java

@Override
protected void onResume() {
    ComponentName loComponent = new ComponentName(this, NetworkStatusReceiver.class);
    this.getPackageManager().setComponentEnabledSetting(loComponent,
            PackageManager.COMPONENT_ENABLED_STATE_ENABLED, PackageManager.DONT_KILL_APP);
    super.onResume();
}

From source file:com.heightechllc.breakify.MainActivity.java

@Override
protected void onDestroy() {
    super.onDestroy();

    // Enable or disable the RescheduleReceiver, which restores AlarmManagers when the system
    //  boots or the time changes. We only want it enabled if an alarm is scheduled, or if
    //  Scheduled Start is enabled.
    int enabledState;
    if (timerState == TIMER_STATE_RUNNING || ScheduledStart.isEnabled(this))
        enabledState = PackageManager.COMPONENT_ENABLED_STATE_ENABLED;
    else//from www. j av a  2s .  c  om
        enabledState = PackageManager.COMPONENT_ENABLED_STATE_DISABLED;

    ComponentName receiver = new ComponentName(this, RescheduleReceiver.class);
    getPackageManager().setComponentEnabledSetting(receiver, enabledState, PackageManager.DONT_KILL_APP);

    // Send any unsent analytics events
    if (mixpanel != null)
        mixpanel.flush();
}

From source file:at.tomtasche.reader.ui.activity.MainActivity.java

public void findDocument() {

    final Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
    // remove mime-type because most apps don't support ODF mime-types
    intent.setType("application/*");
    intent.addCategory(Intent.CATEGORY_OPENABLE);

    PackageManager pm = getPackageManager();
    final List<ResolveInfo> targets = pm.queryIntentActivities(intent, 0);
    int size = targets.size();
    String[] targetNames = new String[size];
    for (int i = 0; i < size; i++) {
        targetNames[i] = targets.get(i).loadLabel(pm).toString();
    }//from  w  ww .ja  v  a2  s .  c o m

    AlertDialog.Builder builder = new AlertDialog.Builder(this);
    builder.setTitle(R.string.dialog_choose_filemanager);
    builder.setItems(targetNames, new OnClickListener() {

        @Override
        public void onClick(DialogInterface dialog, int which) {
            ResolveInfo target = targets.get(which);
            if (target == null) {
                return;
            }

            intent.setComponent(new ComponentName(target.activityInfo.packageName, target.activityInfo.name));

            try {
                startActivityForResult(intent, 42);
            } catch (Exception e) {
                e.printStackTrace();

                showCrouton(R.string.crouton_error_open_app, new Runnable() {

                    @Override
                    public void run() {
                        findDocument();
                    }
                }, AppMsg.STYLE_ALERT);
            }

            dialog.dismiss();
        }
    });
    builder.show();
}

From source file:cn.jasonlv.siri.activity.MainActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    // ??? ???//from   w w w  .j  av a2s.c om
    musicManager = new MusicManager(getApplicationContext());

    // ??
    initImageLoader(getApplicationContext());

    /* get the installed package list*/
    // ??
    mPackageManager = new NativePackageManager(getApplicationContext());

    // ?
    setVolumeControlStream(AudioManager.STREAM_MUSIC);

    // ?
    mSynthesizer = new Synthesizer(getApplicationContext());

    //mSynthesizer.speak("EDI");

    //  ?
    mContactManager = new ContactsManager(getApplicationContext());

    mContactManager.getContactList();

    // ??
    detactor = new LocationDetactor(getApplicationContext());
    info = detactor.getLocationInfo();

    Log.d("location info", info.lat + ", " + info.lon);

    //for(Object o : mPackageManager.getPackageList()){
    //    System.out.println(o.toString());

    setContentView(R.layout.sdk2_api);

    //txtLog = (TextView) findViewById(R.id.txtLog);
    btn = (ActionButton) findViewById(R.id.btn);

    // ?
    speechRecognizer = SpeechRecognizer.createSpeechRecognizer(this,
            new ComponentName(this, VoiceRecognitionService.class));

    speechRecognizer.setRecognitionListener(this);

    btn.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(MainActivity.this);
            boolean api = sp.getBoolean("api", false);
            if (api) {
                switch (status) {
                case STATUS_None:
                    start();
                    //btn.setText("?");
                    status = STATUS_WaitingReady;
                    break;
                case STATUS_WaitingReady:
                    cancel();
                    status = STATUS_None;
                    //btn.setText("");
                    break;
                case STATUS_Ready:
                    cancel();
                    status = STATUS_None;
                    //btn.setText("");
                    break;
                case STATUS_Speaking:
                    stop();
                    status = STATUS_Recognition;
                    //btn.setText("");
                    break;
                case STATUS_Recognition:
                    cancel();
                    status = STATUS_None;
                    //btn.setText("");
                    break;
                }
            } else {
                start();
            }
        }
    });

    ActionBar actionBar = getActionBar();
    actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_STANDARD);
    actionBar.setDisplayShowTitleEnabled(true);

    container = (LinearLayout) findViewById(R.id.container);
    scrollView = (ScrollView) findViewById(R.id.scroll);

    scrollView.fullScroll(View.FOCUS_DOWN);
}

From source file:com.example.android.supportv4.media.BrowseFragment.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View rootView = inflater.inflate(R.layout.fragment_list, container, false);

    mBrowserAdapter = new BrowseAdapter(getActivity(), mMediaItems);

    View controls = rootView.findViewById(R.id.controls);
    controls.setVisibility(View.GONE);

    ListView listView = (ListView) rootView.findViewById(R.id.list_view);
    listView.setAdapter(mBrowserAdapter);
    listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override/*w  ww .  j a  va2 s  . c o m*/
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
            MediaBrowserCompat.MediaItem item = mBrowserAdapter.getItem(position);
            try {
                FragmentDataHelper listener = (FragmentDataHelper) getActivity();
                listener.onMediaItemSelected(item);
            } catch (ClassCastException ex) {
                Log.e(TAG, "Exception trying to cast to FragmentDataHelper", ex);
            }
        }
    });

    Bundle args = getArguments();
    mMediaId = args.getString(ARG_MEDIA_ID, null);

    mMediaBrowser = new MediaBrowserCompat(getActivity(),
            new ComponentName(getActivity(), MediaBrowserServiceSupport.class), mConnectionCallback, null);

    listView.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
            if (mCanLoadNewPage && firstVisibleItem + visibleItemCount == totalItemCount) {
                mCanLoadNewPage = false;
                loadPage((mMediaItems.size() + PAGE_SIZE - 1) / PAGE_SIZE);
            }
        }

        @Override
        public void onScrollStateChanged(AbsListView view, int scrollState) {
            // Do nothing
        }
    });

    return rootView;
}

From source file:com.darshancomputing.BatteryIndicatorPro.BatteryInfoService.java

@Override
public void onCreate() {
    res = getResources();//from   w  w w.ja  va2s  .  c  o m
    str = new Str(res);
    log_db = new LogDatabase(this);

    info = new BatteryInfo();

    messenger = new Messenger(new MessageHandler());
    clientMessengers = new java.util.HashSet<Messenger>();

    predictor = new Predictor(this);
    bl = BatteryLevel.getInstance(this, BatteryLevel.SIZE_NOTIFICATION);
    cwbg = new CircleWidgetBackground(this);

    alarms = new AlarmDatabase(this);

    mNotificationManager = NotificationManagerCompat.from(this);
    mainNotificationB = new NotificationCompat.Builder(this);

    alarmManager = (AlarmManager) getSystemService(Context.ALARM_SERVICE);

    loadSettingsFiles();
    sdkVersioning();

    currentHack = CurrentHack.getInstance(this);
    currentHack.setPreferFS(settings.getBoolean(SettingsActivity.KEY_CURRENT_HACK_PREFER_FS,
            res.getBoolean(R.bool.default_prefer_fs_current_hack)));

    Intent currentInfoIntent = new Intent(this, BatteryInfoActivity.class).putExtra(EXTRA_CURRENT_INFO, true);
    currentInfoPendingIntent = PendingIntent.getActivity(this, RC_MAIN, currentInfoIntent, 0);

    Intent updatePredictorIntent = new Intent(this, BatteryInfoService.class);
    updatePredictorIntent.putExtra(EXTRA_UPDATE_PREDICTOR, true);
    updatePredictorPendingIntent = PendingIntent.getService(this, 0, updatePredictorIntent, 0);

    Intent alarmsIntent = new Intent(this, BatteryInfoActivity.class).putExtra(EXTRA_EDIT_ALARMS, true);
    alarmsPendingIntent = PendingIntent.getActivity(this, RC_ALARMS, alarmsIntent, 0);

    widgetManager = AppWidgetManager.getInstance(this);

    Class[] appWidgetProviders = { BatteryInfoAppWidgetProvider.class, /* Circle widget! */
            FullAppWidgetProvider.class };

    for (int i = 0; i < appWidgetProviders.length; i++) {
        int[] ids = widgetManager.getAppWidgetIds(new ComponentName(this, appWidgetProviders[i]));

        for (int j = 0; j < ids.length; j++) {
            widgetIds.add(ids[j]);
        }
    }

    Intent bc_intent = registerReceiver(mBatteryInfoReceiver, batteryChanged);
    info.load(bc_intent, sp_service);
}

From source file:com.actionbarsherlock.internal.view.MenuBuilder.java

@Override
public int addIntentOptions(int groupId, int itemId, int order, ComponentName caller, Intent[] specifics,
        Intent intent, int flags, android.view.MenuItem[] outSpecificItems) {
    PackageManager pm = mContext.getPackageManager();
    final List<ResolveInfo> lri = pm.queryIntentActivityOptions(caller, specifics, intent, 0);
    final int N = lri != null ? lri.size() : 0;

    if ((flags & FLAG_APPEND_TO_GROUP) == 0) {
        removeGroup(groupId);/*from   w  ww .  j  a va 2 s  . co m*/
    }

    for (int i = 0; i < N; i++) {
        final ResolveInfo ri = lri.get(i);
        Intent rintent = new Intent(ri.specificIndex < 0 ? intent : specifics[ri.specificIndex]);
        rintent.setComponent(
                new ComponentName(ri.activityInfo.applicationInfo.packageName, ri.activityInfo.name));
        final MenuItem item = add(groupId, itemId, order, ri.loadLabel(pm)).setIcon(ri.loadIcon(pm))
                .setIntent(rintent);
        if (outSpecificItems != null && ri.specificIndex >= 0) {
            outSpecificItems[ri.specificIndex] = item;
        }
    }

    return N;
}

From source file:am.roadpolice.roadpolice.alarm.AlarmReceiver.java

@Override
public void onReceive(Context context, Intent intent) {

    if (context == null || intent == null) {
        Logger.error("AlarmReceiver", "onReceive(Context " + (context == null ? "null," : ",") + " Intent "
                + (intent == null ? "null)" : ")"));
        return;/*  www  .j a va 2s .  c om*/
    }

    // Set Context
    mContext = context;

    // Get shared preferences.
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context);
    // Check internet availability and only in that case start actions.
    final ConnectivityManager cm = (ConnectivityManager) context.getSystemService(Context.CONNECTIVITY_SERVICE);
    final NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
    final boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

    final String action = intent.getAction();
    // Catch Network change state.
    if (!TextUtils.isEmpty(action) && action.equals("android.net.conn.CONNECTIVITY_CHANGE")) {
        // If internet connection established
        if (isConnected) {
            // If didn't missed last update of data due to network issues do nothing,
            // otherwise proceed with data updating.
            final boolean missUpdateDueToNetworkIssue = sp
                    .getBoolean(MainActivity.MISS_UPDATE_DUE_TO_NETWORK_ISSUE, false);
            if (!missUpdateDueToNetworkIssue)
                return;
        }
        // If user switch off Internet connection do not proceed.
        else
            return;
    }
    // Check Boot state.
    else if (!TextUtils.isEmpty(action) && action.equals("android.intent.action.BOOT_COMPLETED")) {
        // Get stored alarm time.
        final long nextAlarmTime = PreferenceUtils.getDataLong(context,
                PreferenceUtils.KEY_ALERT_TIME_IN_MILLIS, -1);
        if (nextAlarmTime != -1) {
            // Set new alarm, as after reboot alarm was switched off.
            if (mAlarmManager == null)
                mAlarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);

            Intent alarmIntent = new Intent(context, AlarmReceiver.class);
            if (mAlarmIntent == null)
                mAlarmIntent = PendingIntent.getBroadcast(context, 0, alarmIntent, 0);

            // Enable boot receiver
            ComponentName receiver = new ComponentName(context, AlarmReceiver.class);
            PackageManager pm = context.getPackageManager();
            pm.setComponentEnabledSetting(receiver, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                    PackageManager.DONT_KILL_APP);

            final int ui = DialogSettings.getUpdateInterval(context);
            AlarmType type = ui == DialogSettings.DAILY ? AlarmType.DAILY
                    : ui == DialogSettings.WEEKLY ? AlarmType.WEEKLY : AlarmType.MONTHLY;

            mAlarmManager.setInexactRepeating(AlarmManager.RTC_WAKEUP, nextAlarmTime, type.getValue(),
                    mAlarmIntent);
        }
        return;
    }
    // When alarm rise we appears in the block below.
    else {
        Logger.beep();
        Logger.beep();
        Logger.beep();
        // Calculating next alarm time.
        final Calendar calendar = Calendar.getInstance();
        calendar.setTimeInMillis(System.currentTimeMillis());
        final int updateInterval = DialogSettings.getUpdateInterval(context);
        if (updateInterval == DialogSettings.DAILY)
            calendar.add(Calendar.DATE, 1);
        else if (updateInterval == DialogSettings.WEEKLY)
            calendar.add(Calendar.DATE, 7);
        else if (updateInterval == DialogSettings.MONTHLY)
            calendar.add(Calendar.MONTH, 1);
        else
            Logger.error("AlarmReceiver", "Unknown Update Interval.");

        // Next alarm time.
        final long nextAlarmTimeInMillis = calendar.getTimeInMillis();
        // Store next alarm time for further use.
        PreferenceUtils.storeDataLong(context, PreferenceUtils.KEY_ALERT_TIME_IN_MILLIS, nextAlarmTimeInMillis);
    }

    if (!isConnected) {
        Logger.debug("AlarmReceiver", "No Internet connection, while receiving Alarm message");
        // If no internet connecting schedule data update, as soon
        // as internet connection will be available.
        SharedPreferences.Editor ed = sp.edit();
        ed.putBoolean(MainActivity.MISS_UPDATE_DUE_TO_NETWORK_ISSUE, true);
        ed.apply();
        return;
    }

    final String cerNum = sp.getString(MainActivity.CER_NUMBER, MainActivity.EMPTY_STRING);
    final String regNum = sp.getString(MainActivity.REG_NUMBER, MainActivity.EMPTY_STRING);
    final boolean login = sp.getBoolean(MainActivity.AUTO_LOGIN, false);
    if (!login) { // If no auto login user detected.
        Logger.debug("AlarmReceiver", "Why we enter this case if no auto login users detected?");
        // Remove alarm.
        AlarmReceiver.createAlarm(context, AlarmReceiver.AlarmType.NONE);
        return;
    }

    if (TextUtils.isEmpty(cerNum) || TextUtils.isEmpty(regNum)) {
        Logger.debug("AlarmReceiver", "Why we enter this case if both data are null or empty?");
        // Remove alarm.
        AlarmReceiver.createAlarm(context, AlarmReceiver.AlarmType.NONE);
        // Remove auto login.
        SharedPreferences.Editor ed = sp.edit();
        ed.putBoolean(MainActivity.AUTO_LOGIN, false);
        ed.apply();
        return;
    }

    // Start downloading data from internet.
    Submitter submitter = new Submitter(cerNum, regNum, this);
    submitter.executeOnExecutor(Executors.newSingleThreadExecutor());
}