Java Code Examples for android.content.ComponentName

The following are top voted examples for showing how to use android.content.ComponentName. 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 generate more good examples.
Example 1
Project: ProgressManager   File: a.java   Source Code and License 6 votes vote down vote up
/**
 * Dismiss the Keyboard Shortcuts screen.
 */
public final void dismissKeyboardShortcutsHelper() {
    Intent intent = new Intent(Intent.ACTION_DISMISS_KEYBOARD_SHORTCUTS);
    intent.setComponent(new ComponentName(KEYBOARD_SHORTCUTS_RECEIVER_PKG_NAME,
            KEYBOARD_SHORTCUTS_RECEIVER_CLASS_NAME));
    sendBroadcast(intent);
}
 
Example 2
Project: AppChooser   File: ResolversFragment.java   Source Code and License 6 votes vote down vote up
@Override
public void showFileContent(ActivityInfo activityInfo, File file,
                            int requestCode) throws AppChooserException {
    Intent intent = new Intent(Intent.ACTION_VIEW);
    intent.setComponent(new ComponentName(activityInfo.getPkg(), activityInfo.getCls()));
    intent.setDataAndType(Uri.fromFile(file), activityInfo.getMimeType());
    ComponentName componentName = intent.resolveActivity(getActivity().getPackageManager());
    if (componentName != null) {
        try {
            if (requestCode == ResolversConsts.DEFAULT_REQUEST_CODE) {
                getActivity().startActivity(intent);
            } else {
                getActivity().startActivityForResult(intent, requestCode);
            }
        } catch (ActivityNotFoundException e) {
            throw new AppChooserException(e);
        }
    } else {
        throw new AppChooserException();
    }
}
 
Example 3
Project: DizzyPassword   File: MyApplication.java   Source Code and License 6 votes vote down vote up
/**
 * 根据包名打开第三方应用
 *
 * @param context
 * @param packageName
 * @throws PackageManager.NameNotFoundException
 */
public static void openAppByPackageName(Context context, String packageName) throws PackageManager.NameNotFoundException {
    PackageInfo pi;
    try {
        pi = MyApplication.getContext().getPackageManager().getPackageInfo(packageName, 0);
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.setPackage(pi.packageName);
        PackageManager pManager = MyApplication.getContext().getPackageManager();
        List<ResolveInfo> apps = pManager.queryIntentActivities(resolveIntent, 0);
        ResolveInfo ri = apps.iterator().next();
        if (ri != null) {
            packageName = ri.activityInfo.packageName;
            String className = ri.activityInfo.name;
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);//重点是加这个
            ComponentName cn = new ComponentName(packageName, className);
            intent.setComponent(cn);
            context.startActivity(intent);
        }
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
}
 
Example 4
Project: LaunchEnr   File: LauncherAppWidgetInfo.java   Source Code and License 6 votes vote down vote up
public LauncherAppWidgetInfo(int appWidgetId, ComponentName providerName) {
    if (appWidgetId == CUSTOM_WIDGET_ID) {
        itemType = LauncherSettings.Favorites.ITEM_TYPE_CUSTOM_APPWIDGET;
    } else {
        itemType = LauncherSettings.Favorites.ITEM_TYPE_APPWIDGET;
    }

    this.appWidgetId = appWidgetId;
    this.providerName = providerName;

    // Since the widget isn't instantiated yet, we don't know these values. Set them to -1
    // to indicate that they should be calculated based on the layout and minWidth/minHeight
    spanX = -1;
    spanY = -1;
    // We only support app widgets on current user.
    user = Process.myUserHandle();
    restoreStatus = RESTORE_COMPLETED;
}
 
Example 5
Project: ProgressManager   File: a.java   Source Code and License 6 votes vote down vote up
/**
 * Request the Keyboard Shortcuts screen to show up. This will trigger
 * {@link #onProvideKeyboardShortcuts} to retrieve the shortcuts for the foreground activity.
 */
public final void requestShowKeyboardShortcuts() {
    Intent intent = new Intent(Intent.ACTION_SHOW_KEYBOARD_SHORTCUTS);
    intent.setComponent(new ComponentName(KEYBOARD_SHORTCUTS_RECEIVER_PKG_NAME,
            KEYBOARD_SHORTCUTS_RECEIVER_CLASS_NAME));
    sendBroadcast(intent);
}
 
Example 6
Project: FirebasePost   File: NotifactionUtil.java   Source Code and License 6 votes vote down vote up
/**
 * Method checks if the app is in background or not
 */
public static boolean isAppIsInBackground(Context context) {
    boolean isInBackground = true;
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
        List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                for (String activeProcess : processInfo.pkgList) {
                    if (activeProcess.equals(context.getPackageName())) {
                        isInBackground = false;
                    }
                }
            }
        }
    } else {
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;
        if (componentInfo.getPackageName().equals(context.getPackageName())) {
            isInBackground = false;
        }
    }

    return isInBackground;
}
 
Example 7
Project: easyfilemanager   File: DocumentsActivity.java   Source Code and License 5 votes vote down vote up
public void onAppPicked(ResolveInfo info) {
    final Intent intent = new Intent(getIntent());
    intent.setFlags(intent.getFlags() & ~Intent.FLAG_ACTIVITY_FORWARD_RESULT);
    intent.setComponent(new ComponentName(
            info.activityInfo.applicationInfo.packageName, info.activityInfo.name));
    startActivityForResult(intent, CODE_FORWARD);
}
 
Example 8
Project: ScreenOffTime   File: MainActivity.java   Source Code and License 5 votes vote down vote up
private void disableComponent() {
        PackageManager packageManager = getPackageManager();
        ComponentName componentName = new ComponentName(this, MainActivity.class);
//        packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
//                PackageManager.DONT_KILL_APP);
        int res = packageManager.getComponentEnabledSetting(componentName);
        if (res == PackageManager.COMPONENT_ENABLED_STATE_DEFAULT
                || res == PackageManager.COMPONENT_ENABLED_STATE_ENABLED) {
            // 隐藏应用图标
            packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                    PackageManager.DONT_KILL_APP);
        } else {
            // 显示应用图标
            packageManager.setComponentEnabledSetting(componentName, PackageManager.COMPONENT_ENABLED_STATE_DEFAULT,
                    PackageManager.DONT_KILL_APP);
        }
    }
 
Example 9
Project: PDialogs-Android   File: InternetWarning.java   Source Code and License 5 votes vote down vote up
@Override
public void onClick(View view) {
    int i = view.getId();
    if (i == R.id.gprsACBtn) {
        context.startActivity(new Intent(Settings.ACTION_DATA_ROAMING_SETTINGS)
                .addCategory(Intent.ACTION_MAIN)
                .setComponent(new ComponentName("com.android.settings"
                        , "com.android.settings.Settings$DataUsageSummaryActivity"))
                .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
        dismiss();
    } else if (i == R.id.wifiACBtn) {
        context.startActivity(new Intent(Settings.ACTION_WIFI_SETTINGS));
        dismiss();
    }
}
 
Example 10
Project: lineagex86   File: NotificationStation.java   Source Code and License 5 votes vote down vote up
@Override
public void onAttach(Activity activity) {
    logd("onAttach(%s)", activity.getClass().getSimpleName());
    super.onAttach(activity);
    mContext = activity;
    mPm = mContext.getPackageManager();
    mNoMan = INotificationManager.Stub.asInterface(
            ServiceManager.getService(Context.NOTIFICATION_SERVICE));
    try {
        mListener.registerAsSystemService(mContext, new ComponentName(mContext.getPackageName(),
                this.getClass().getCanonicalName()), ActivityManager.getCurrentUser());
    } catch (RemoteException e) {
        Log.e(TAG, "Cannot register listener", e);
    }
}
 
Example 11
Project: C500Companion   File: C500Service.java   Source Code and License 5 votes vote down vote up
public void openApplication(Context context, String packageName) {
    PackageInfo pi;
    try {
        pi = context.getPackageManager().getPackageInfo(packageName, 0);
    } catch (PackageManager.NameNotFoundException e) {
        pi = null;
        e.printStackTrace();
    }
    if (pi != null) {
        Intent resolveIntent = new Intent("android.intent.action.MAIN", null);
        resolveIntent.setPackage(pi.packageName);
        ResolveInfo ri = (ResolveInfo) context.getPackageManager().queryIntentActivities(resolveIntent, 0).iterator().next();
        if (ri != null) {
            packageName = ri.activityInfo.packageName;
            String className = ri.activityInfo.name;
            Intent intent = new Intent("android.intent.action.MAIN");
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.setComponent(new ComponentName(packageName, className));
            context.startActivity(intent);
        }
    }
}
 
Example 12
Project: item-reaper   File: ItemWidgetProvider.java   Source Code and License 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);
    if (intent.getAction().equals(ACTION_DATA_UPDATED)) {
        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
        int[] appWidgetIds = appWidgetManager.getAppWidgetIds(
                new ComponentName(context, getClass()));
        appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.widget_list);
    }
}
 
Example 13
Project: TPlayer   File: VJobSchedulerService.java   Source Code and License 5 votes vote down vote up
@Override
public List<JobInfo> getAllPendingJobs() throws RemoteException {
    int vuid = VBinder.getCallingUid();
    List<JobInfo> jobs = mScheduler.getAllPendingJobs();
    synchronized (mJobStore) {
        Iterator<JobInfo> iterator = jobs.listIterator();
        while (iterator.hasNext()) {
            JobInfo job = iterator.next();
            if (!VASettings.STUB_JOB.equals(job.getService().getClassName())) {
                // Schedule by Host, invisible in VA.
                iterator.remove();
                continue;
            }
            Map.Entry<JobId, JobConfig> jobEntry = findJobByVirtualJobId(job.getId());
            if (jobEntry == null) {
                iterator.remove();
                continue;
            }
            JobId jobId = jobEntry.getKey();
            JobConfig config = jobEntry.getValue();
            if (jobId.vuid != vuid) {
                iterator.remove();
                continue;
            }
            mirror.android.app.job.JobInfo.jobId.set(job, jobId.clientJobId);
            mirror.android.app.job.JobInfo.service.set(job, new ComponentName(jobId.packageName, config.serviceName));
        }
    }
    return jobs;
}
 
Example 14
Project: container   File: VActivityManagerService.java   Source Code and License 5 votes vote down vote up
private void performScheduleReceiver(IVClient client, int vuid, ActivityInfo info, Intent intent,
                                     PendingResultData result) {

    ComponentName componentName = ComponentUtils.toComponentName(info);
    BroadcastSystem.get().broadcastSent(vuid, info, result);
    try {
        client.scheduleReceiver(componentName, intent, result);
    } catch (Throwable e) {
        if (result != null) {
            result.finish();
        }
    }
}
 
Example 15
Project: PingWidget   File: PingWidgetUpdateService.java   Source Code and License 5 votes vote down vote up
@Override
public void onConfigurationChanged(Configuration newConfig) {
    Log.d(TAG, "onConfigurationChanged() " + newConfig.toString());

    //Called when screen is rotated, phone charging state changes
    //The widget gets reset, so we need to reconfigure some things

    //Get AppWidgetManager
    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(getApplicationContext());

    // Get all widget ids
    int[] allWidgetIds = appWidgetManager.getAppWidgetIds(new ComponentName(getApplication(), PingWidgetProvider.class));

    for (int widgetId : allWidgetIds) {

        //Get widget data
        PingWidgetData data = SharedPreferencesHelper.readPingWidgetData(getApplicationContext(), widgetId);
        if(data != null) {

            //Get RemoteViews
            RemoteViews views = RemoteViewsUtil.getRemoteViews(getApplicationContext(), data.getWidgetLayoutType());

            //Update widget views
            RemoteViewsUtil.initWidgetViews(getApplicationContext(), views, data);

            //Register an Intent so that onClicks on the widget are received by PingWidgetProvider.onReceive()
            //Create an Intent, set PING_WIDGET_TOGGLE action to it, put EXTRA_APPWIDGET_ID as extra
            Util.registerWidgetStartPauseOnClickListener(getApplication(), widgetId, views);
            Util.registerWidgetReconfigureClickListener(getApplication(), widgetId, views);

            //Update the widget
            appWidgetManager.updateAppWidget(widgetId, views);
        }

    }
    super.onConfigurationChanged(newConfig);
}
 
Example 16
Project: IFWManager   File: StringFilter.java   Source Code and License 5 votes vote down vote up
@Override
public String getValue(ComponentName resolvedComponent, Intent intent,
                       String resolvedType) {
    Uri data = intent.getData();
    if (data != null) {
        return data.getScheme();
    }
    return null;
}
 
Example 17
Project: Android-AudioRecorder-App   File: RecordFragment.java   Source Code and License 5 votes vote down vote up
@Override public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
  mIsServiceBound = true;
  mAudioRecordService =
      ((AudioRecordService.ServiceBinder) iBinder).getService();
  Log.i("Tesing", " " + mAudioRecordService.isRecording() + " recording");
  audioRecordPresenter.onServiceStatusAvailable(mAudioRecordService.isRecording(),
      mAudioRecordService.isPaused());
}
 
Example 18
Project: popomusic   File: MainActivty.java   Source Code and License 5 votes vote down vote up
@Override
public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
    mServiceMessenger = new Messenger(iBinder);
    //连接到服务
    if (null != mServiceMessenger) {
        Message msgToService = Message.obtain();
        msgToService.replyTo = mMessengerClient;
        msgToService.what = Constant.MAIN_ACTIVITY;
        try {
            mServiceMessenger.send(msgToService);
        } catch (RemoteException e) {
            e.printStackTrace();
        }
    }
}
 
Example 19
Project: Espresso   File: AppWidgetProvider.java   Source Code and License 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);
    String action = intent.getAction();
    if (REFRESH_ACTION.equals(action)) {
        AppWidgetManager manager = AppWidgetManager.getInstance(context);
        ComponentName name = new ComponentName(context, AppWidgetProvider.class);
        manager.notifyAppWidgetViewDataChanged(manager.getAppWidgetIds(name), R.id.listViewWidget);
    }
}
 
Example 20
Project: CryptoVoice   File: GcmIntentService.java   Source Code and License 5 votes vote down vote up
private boolean isAppIsInBackground(Context context) {
    boolean isInBackground = true;
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT_WATCH) {
        List<ActivityManager.RunningAppProcessInfo> runningProcesses = am.getRunningAppProcesses();
        for (ActivityManager.RunningAppProcessInfo processInfo : runningProcesses) {
            if (processInfo.importance == ActivityManager.RunningAppProcessInfo.IMPORTANCE_FOREGROUND) {
                for (String activeProcess : processInfo.pkgList) {
                    if (activeProcess.equals(context.getPackageName())) {
                        isInBackground = false;
                    }
                }
            }
        }
    } else {
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        ComponentName componentInfo = taskInfo.get(0).topActivity;
        if (componentInfo.getPackageName().equals(context.getPackageName())) {
            isInBackground = false;
        }
    }

    return isInBackground;
}
 
Example 21
Project: buildAPKsSamples   File: Home.java   Source Code and License 5 votes vote down vote up
/**
 * Loads the list of installed applications in mApplications.
 */
private void loadApplications(boolean isLaunching) {
    if (isLaunching && mApplications != null) {
        return;
    }

    PackageManager manager = getPackageManager();

    Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
    mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

    final List<ResolveInfo> apps = manager.queryIntentActivities(mainIntent, 0);
    Collections.sort(apps, new ResolveInfo.DisplayNameComparator(manager));

    if (apps != null) {
        final int count = apps.size();

        if (mApplications == null) {
            mApplications = new ArrayList<ApplicationInfo>(count);
        }
        mApplications.clear();

        for (int i = 0; i < count; i++) {
            ApplicationInfo application = new ApplicationInfo();
            ResolveInfo info = apps.get(i);

            application.title = info.loadLabel(manager);
            application.setActivity(new ComponentName(
                    info.activityInfo.applicationInfo.packageName,
                    info.activityInfo.name),
                    Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
            application.icon = info.activityInfo.loadIcon(manager);

            mApplications.add(application);
        }
    }
}
 
Example 22
Project: VirtualHook   File: VActivityManagerService.java   Source Code and License 5 votes vote down vote up
@Override
public void onActivityCreated(ComponentName component, ComponentName caller, IBinder token, Intent intent, String affinity, int taskId, int launchMode, int flags) {
    int pid = Binder.getCallingPid();
    ProcessRecord targetApp = findProcessLocked(pid);
    if (targetApp != null) {
        mMainStack.onActivityCreated(targetApp, component, caller, token, intent, affinity, taskId, launchMode, flags);
    }
}
 
Example 23
Project: AndroidBasicLibs   File: PackageUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 启动应用
 */
public static boolean startAppByPackageName(Context context, String packageName, Map<String, String> param) {
    PackageInfo pi = null;
    try {
        pi = context.getPackageManager().getPackageInfo(packageName, 0);
        Intent resolveIntent = new Intent(Intent.ACTION_MAIN, null);
        resolveIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.DONUT) {
            resolveIntent.setPackage(pi.packageName);
        }

        List<ResolveInfo> apps = context.getPackageManager().queryIntentActivities(resolveIntent, 0);

        ResolveInfo ri = apps.iterator().next();
        if (ri != null) {
            String packageName1 = ri.activityInfo.packageName;
            String className = ri.activityInfo.name;

            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            intent.addCategory(Intent.CATEGORY_LAUNCHER);

            ComponentName cn = new ComponentName(packageName1, className);

            intent.setComponent(cn);
            if (param != null) {
                for (Map.Entry<String, String> en : param.entrySet()) {
                    intent.putExtra(en.getKey(), en.getValue());
                }
            }
            context.startActivity(intent);
            return true;
        }
    } catch (Exception e) {
        e.printStackTrace();
        ViseLog.e("启动失败");
    }
    return false;
}
 
Example 24
Project: TrainAppTFG   File: ListarYConectarBluetooth.java   Source Code and License 5 votes vote down vote up
@Override
public void onServiceConnected(ComponentName name, IBinder service) {
    BluetoothLeService.LocalBinder binder = (BluetoothLeService.LocalBinder) service;
    mService = binder.getService();
    Log.d("BIND", "mBound(true)");
    mBound = true;
}
 
Example 25
Project: ProgressManager   File: a.java   Source Code and License 5 votes vote down vote up
/**
 * Obtain an {@link Intent} that will launch an explicit target activity specified by
 * this activity's logical parent. The logical parent is named in the application's manifest
 * by the {@link android.R.attr#parentActivityName parentActivityName} attribute.
 * Activity subclasses may override this method to modify the Intent returned by
 * super.getParentActivityIntent() or to implement a different mechanism of retrieving
 * the parent intent entirely.
 *
 * @return a new Intent targeting the defined parent of this activity or null if
 *         there is no valid parent.
 */
@Nullable
public Intent getParentActivityIntent() {
    final String parentName = mActivityInfo.parentActivityName;
    if (TextUtils.isEmpty(parentName)) {
        return null;
    }

    // If the parent itself has no parent, generate a main activity intent.
    final ComponentName target = new ComponentName(this, parentName);
    try {
        final ActivityInfo parentInfo = getPackageManager().getActivityInfo(target, 0);
        final String parentActivity = parentInfo.parentActivityName;
        final Intent parentIntent = parentActivity == null
                ? Intent.makeMainActivity(target)
                : new Intent().setComponent(target);
        return parentIntent;
    } catch (NameNotFoundException e) {
        Log.e(TAG, "getParentActivityIntent: bad parentActivityName '" + parentName +
                "' in manifest");
        return null;
    }
}
 
Example 26
Project: Android_AutoSignInTool   File: Utils.java   Source Code and License 5 votes vote down vote up
public static String getTopApp(Context context) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) { // 5.0及之后的方法
        UsageStatsManager usm = (UsageStatsManager) context.getSystemService(Context.USAGE_STATS_SERVICE);
        if (usm != null) {
            long now = System.currentTimeMillis();
            // 获取40秒之内的应用程序使用状态
            List<UsageStats> stats = usm.queryUsageStats(UsageStatsManager.INTERVAL_BEST, now - 40 * 1000, now);
            String topActivity = "";
            // 获取最新运行的程序
            if ((stats != null) && (!stats.isEmpty())) {
                int j = 0;
                for (int i = 0; i < stats.size(); i++) {
                    if (stats.get(i).getLastTimeUsed() > stats.get(j).getLastTimeUsed()) {
                        j = i;
                    }
                }
                topActivity = stats.get(j).getPackageName();
                return topActivity;
            }
        }
    } else if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP){ // 5.0之前的方法
        ActivityManager activityManager = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
        ComponentName cn = activityManager.getRunningTasks(1).get(0).topActivity;
        return cn.getPackageName();
    }
    return "Not found!";
}
 
Example 27
Project: FileDownloader-master   File: NotificationSampleActivity.java   Source Code and License 5 votes vote down vote up
private NotificationItem(int id, String title, String desc) {
    super(id, title, desc);
    Intent[] intents = new Intent[2];
    intents[0] = Intent.makeMainActivity(new ComponentName(DemoApplication.CONTEXT,
            MainActivity.class));
    intents[1] = new Intent(DemoApplication.CONTEXT, NotificationSampleActivity.class);

    this.pendingIntent = PendingIntent.getActivities(DemoApplication.CONTEXT, 0, intents,
            PendingIntent.FLAG_UPDATE_CURRENT);

    builder = new NotificationCompat.
            Builder(FileDownloadHelper.getAppContext());

    builder.setDefaults(Notification.DEFAULT_LIGHTS)
            .setOngoing(true)
            .setPriority(NotificationCompat.PRIORITY_MIN)
            .setContentTitle(getTitle())
            .setContentText(desc)
            .setContentIntent(pendingIntent)
            .setSmallIcon(R.mipmap.ic_launcher);

}
 
Example 28
Project: ProgressManager   File: a.java   Source Code and License 5 votes vote down vote up
/**
 * Obtain an {@link Intent} that will launch an explicit target activity specified by
 * this activity's logical parent. The logical parent is named in the application's manifest
 * by the {@link android.R.attr#parentActivityName parentActivityName} attribute.
 * Activity subclasses may override this method to modify the Intent returned by
 * super.getParentActivityIntent() or to implement a different mechanism of retrieving
 * the parent intent entirely.
 *
 * @return a new Intent targeting the defined parent of this activity or null if
 *         there is no valid parent.
 */
@Nullable
public Intent getParentActivityIntent() {
    final String parentName = mActivityInfo.parentActivityName;
    if (TextUtils.isEmpty(parentName)) {
        return null;
    }

    // If the parent itself has no parent, generate a main activity intent.
    final ComponentName target = new ComponentName(this, parentName);
    try {
        final ActivityInfo parentInfo = getPackageManager().getActivityInfo(target, 0);
        final String parentActivity = parentInfo.parentActivityName;
        final Intent parentIntent = parentActivity == null
                ? Intent.makeMainActivity(target)
                : new Intent().setComponent(target);
        return parentIntent;
    } catch (NameNotFoundException e) {
        Log.e(TAG, "getParentActivityIntent: bad parentActivityName '" + parentName +
                "' in manifest");
        return null;
    }
}
 
Example 29
Project: VirtualHook   File: VJobSchedulerService.java   Source Code and License 5 votes vote down vote up
@Override
public List<JobInfo> getAllPendingJobs() throws RemoteException {
    int vuid = VBinder.getCallingUid();
    List<JobInfo> jobs = mScheduler.getAllPendingJobs();
    synchronized (mJobStore) {
        Iterator<JobInfo> iterator = jobs.listIterator();
        while (iterator.hasNext()) {
            JobInfo job = iterator.next();
            if (!StubManifest.STUB_JOB.equals(job.getService().getClassName())) {
                // Schedule by Host, invisible in VA.
                iterator.remove();
                continue;
            }
            Map.Entry<JobId, JobConfig> jobEntry = findJobByVirtualJobId(job.getId());
            if (jobEntry == null) {
                iterator.remove();
                continue;
            }
            JobId jobId = jobEntry.getKey();
            JobConfig config = jobEntry.getValue();
            if (jobId.vuid != vuid) {
                iterator.remove();
                continue;
            }
            mirror.android.app.job.JobInfo.jobId.set(job, jobId.clientJobId);
            mirror.android.app.job.JobInfo.service.set(job, new ComponentName(jobId.packageName, config.serviceName));
        }
    }
    return jobs;
}
 
Example 30
Project: StopApp   File: SettingActivity.java   Source Code and License 5 votes vote down vote up
/**
     * 切换桌面图标
     *
     * @param componentDisabledName
     * @param componentEnabledName
     */
    private void setComponentEnabled(ComponentName componentDisabledName
            , ComponentName componentEnabledName) {
        PackageManager pm = getPackageManager();
        pm.setComponentEnabledSetting(componentDisabledName, PackageManager.COMPONENT_ENABLED_STATE_DISABLED,
                PackageManager.DONT_KILL_APP);
        pm.setComponentEnabledSetting(componentEnabledName, PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
                PackageManager.DONT_KILL_APP);
        snackBarShow(mCoordinatorLayout, getString(R.string.launcher_icon_had_change));
        // Find launcher and kill it (restart launcher)
        // MIUI8 Android6.0.6:android.content.pm.PackageManager$NameNotFoundException
//        ActivityManager am = (ActivityManager) getSystemService(Activity.ACTIVITY_SERVICE);
//        Intent i = new Intent(Intent.ACTION_MAIN);
//        i.addCategory(Intent.CATEGORY_HOME);
//        i.addCategory(Intent.CATEGORY_DEFAULT);
//        List<ResolveInfo> resolves = pm.queryIntentActivities(i, 0);
//        for (ResolveInfo res : resolves) {
//            if (res.activityInfo != null) {
//                am.killBackgroundProcesses(res.activityInfo.packageName);
//            }
//        }
    }
 
Example 31
Project: ThunderMusic   File: MediaAppWidgetProvider2x1_Light.java   Source Code and License 5 votes vote down vote up
/**
 * Check against {@link AppWidgetManager} if there are any instances of this
 * widget.
 */
private boolean hasInstances(Context context) {
    AppWidgetManager appWidgetManager = AppWidgetManager
            .getInstance(context);
    int[] appWidgetIds = appWidgetManager
            .getAppWidgetIds(new ComponentName(context, this.getClass()));
    return (appWidgetIds.length > 0);
}
 
Example 32
Project: Hello-Music-droid   File: MusicService.java   Source Code and License 5 votes vote down vote up
private final PendingIntent retrievePlaybackAction(final String action) {
    final ComponentName serviceName = new ComponentName(this, MusicService.class);
    Intent intent = new Intent(action);
    intent.setComponent(serviceName);

    return PendingIntent.getService(this, 0, intent, 0);
}
 
Example 33
Project: chromium-for-android-56-debug-video   File: MediaNotificationManager.java   Source Code and License 5 votes vote down vote up
private MediaSessionCompat createMediaSession() {
    MediaSessionCompat mediaSession = new MediaSessionCompat(
            mContext,
            mContext.getString(R.string.app_name),
            new ComponentName(mContext.getPackageName(),
                    getButtonReceiverClassName()),
            null);
    mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS
            | MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
    mediaSession.setCallback(mMediaSessionCallback);

    // TODO(mlamouri): the following code is to work around a bug that hopefully
    // MediaSessionCompat will handle directly. see b/24051980.
    try {
        mediaSession.setActive(true);
    } catch (NullPointerException e) {
        // Some versions of KitKat do not support AudioManager.registerMediaButtonIntent
        // with a PendingIntent. They will throw a NullPointerException, in which case
        // they should be able to activate a MediaSessionCompat with only transport
        // controls.
        mediaSession.setActive(false);
        mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_TRANSPORT_CONTROLS);
        mediaSession.setActive(true);
    }
    return mediaSession;
}
 
Example 34
Project: LaunchEnr   File: LoaderCursor.java   Source Code and License 5 votes vote down vote up
/**
 * Make an ShortcutInfo object for a shortcut that is an application.
 */
public ShortcutInfo getAppShortcutInfo(
        Intent intent, boolean allowMissingTarget, boolean useLowResIcon) {
    if (user == null) {
        return null;
    }

    ComponentName componentName = intent.getComponent();
    if (componentName == null) {
        return null;
    }

    Intent newIntent = new Intent(Intent.ACTION_MAIN, null);
    newIntent.addCategory(Intent.CATEGORY_LAUNCHER);
    newIntent.setComponent(componentName);
    LauncherActivityInfo lai = LauncherAppsCompat.getInstance(mContext)
            .resolveActivity(newIntent, user);
    if ((lai == null) && !allowMissingTarget) {
        return null;
    }

    final ShortcutInfo info = new ShortcutInfo();
    info.itemType = LauncherSettings.Favorites.ITEM_TYPE_APPLICATION;
    info.user = user;
    info.intent = newIntent;

    mIconCache.getTitleAndIcon(info, lai, useLowResIcon);
    if (mIconCache.isDefaultIcon(info.iconBitmap, user)) {
        Bitmap icon = loadIcon(info);
        info.iconBitmap = icon != null ? icon : info.iconBitmap;
    }

    if (lai != null && PackageManagerHelper.isAppSuspended(lai.getApplicationInfo())) {
        info.isDisabled = ShortcutInfo.FLAG_DISABLED_SUSPENDED;
    }

    // from the db
    if (TextUtils.isEmpty(info.title)) {
        info.title = getTitle();
    }

    // fall back to the class name of the activity
    if (info.title == null) {
        info.title = componentName.getClassName();
    }

    info.contentDescription = mUserManager.getBadgedLabelForUser(info.title, info.user);
    return info;
}
 
Example 35
Project: Utils   File: AppUtil.java   Source Code and License 5 votes vote down vote up
/**
 * 判断当前App处于前台还是后台
 * <p>需添加权限 {@code <uses-permission android:name="android.permission.GET_TASKS"/>}</p>
 * <p>并且必须是系统应用该方法才有效</p>
 *
 * @param context 上下文
 * @return {@code true}: 后台<br>{@code false}: 前台
 */
public static boolean isAppBackground(Context context) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    @SuppressWarnings("deprecation")
    List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
    if (!tasks.isEmpty()) {
        ComponentName topActivity = tasks.get(0).topActivity;
        if (!topActivity.getPackageName().equals(context.getPackageName())) {
            return true;
        }
    }
    return false;
}
 
Example 36
Project: ReplyMessage   File: JumpPermissionManagement.java   Source Code and License 5 votes vote down vote up
public static void LG(Activity activity) {
    Intent intent = new Intent("android.intent.action.MAIN");
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra("packageName", BuildConfig.APPLICATION_ID);
    ComponentName comp = new ComponentName("com.android.settings", "com.android.settings.Settings$AccessLockSummaryActivity");
    intent.setComponent(comp);
    activity.startActivity(intent);
}
 
Example 37
Project: atlas   File: BaseDelegateService.java   Source Code and License 5 votes vote down vote up
private AdditionalServiceRecord retriveServiceByComponent(ComponentName component){
    Iterator iter = mActivateServices.entrySet().iterator();
    while (iter.hasNext()) {
        Map.Entry<AdditionalServiceRecord,Service> entry = (Map.Entry<AdditionalServiceRecord,Service>) iter.next();
        AdditionalServiceRecord tmpRecord = entry.getKey();
        if(tmpRecord.component.equals(component)){
            //service has created
            return tmpRecord;
        }
    }
    return null;
}
 
Example 38
Project: MuslimMateAndroid   File: PrayerWidget.java   Source Code and License 5 votes vote down vote up
/**
 * Receive broadcast for refresh
 *
 * @param context Application context
 * @param intent  Intent to do something
 */
@Override
public void onReceive(Context context, Intent intent) {

    String action = intent.getAction();
    if (action.equals(PRAYER_CHANGE) || action.equals(Intent.ACTION_DATE_CHANGED)) {
        AppWidgetManager gm = AppWidgetManager.getInstance(context);
        int[] ids = gm.getAppWidgetIds(new ComponentName(context, PrayerWidget.class));
        this.onUpdate(context, gm, ids);
    } else {
        super.onReceive(context, intent);
    }
}
 
Example 39
Project: GitHub   File: NetUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 打开网络设置界面
 */
public static void openSetting(Activity activity, int requestCode) {
    Intent intent = new Intent("/");
    ComponentName cm = new ComponentName("com.android.settings",
            "com.android.settings.WirelessSettings");
    intent.setComponent(cm);
    intent.setAction(Intent.ACTION_VIEW);
    activity.startActivityForResult(intent, requestCode);
}
 
Example 40
Project: serviceconnector   File: ActivityWithoutServiceConnector.java   Source Code and License 5 votes vote down vote up
@Override
public void onServiceConnected(ComponentName componentName, IBinder service) {
    mEchoService = IEchoService.Stub.asInterface(service);
    try {
        echoMessage("Test");
    } catch (RemoteException exception) {
    }
}
 
Example 41
Project: cardinalsSample   File: PackageUtils.java   Source Code and License 5 votes vote down vote up
/**
 * 判断当前应用是否在前端运行
 *
 * @param context Contex对象
 * @return 当前应用是否在前端运行
 */
public static boolean isAppOnForeground(Context context) {
    ActivityManager am = (ActivityManager) context.getSystemService(Context.ACTIVITY_SERVICE);
    List<ActivityManager.RunningTaskInfo> tasks = am.getRunningTasks(1);
    if (!tasks.isEmpty()) {
        ComponentName topActivity = tasks.get(0).topActivity;
        if (topActivity.getPackageName().equals(context.getPackageName())) {
            return true;
        }
    }
    return false;
}
 
Example 42
Project: CSipSimple   File: SipHome.java   Source Code and License 5 votes vote down vote up
private void startSipService() {
    Thread t = new Thread("StartSip") {
        public void run() {
            Intent serviceIntent = new Intent(SipManager.INTENT_SIP_SERVICE);
            // Optional, but here we bundle so just ensure we are using csipsimple package
            serviceIntent.setPackage(SipHome.this.getPackageName());
            serviceIntent.putExtra(SipManager.EXTRA_OUTGOING_ACTIVITY, new ComponentName(SipHome.this, SipHome.class));
            startService(serviceIntent);
            postStartSipService();
        };
    };
    t.start();

}
 
Example 43
Project: chromium-for-android-56-debug-video   File: DownloadActivity.java   Source Code and License 5 votes vote down vote up
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    boolean isOffTheRecord = DownloadUtils.shouldShowOffTheRecordDownloads(getIntent());
    ComponentName parentComponent = IntentUtils.safeGetParcelableExtra(
            getIntent(), IntentHandler.EXTRA_PARENT_COMPONENT);
    mDownloadManagerUi = new DownloadManagerUi(this, isOffTheRecord, parentComponent);
    setContentView(mDownloadManagerUi.getView());
    mIsOffTheRecord = isOffTheRecord;
    mDownloadManagerUi.addObserver(mUiObserver);
    // Call updateForUrl() to align with how DownloadPage interacts with DownloadManagerUi.
    mDownloadManagerUi.updateForUrl(UrlConstants.DOWNLOADS_URL);
}
 
Example 44
Project: ThunderMusic   File: MusicUtils.java   Source Code and License 5 votes vote down vote up
public void onServiceConnected(ComponentName className,
                               android.os.IBinder service) {
    sService = IMediaPlaybackService.Stub.asInterface(service);
    if (mCallback != null) {
        mCallback.onServiceConnected(className, service);
    }
}
 
Example 45
Project: Phoenix-for-VK   File: MusicUtils.java   Source Code and License 5 votes vote down vote up
@Override
public void onServiceDisconnected(final ComponentName className) {
    if (mCallback != null) {
        mCallback.onServiceDisconnected(className);
    }

    mService = null;

    SERVICE_BIND_PUBLISHER.onNext(Optional.empty());
}
 
Example 46
Project: GoSCELE   File: ScheduleDailyWidget.java   Source Code and License 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);

    boolean isDataChange = Constant.WIDGET_ACTION_DATA_CHANGE.equals(intent.getAction()) && intent.getBooleanExtra("isEmptyList", false);
    if (IS_NOT_READY_YET != isDataChange) {
        IS_NOT_READY_YET = isDataChange;

        AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);
        ComponentName thisAppWidget = new ComponentName(context.getPackageName(), ScheduleDailyWidget.class.getName());
        onUpdate(context, appWidgetManager, appWidgetManager.getAppWidgetIds(thisAppWidget));
    }
}
 
Example 47
Project: IPCCommunication   File: ClientMsgUtils.java   Source Code and License 5 votes vote down vote up
@Override
public void onServiceDisconnected(ComponentName name) {
    // TODO Auto-generated method stub
    Log.d(TAG, "---  onServiceDisconnected   --- ");
    connect = false;
    if (mConnectListener != null) {
        mConnectListener.onDisconnected();
    }
}
 
Example 48
Project: boohee_v5.6   File: g.java   Source Code and License 5 votes vote down vote up
private void k() {
    try {
        this.c.getPackageManager().setComponentEnabledSetting(new ComponentName(this.c, "com" +
                ".xiaomi.push.service.XMPushService"), 1, 1);
    } catch (Throwable th) {
    }
}
 
Example 49
Project: orgzly-android   File: ListWidgetProvider.java   Source Code and License 5 votes vote down vote up
private static void updateListContents(Context context) {
    if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, "updateListContents");

    AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(context);

    ComponentName thisAppWidgetComponentName = new ComponentName(context.getPackageName(), ListWidgetProvider.class.getName());
    int[] appWidgetIds = appWidgetManager.getAppWidgetIds(thisAppWidgetComponentName);
    appWidgetManager.notifyAppWidgetViewDataChanged(appWidgetIds, R.id.list_widget_list_view);
}
 
Example 50
Project: GitHub   File: BaseFileServiceUIGuard.java   Source Code and License 5 votes vote down vote up
@Override
public void onServiceDisconnected(ComponentName name) {
    if (FileDownloadLog.NEED_LOG) {
        FileDownloadLog.d(this, "onServiceDisconnected %s %s", name, this.service);
    }
    releaseConnect(true);
}
 
Example 51
Project: prevent   File: ActivityManagerService.java   Source Code and License 5 votes vote down vote up
final ProcessRecord startProcessLocked(String processName, ApplicationInfo info,
                                       boolean knownToBeDead, int intentFlags, String hostingType, ComponentName hostingName,
                                       boolean allowWhileBooting, boolean isolated, int isolatedUid, boolean keepIfLarge,
                                       String abiOverride, String entryPoint, String[] entryPointArgs, Runnable crashHandler) {
    if (PreventRunningUtils.hookStartProcessLocked(processName, info, knownToBeDead, intentFlags, hostingType, hostingName)) {
        return startProcessLocked$Pr(processName, info,
                knownToBeDead, intentFlags, hostingType, hostingName,
                allowWhileBooting, isolated, isolatedUid, keepIfLarge,
                abiOverride, entryPoint, entryPointArgs, crashHandler);
    } else {
        return null;
    }
}
 
Example 52
Project: permissions4m   File: MEIZU.java   Source Code and License 5 votes vote down vote up
@Override
public Intent settingIntent() throws Exception {
    Intent intent = new Intent();
    intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.putExtra(PACK_TAG, activity.getPackageName());
    ComponentName comp = new ComponentName(PKG, getCls());
    intent.setComponent(comp);

    return intent;
}
 
Example 53
Project: BikeLine   File: ChooseLocationActivity.java   Source Code and License 5 votes vote down vote up
public void onServiceConnected(ComponentName className, IBinder service) {
    GPSService.GPSBinder binder = (GPSService.GPSBinder) service;
    gpsService = binder.getService();
    gpsService.startListener(ChooseLocationActivity.this);
    progressDialog.dismiss();
    if(address == null)
        updateNowLocation(new LatLng(gpsService.getLatitude(), gpsService.getLongitude()),
                                        getResources().getString(R.string.now_location_tag), false);
    if(address != null && address.equals(getResources().getString(R.string.now_location_tag))) {
        Log.i("ChooseLocationActivity", "here");
        searchPosition = new LatLng(gpsService.getLatitude(), gpsService.getLongitude());
        updateNowLocation(searchPosition, getResources().getString(R.string.now_location_tag), false);
    }
}
 
Example 54
Project: DepressingThoughts   File: AppWidget.java   Source Code and License 5 votes vote down vote up
@Override
public void onReceive(Context context, Intent intent) {
    super.onReceive(context, intent);
    if (intent.getAction().equals(AppWidgetManager.ACTION_APPWIDGET_UPDATE)) {
        final AppWidgetManager mgr = AppWidgetManager.getInstance(context);
        final ComponentName cn = new ComponentName(context, AppWidget.class);
        int[] appWidgetIds = mgr.getAppWidgetIds(cn);
        onUpdate(context, mgr, appWidgetIds);
    }
}
 
Example 55
Project: Hello-Music-droid   File: SmallWidget.java   Source Code and License 4 votes vote down vote up
@Override
void onViewsUpdate(Context context, RemoteViews remoteViews, ComponentName serviceName, Bundle extras) {
    remoteViews.setOnClickPendingIntent(R.id.image_next, PendingIntent.getService(
            context,
            REQUEST_NEXT,
            new Intent(context, MusicService.class)
                    .setAction(MusicService.NEXT_ACTION)
                    .setComponent(serviceName),
            0
    ));
    remoteViews.setOnClickPendingIntent(R.id.image_playpause, PendingIntent.getService(
            context,
            REQUEST_PLAYPAUSE,
            new Intent(context, MusicService.class)
                    .setAction(MusicService.TOGGLEPAUSE_ACTION)
                    .setComponent(serviceName),
            0
    ));
    if (extras != null) {
        String t = extras.getString("track");
        if (t != null) {
            remoteViews.setTextViewText(R.id.textView_title, t);
        }
        t = extras.getString("artist");
        if (t != null) {
            remoteViews.setTextViewText(R.id.textView_subtitle, t);
        }
        remoteViews.setImageViewResource(R.id.image_playpause,
                extras.getBoolean("playing") ? R.drawable.ic_pause_white_36dp : R.drawable.ic_play_white_36dp);
        long albumId = extras.getLong("albumid");
        if (albumId != -1) {
            Bitmap artwork = ImageLoader.getInstance().loadImageSync(TimberUtils.getAlbumArtUri(albumId).toString());
            if (artwork != null) {
                remoteViews.setImageViewBitmap(R.id.imageView_cover, artwork);
            } else {
                remoteViews.setImageViewResource(R.id.imageView_cover, R.drawable.ic_empty_music2);
            }
        }
    }
    remoteViews.setOnClickPendingIntent(R.id.textView_title, PendingIntent.getActivity(
            context,
            0,
            NavigationUtils.getNowPlayingIntent(context),
            PendingIntent.FLAG_UPDATE_CURRENT
    ));
}
 
Example 56
Project: android-dev-challenge   File: TestTaskContentProvider.java   Source Code and License 4 votes vote down vote up
/**
 * This test checks to make sure that the content provider is registered correctly in the
 * AndroidManifest file. If it fails, you should check the AndroidManifest to see if you've
 * added a <provider/> tag and that you've properly specified the android:authorities attribute.
 */
@Test
public void testProviderRegistry() {

    /*
     * A ComponentName is an identifier for a specific application component, such as an
     * Activity, ContentProvider, BroadcastReceiver, or a Service.
     *
     * Two pieces of information are required to identify a component: the package (a String)
     * it exists in, and the class (a String) name inside of that package.
     *
     * We will use the ComponentName for our ContentProvider class to ask the system
     * information about the ContentProvider, specifically, the authority under which it is
     * registered.
     */
    String packageName = mContext.getPackageName();
    String taskProviderClassName = TaskContentProvider.class.getName();
    ComponentName componentName = new ComponentName(packageName, taskProviderClassName);

    try {

        /*
         * Get a reference to the package manager. The package manager allows us to access
         * information about packages installed on a particular device. In this case, we're
         * going to use it to get some information about our ContentProvider under test.
         */
        PackageManager pm = mContext.getPackageManager();

        /* The ProviderInfo will contain the authority, which is what we want to test */
        ProviderInfo providerInfo = pm.getProviderInfo(componentName, 0);
        String actualAuthority = providerInfo.authority;
        String expectedAuthority = packageName;

        /* Make sure that the registered authority matches the authority from the Contract */
        String incorrectAuthority =
                "Error: TaskContentProvider registered with authority: " + actualAuthority +
                        " instead of expected authority: " + expectedAuthority;
        assertEquals(incorrectAuthority,
                actualAuthority,
                expectedAuthority);

    } catch (PackageManager.NameNotFoundException e) {
        String providerNotRegisteredAtAll =
                "Error: TaskContentProvider not registered at " + mContext.getPackageName();
        /*
         * This exception is thrown if the ContentProvider hasn't been registered with the
         * manifest at all. If this is the case, you need to double check your
         * AndroidManifest file
         */
        fail(providerNotRegisteredAtAll);
    }
}
 
Example 57
Project: CSipSimple   File: OutgoingCallChooser.java   Source Code and License 4 votes vote down vote up
@Override
public void onServiceDisconnected(ComponentName arg0) {
    service = null;
}
 
Example 58
Project: springreplugin   File: PluginCommImpl.java   Source Code and License 4 votes vote down vote up
/**
     * 加载插件Activity,在startActivity之前调用
     * @param intent
     * @param plugin 插件名
     * @param target 目标Service名,如果传null,则取获取到的第一个
     * @param process 是否在指定进程中启动
     * @return
     */
    public ComponentName loadPluginActivity(Intent intent, String plugin, String activity, int process) {

        ActivityInfo ai = null;
        String container = null;
        PluginBinderInfo info = new PluginBinderInfo(PluginBinderInfo.ACTIVITY_REQUEST);

        try {
            // 获取 ActivityInfo(可能是其它插件的 Activity,所以这里使用 pair 将 pluginName 也返回)
            ai = getActivityInfo(plugin, activity, intent);
            if (ai == null) {
                if (LOG) {
                    LogDebug.d(PLUGIN_TAG, "PACM: bindActivity: activity not found");
                }
                return null;
            }

            // 存储此 Activity 在插件 Manifest 中声明主题到 Intent
            intent.putExtra(INTENT_KEY_THEME_ID, ai.theme);
            if (LOG) {
                LogDebug.d("theme", String.format("intent.putExtra(%s, %s);", ai.name, ai.theme));
            }

            // 根据 activity 的 processName,选择进程 ID 标识
            if (ai.processName != null) {
                process = PluginClientHelper.getProcessInt(ai.processName);
            }

            // 容器选择(启动目标进程)
            IPluginClient client = RePluginOS.startPluginProcess(plugin, process, info);
            if (client == null) {
                return null;
            }

            // 远程分配坑位
            container = client.allocActivityContainer(plugin, process, ai.name, intent);
            if (LOG) {
                LogDebug.i(PLUGIN_TAG, "alloc success: container=" + container + " plugin=" + plugin + " activity=" + activity);
            }
        } catch (Throwable e) {
            if (LOGR) {
                LogRelease.e(PLUGIN_TAG, "l.p.a spp|aac: " + e.getMessage(), e);
            }
        }

        // 分配失败
        if (TextUtils.isEmpty(container)) {
            return null;
        }

        PluginMgr.cleanIntentPluginParams(intent);

        // TODO 是否重复
        // 附上额外数据,进行校验
//        intent.putExtra(PluginManager.EXTRA_PLUGIN, plugin);
//        intent.putExtra(PluginManager.EXTRA_ACTIVITY, activity);
//        intent.putExtra(PluginManager.EXTRA_PROCESS, process);
//        intent.putExtra(PluginManager.EXTRA_CONTAINER, container);

        PluginIntent ii = new PluginIntent(intent);
        ii.setPlugin(plugin);
        ii.setActivity(ai.name);
        ii.setProcess(IPluginManager.PROCESS_AUTO);
        ii.setContainer(container);
        ii.setCounter(0);
        return new ComponentName(IPC.getPackageName(), container);
    }
 
Example 59
Project: Ships   File: CalibrateTask.java   Source Code and License 4 votes vote down vote up
public void onServiceDisconnected(ComponentName className) {
	nmeaClientService = null;
}
 
Example 60
Project: ubiquitous   File: TestWeatherProvider.java   Source Code and License 4 votes vote down vote up
/**
 * This test checks to make sure that the content provider is registered correctly in the
 * AndroidManifest file. If it fails, you should check the AndroidManifest to see if you've
 * added a <provider/> tag and that you've properly specified the android:authorities attribute.
 * <p>
 * Potential causes for failure:
 * <p>
 *   1) Your WeatherProvider was registered with the incorrect authority
 * <p>
 *   2) Your WeatherProvider was not registered at all
 */
@Test
public void testProviderRegistry() {

    /*
     * A ComponentName is an identifier for a specific application component, such as an
     * Activity, ContentProvider, BroadcastReceiver, or a Service.
     *
     * Two pieces of information are required to identify a component: the package (a String)
     * it exists in, and the class (a String) name inside of that package.
     *
     * We will use the ComponentName for our ContentProvider class to ask the system
     * information about the ContentProvider, specifically, the authority under which it is
     * registered.
     */
    String packageName = mContext.getPackageName();
    String weatherProviderClassName = WeatherProvider.class.getName();
    ComponentName componentName = new ComponentName(packageName, weatherProviderClassName);

    try {

        /*
         * Get a reference to the package manager. The package manager allows us to access
         * information about packages installed on a particular device. In this case, we're
         * going to use it to get some information about our ContentProvider under test.
         */
        PackageManager pm = mContext.getPackageManager();

        /* The ProviderInfo will contain the authority, which is what we want to test */
        ProviderInfo providerInfo = pm.getProviderInfo(componentName, 0);
        String actualAuthority = providerInfo.authority;
        String expectedAuthority = WeatherContract.CONTENT_AUTHORITY;

        /* Make sure that the registered authority matches the authority from the Contract */
        String incorrectAuthority =
                "Error: WeatherProvider registered with authority: " + actualAuthority +
                        " instead of expected authority: " + expectedAuthority;
        assertEquals(incorrectAuthority,
                actualAuthority,
                expectedAuthority);

    } catch (PackageManager.NameNotFoundException e) {
        String providerNotRegisteredAtAll =
                "Error: WeatherProvider not registered at " + mContext.getPackageName();
        /*
         * This exception is thrown if the ContentProvider hasn't been registered with the
         * manifest at all. If this is the case, you need to double check your
         * AndroidManifest file
         */
        fail(providerNotRegisteredAtAll);
    }
}