Java 类android.app.Service 实例源码

项目:letv    文件:ServcesManager.java   
private void handleOnStartOne(Intent intent, int flags, int startIds) throws Exception {
    ServiceInfo info = ApkManager.getInstance().resolveServiceInfo(intent, 0);
    if (info != null) {
        Service service = (Service) this.mNameService.get(info.name);
        if (service != null) {
            intent.setExtrasClassLoader(getClassLoader(info.applicationInfo));
            Object token = findTokenByService(service);
            Integer integer = (Integer) this.mServiceTaskIds.get(token);
            if (integer == null) {
                integer = Integer.valueOf(-1);
            }
            int startId = integer.intValue() + 1;
            this.mServiceTaskIds.put(token, Integer.valueOf(startId));
            int res = service.onStartCommand(intent, flags, startId);
            QueuedWorkCompat.waitToFinish();
        }
    }
}
项目:Logistics-guard    文件:PhoneStatReceiver.java   
@Override
public void onReceive(Context context, Intent intent) {
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
    switch (tm.getCallState()) {
        case TelephonyManager.CALL_STATE_RINGING:
            context.startService(new Intent(context, RecordAudioService.class));
            break;
        case TelephonyManager.CALL_STATE_OFFHOOK:

            break;
        case TelephonyManager.CALL_STATE_IDLE:
            context.stopService(new Intent(context, RecordAudioService.class));
            break;
    }
}
项目:Java-9-Programming-Blueprints    文件:WifiReceiver.java   
@Override
public void onReceive(Context context, Intent intent) {
    WifiManager wifiMgr = (WifiManager) context.getApplicationContext()
            .getSystemService(Service.WIFI_SERVICE);
    if (wifiMgr.isWifiEnabled()) {
        context.startService(new Intent(context, DeskDroidService.class));
    } else {
        context.stopService(new Intent(context, DeskDroidService.class));
    }
}
项目:android-apkbox    文件:HookService_Manager.java   
private static void createService(Service service, Intent intent) {
    if (intent.hasExtra(ApkConstant.EXTRA_APK_PATH)) {
        String apkPath = ApkComponentModifier.getPath(intent);
        String className = ApkComponentModifier.getClassName(intent);
        String key = ApkComponentModifier.getKey(intent);
        if (!mRealServices.containsKey(service) || !mRealServices.get(service).containsKey(key)) {
            try {
                Object realToken = new Binder();
                Service rawService = handleCreateService(realToken, service, apkPath, className);
                if (mRealServices.containsKey(service)) {
                    mRealServices.get(service).put(key, rawService);
                } else {
                    Map<String, Service> serviceMap = new HashMap<>();
                    serviceMap.put(key, rawService);
                    mRealServices.put(service, serviceMap);
                }
            } catch (Exception e) {
            }
        }
    }
}
项目:boohee_v5.6    文件:WXApiImplV10.java   
public final boolean registerApp(String str) {
    if (this.detached) {
        throw new IllegalStateException("registerApp fail, WXMsgImpl has been detached");
    } else if (WXApiImplComm.validateAppSignatureForPackage(this.context, "com.tencent.mm",
            this.checkSignature)) {
        if (activityCb == null && VERSION.SDK_INT >= 14) {
            if (this.context instanceof Activity) {
                initMta(this.context, str);
                activityCb = new ActivityLifecycleCb(this.context);
                ((Activity) this.context).getApplication().registerActivityLifecycleCallbacks
                        (activityCb);
            } else if (this.context instanceof Service) {
                initMta(this.context, str);
                activityCb = new ActivityLifecycleCb(this.context);
                ((Service) this.context).getApplication().registerActivityLifecycleCallbacks
                        (activityCb);
            } else {
                a.b(TAG, "context is not instanceof Activity or Service, disable WXStat");
            }
        }
        a.d(TAG, "registerApp, appId = " + str);
        if (str != null) {
            this.appId = str;
        }
        a.d(TAG, "register app " + this.context.getPackageName());
        com.tencent.mm.sdk.a.a.a.a aVar = new com.tencent.mm.sdk.a.a.a.a();
        aVar.o = "com.tencent.mm";
        aVar.p = ConstantsAPI.ACTION_HANDLE_APP_REGISTER;
        aVar.m = "weixin://registerapp?appid=" + this.appId;
        return com.tencent.mm.sdk.a.a.a.a(this.context, aVar);
    } else {
        a.a(TAG, "register app failed for wechat app signature check failed");
        return false;
    }
}
项目:dcs-sdk-java    文件:MediaPlayerImpl.java   
public MediaPlayerImpl() {
    mMediaPlayer = new MediaPlayer();
    // set audio stream type
    mMediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
    mMediaPlayer.setOnBufferingUpdateListener(bufferingUpdateListener);
    mMediaPlayer.setOnErrorListener(errorListener);
    mMediaPlayer.setOnPreparedListener(preparedListener);
    mMediaPlayer.setOnCompletionListener(completionListener);
    mMediaPlayer.setOnSeekCompleteListener(seekCompleteListener);
    // 不同的音频源,此回调有的不回调!!!
    // mMediaPlayer.setOnInfoListener(infoListener);

    // 读取音量和静音的数据
    currentVolume = (float) MediaPlayerPreferenceUtil.get(context,
            KEY_SP_VOLUME, 0.8f);
    isMute = (boolean) MediaPlayerPreferenceUtil.get(context,
            KEY_SP_MUTE, false);
    // LinkedList
    mediaPlayerListeners = Collections.synchronizedList(new LinkedList<IMediaPlayer.IMediaPlayerListener>());
    posHandler = new PosHandler(Looper.getMainLooper());

    // 来电监听
    telephonyManager = (TelephonyManager)
            context.getSystemService(Service.TELEPHONY_SERVICE);
    telephonyManager.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
项目:Remindy    文件:NotificationIntentService.java   
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "onStartCommand()");

    // Create an instance of GoogleAPIClient.
    if (mGoogleApiClient == null) {
        mGoogleApiClient = new GoogleApiClient.Builder(this)
                .addConnectionCallbacks(this)
                .addOnConnectionFailedListener(this)
                .addApi(LocationServices.API)
                .build();
        mGoogleApiClient.connect();
    }

    //Reset triggered tasks
    SharedPreferenceUtil.setTriggeredTaskList(new ArrayList<Integer>(), getApplicationContext());

    //Update Alarms
    AlarmManagerUtil.updateAlarms(getApplicationContext());


    return Service.START_NOT_STICKY;
}
项目:airgram    文件:VideoEncodingService.java   
public int onStartCommand(Intent intent, int flags, int startId) {
    path = intent.getStringExtra("path");
    if (path == null) {
        stopSelf();
        return Service.START_NOT_STICKY;
    }
    FileLog.e("tmessages", "start video service");
    if (builder == null) {
        builder = new NotificationCompat.Builder(ApplicationLoader.applicationContext);
        builder.setSmallIcon(android.R.drawable.stat_sys_upload);
        builder.setWhen(System.currentTimeMillis());
        builder.setContentTitle(LocaleController.getString("AppName", R.string.AppName));
        builder.setTicker(LocaleController.getString("SendingVideo", R.string.SendingVideo));
        builder.setContentText(LocaleController.getString("SendingVideo", R.string.SendingVideo));
    }
    currentProgress = 0;
    builder.setProgress(100, currentProgress, currentProgress == 0);
    startForeground(4, builder.build());
    NotificationManagerCompat.from(ApplicationLoader.applicationContext).notify(4, builder.build());
    return Service.START_NOT_STICKY;
}
项目:stay-awake-app    文件:HandleNotifications.java   
private static Notification buildNotification(Service context, String channelId) {
    // Create Pending Intents.
    PendingIntent piLaunchMainActivity = getLaunchActivityPI(context);
    PendingIntent piStopService = getStopServicePI(context);

    // Action to stop the service.
    Notification.Action stopAction =
            new Notification.Action.Builder(
                            STOP_ACTION_ICON,
                            getNotificationStopActionText(context),
                            piStopService)
                    .build();

    // Create a notification.
    return new Notification.Builder(context, channelId)
            .setContentTitle(getNotificationTitle(context))
            .setContentText(getNotificationContent(context))
            .setSmallIcon(SMALL_ICON)
            .setContentIntent(piLaunchMainActivity)
            .setActions(stopAction)
            .setStyle(new Notification.BigTextStyle())
            .build();
}
项目:DroidPlugin    文件:ServcesManager.java   
private void handleOnTaskRemovedOne(Intent intent) throws Exception {
    if (VERSION.SDK_INT >= VERSION_CODES.ICE_CREAM_SANDWICH) {
        ServiceInfo info = PluginManager.getInstance().resolveServiceInfo(intent, 0);
        if (info != null) {
            Service service = mNameService.get(info.name);
            if (service != null) {
                ClassLoader classLoader = getClassLoader(info.applicationInfo);
                intent.setExtrasClassLoader(classLoader);
                service.onTaskRemoved(intent);
                QueuedWorkCompat.waitToFinish();
            }
            QueuedWorkCompat.waitToFinish();
        }
    }
}
项目:AppFirCloud    文件:DownLoadService.java   
@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Bundle extras = intent.getExtras();
        if (extras != null) {
            apkName = extras.getString("name");
            downloadUrl = extras.getString("downloadurl");
            Logger.i("DownLoadService: %s", apkName + "\r\n" + downloadUrl);
//            downloadUrl = "http://pro-app-qn.fir.im/f63088ce552e398521ce5840de798c803b29dd2c.apk?attname=appcloud-v1.0.0-huawei-release.apk_V1.0.0.apk&e=1513073607&token=LOvmia8oXF4xnLh0IdH05XMYpH6ENHNpARlmPc-T:zlbPNpvxSrX779NlvRQW0kTjPr0=";
            apkName = apkName + "_" + Long.toString(System.currentTimeMillis() / 1000) + ".apk";
            Log.i(TAG, "apkName: " + apkName);
        }

        //如果路径下apk文件存在,就删除
        File file = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS), apkName);
        if (file.exists()) {
            file.delete();
        }

        //创建广播对象并注册广播,用于监听下载完成后自动安装APK
        mReceiver = new DownloadCompleteReceiver();
        registerReceiver(mReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

        //下载需要写SD卡权限, targetSdkVersion>=23 需要动态申请权限
        applyPermissions();

        return Service.START_STICKY;
    }
项目:orgzly-android    文件:SyncService.java   
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (BuildConfig.LOG_DEBUG) LogUtils.d(TAG, intent);

    boolean isTriggeredAutomatically = isTriggeredAutomatically(intent);

    if (intent != null && AppIntent.ACTION_SYNC_START.equals(intent.getAction())) {
        if (!isRunning()) {
            start(isTriggeredAutomatically);
        }

    } else if (intent != null && AppIntent.ACTION_SYNC_STOP.equals(intent.getAction())) {
        if (isRunning()) {
            stop();
        }

    } else {
        if (isRunning()) {
            stop();
        } else {
            start(isTriggeredAutomatically);
        }
    }

    return Service.START_REDELIVER_INTENT;
}
项目:atlas    文件:BaseDelegateService.java   
private void handleServiceArgs(Intent serviceIntent,IBinder token){
    Service service = mActivateServices.get(token);
    if(service!=null){
        if(serviceIntent!=null) {
            serviceIntent.setExtrasClassLoader(service.getClassLoader());
        }
        service.onStartCommand(serviceIntent,Service.START_FLAG_RETRY,0);
    }
}
项目:letv    文件:ServcesManager.java   
private void handleOnTaskRemovedOne(Intent intent) throws Exception {
    if (VERSION.SDK_INT >= 14) {
        ServiceInfo info = ApkManager.getInstance().resolveServiceInfo(intent, 0);
        if (info != null) {
            Service service = (Service) this.mNameService.get(info.name);
            if (service != null) {
                intent.setExtrasClassLoader(getClassLoader(info.applicationInfo));
                service.onTaskRemoved(intent);
                QueuedWorkCompat.waitToFinish();
            }
            QueuedWorkCompat.waitToFinish();
        }
    }
}
项目:letv    文件:ServcesManager.java   
private IBinder handleOnBindOne(Intent intent) throws Exception {
    ServiceInfo info = ApkManager.getInstance().resolveServiceInfo(intent, 0);
    if (info != null) {
        Service service = (Service) this.mNameService.get(info.name);
        if (service != null) {
            intent.setExtrasClassLoader(getClassLoader(info.applicationInfo));
            return service.onBind(intent);
        }
    }
    return null;
}
项目:letv    文件:ServcesManager.java   
private void handleOnRebindOne(Intent intent) throws Exception {
    ServiceInfo info = ApkManager.getInstance().resolveServiceInfo(intent, 0);
    if (info != null) {
        Service service = (Service) this.mNameService.get(info.name);
        if (service != null) {
            intent.setExtrasClassLoader(getClassLoader(info.applicationInfo));
            service.onRebind(intent);
        }
    }
}
项目:chromium-swe-updater    文件:CheckUpdateService.java   
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    updater.checkForUpdate(new ChromiumUpdater.ReturnCallback<Boolean>() {
        @Override
        public void onReturn(Boolean returnValue) {
            if(returnValue == null) {
                showUpdateFailure();
            } else if(returnValue) {
                showUpdateNotification();
            }

            stopSelf();
        }
    });
    Log.d(TAG, "notify update");
    return Service.START_STICKY;
}
项目:DroidPlugin    文件:ServcesManager.java   
public void onRebind(Context context, Intent intent) throws Exception {
    Intent targetIntent = intent.getParcelableExtra(Env.EXTRA_TARGET_INTENT);
    if (targetIntent != null) {
        ServiceInfo info = PluginManager.getInstance().resolveServiceInfo(targetIntent, 0);
        Service service = mNameService.get(info.name);
        if (service == null) {
            handleCreateServiceOne(context, intent, info);
        }
        handleOnRebindOne(targetIntent);
    }
}
项目:GitHub    文件:TinkerServiceInternals.java   
private static String getServiceProcessName(Context context, Class<? extends Service> serviceClass) {
    PackageManager packageManager = context.getPackageManager();

    ComponentName component = new ComponentName(context, serviceClass);
    ServiceInfo serviceInfo;
    try {
        serviceInfo = packageManager.getServiceInfo(component, 0);
    } catch (Throwable ignored) {
        // Service is disabled.
        return null;
    }

    return serviceInfo.processName;
}
项目:malvarez-watchface    文件:HeartRateWidget.java   
@Override
public void init(Service service) {
    this.textLeft = service.getResources().getDimension(R.dimen.malvarez_heart_rate_text_left);
    this.textTop = service.getResources().getDimension(R.dimen.malvarez_heart_rate_text_top);

    this.textPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
    this.textPaint.setColor(service.getResources().getColor(R.color.malvarez_time_colour));
    this.textPaint.setTypeface(ResourceManager.getTypeFace(service.getResources(), ResourceManager.Font.BEBAS_NEUE));
    this.textPaint.setTextSize(service.getResources().getDimension(R.dimen.malvarez_circles_font_size));
    this.textPaint.setTextAlign(Paint.Align.CENTER);

    this.heartIcon = service.getResources().getDrawable(R.drawable.heart, null);
    this.setDrawableBounds(this.heartIcon, service.getResources().getDimension(R.dimen.malvarez_heart_rate_icon_left), service.getResources().getDimension(R.dimen.malvarez_heart_rate_icon_top));
}
项目:OSchina_resources_android    文件:BaseSensorFragment.java   
@Override
protected void initWidget(View root) {
    super.initWidget(root);
    mSensor = (SensorManager) getActivity()
            .getSystemService(Context.SENSOR_SERVICE);
    mVibrator = (Vibrator) getActivity().getSystemService(Service.VIBRATOR_SERVICE);
    mCardView.setOnClickListener(this);
}
项目:Snach-Android    文件:BLEManager.java   
public BLEManager(String deviceAddress, Context applicationContext, Service mService) {
    this.DEVICE_ADDRESS = deviceAddress;
    this.context = applicationContext;
    this.mConnectionListener = (OnConnectionEventListener) mService;

    initSharedPref();
    initSavedGestures();
    initSnachScreens();
    gestureHandler = new GestureProcessingHandler(gestureCharacteristicsData, context, this);

    connectionTimeoutChecker = new Handler();
    connectionTimeoutRunnable = new Runnable() {
        @Override
        public void run() {
            if(isSnachConnected) {
                isSnachConnected = false;
                mConnectionListener.ConnectionLost();
            }
        }
    };

    connectionTimeoutChecker.postDelayed(connectionTimeoutRunnable, Globals.DEFAULT_CONNECTED_TIMEOUT);

    dataLostChecker = new Handler();
    dataLostRunnable = new Runnable() {
        @Override
        public void run() {
            hasFinishedWriting = true;
        }
    };

    initSnachNotifications();
}
项目:letv    文件:ServcesManager.java   
public void onDestroy() {
    for (Service service : this.mTokenServices.values()) {
        service.onDestroy();
    }
    this.mTokenServices.clear();
    this.mServiceTaskIds.clear();
    this.mNameService.clear();
    QueuedWorkCompat.waitToFinish();
}
项目:DebugOverlay-Android    文件:DebugOverlayService.java   
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    if (DebugOverlay.DEBUG) {
        Log.i(TAG, "onStartCommand() called");
    }
    config = intent.getParcelableExtra(DebugOverlay.KEY_CONFIG);
    // no need to restart this service
    return Service.START_NOT_STICKY;
}
项目:malvarez-watchface    文件:HeartRateWidget.java   
@Override
public List<SlptViewComponent> buildSlptViewComponent(Service service) {
    SlptLinearLayout heart = new SlptLinearLayout();
    heart.add(new SlptLastHeartRateView());
    heart.setTextAttrForAll(
            service.getResources().getDimension(R.dimen.malvarez_circles_font_size_slpt),
            -1,
            ResourceManager.getTypeFace(service.getResources(), ResourceManager.Font.BEBAS_NEUE)
    );
    heart.setStart(
            (int) service.getResources().getDimension(R.dimen.malvarez_heart_rate_text_left_slpt),
            (int) service.getResources().getDimension(R.dimen.malvarez_heart_rate_text_top_slpt));
    return Collections.<SlptViewComponent>singletonList(heart);
}
项目:android-ponewheel    文件:VibrateService.java   
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d(TAG, "Vibrate Service started");
    return Service.START_NOT_STICKY;
    //return super.onStartCommand(intent, flags, startId);

}
项目:malvarez-watchface    文件:MalvarezClock.java   
@Override
public void init(Service service) {

    this.background = service.getResources().getColor(R.color.malvarez_background);

    this.leftHour = service.getResources().getDimension(R.dimen.malvarez_time_hour_left);
    this.topHour = service.getResources().getDimension(R.dimen.malvarez_time_hour_top);
    this.leftMinute = service.getResources().getDimension(R.dimen.malvarez_time_minute_left);
    this.topMinute = service.getResources().getDimension(R.dimen.malvarez_time_minute_top);
    this.leftDate = service.getResources().getDimension(R.dimen.malvarez_date_left);
    this.topDate = service.getResources().getDimension(R.dimen.malvarez_date_top);

    this.hourFont = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
    this.hourFont.setTypeface(ResourceManager.getTypeFace(service.getResources(), ResourceManager.Font.BEBAS_NEUE));
    this.hourFont.setTextSize(service.getResources().getDimension(R.dimen.malvarez_time_font_size));
    this.hourFont.setColor(service.getResources().getColor(R.color.malvarez_time_colour));
    this.hourFont.setTextAlign(Paint.Align.CENTER);

    this.timeFont = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
    this.timeFont.setTypeface(ResourceManager.getTypeFace(service.getResources(), ResourceManager.Font.BEBAS_NEUE));
    this.timeFont.setTextSize(service.getResources().getDimension(R.dimen.malvarez_time_font_size));
    this.timeFont.setColor(service.getResources().getColor(R.color.malvarez_hour_colour));
    this.timeFont.setTextAlign(Paint.Align.CENTER);

    this.dateFont = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
    this.dateFont.setTypeface(ResourceManager.getTypeFace(service.getResources(), ResourceManager.Font.BEBAS_NEUE));
    this.dateFont.setTextSize(service.getResources().getDimension(R.dimen.malvarez_date_font_size));
    this.dateFont.setColor(service.getResources().getColor(R.color.malvarez_time_colour));
    this.dateFont.setTextAlign(Paint.Align.CENTER);
}
项目:QuranAndroid    文件:DownloadManager.java   
/**
 * Function show download information
 *
 * @param values download information values
 */
@Override
protected void onProgressUpdate(Long... values) {

    if (downloadProgressBar != null) {
        downloadProgressBar.setMax(values[1].intValue());
        downloadProgressBar.setProgress(values[0].intValue());
    }

    if (downloadInfo != null) {
        downloadInfo.setText(values[1] / 1000000 + "/" + values[0] / 1000000);
    }

    if (notificationDownloaderFlag) {
        //remoteViews.setProgressBar(R.id.progressBar2, , , false);
        builder.setProgress(values[1].intValue(), values[0].intValue(), false);
        notificationManager.notify(0, builder.build());
    }

    if (context != null) {
        if (context instanceof Service) {
            Intent i = new Intent(AppConstants.Download.INTENT);
            i.putExtra(AppConstants.Download.NUMBER, values[0]);
            i.putExtra(AppConstants.Download.MAX, values[1]);
            i.putExtra(AppConstants.Download.DOWNLOAD, AppConstants.Download.IN_DOWNLOAD);
            LocalBroadcastManager.getInstance(context).sendBroadcast(i);
        }

    }

}
项目:android-apkbox    文件:HookService_Manager.java   
public static void onLowMemoryService(Service service) {
    if (mRealServices.containsKey(service)) {
        Map<String, Service> serviceMap = mRealServices.get(service);
        for (Map.Entry<String, Service> entry :
                serviceMap.entrySet()) {
            entry.getValue().onLowMemory();
        }
    }
}
项目:phonk    文件:PhonkServerService.java   
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    MLog.d(TAG, "onStartCommand");

    if (intent != null) {
        AndroidUtils.debugIntent(TAG, intent);
        if (intent.getAction() == SERVICE_CLOSE) stopSelf();
    }

    return Service.START_STICKY;
}
项目:SocialLogin    文件:SocialLogin.java   
/**
 * Initialize SocialLogin
 *
 * @param context {@link Context} object, it will be Application Context.
 */
public static void init(Context context) {
    if (context instanceof Activity || context instanceof Service) {
        throw new InvalidParameterException("Context must be Application Context, not Activity, Service Context.");
    }

    mContext = context;
    clear();
}
项目:SocialLogin    文件:SocialLogin.java   
/**
 * Initialize SocialLogin with pre-configured AvailableTypeMap
 *
 * @param context
 * @param availableTypeMap
 */
public static void init(Context context, Map<SocialType, SocialConfig> availableTypeMap) {
    if (context instanceof Activity || context instanceof Service) {
        throw new InvalidParameterException("Context must be Application Context, not Activity, Service Context.");
    }

    mContext = context;

    if (!availableTypeMap.isEmpty()) {
        SocialLogin.availableTypeMap = availableTypeMap;
        initializeSDK();
    }
}
项目:Synapse    文件:MainService.java   
private void downloadFiles() {
    deleteOldFiles();

    final String[] files = Global.getInstance().getDataSet();
    final DownloadManager downloadManager = (DownloadManager) getSystemService(DOWNLOAD_SERVICE);

    if (downloadManager == null) {
        return;
    }

    unregisterDownloadReceiver();

    final Uri baseUri = Global.getInstance().getBaseDownloadUri();
    final File downloadDir = Global.getInstance().getDirs().download;
    final Set<Long> ids = new HashSet<>();

    for (String file : files) {
        final Uri uri = Uri.withAppendedPath(baseUri, file);
        final DownloadManager.Request request = new DownloadManager.Request(uri);

        request.setAllowedNetworkTypes(DownloadManager.Request.NETWORK_MOBILE
                | DownloadManager.Request.NETWORK_WIFI);
        request.setVisibleInDownloadsUi(true);
        request.setDestinationUri(Uri.fromFile(new File(downloadDir, file)));

        ids.add(downloadManager.enqueue(request));
    }

    mDownloadReceiver = new DownloadReceiver(downloadManager, ids);
    registerReceiver(mDownloadReceiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));

    TimeHelper.getInstance()
            .start(TrackCons.Service.DOWNLOAD);
}
项目:vinyl-cast    文件:Helpers.java   
public static void createStopNotification(MediaSessionCompat mediaSession, Service context, Class<?> serviceClass, int NOTIFICATION_ID) {

        PendingIntent stopIntent = PendingIntent
                .getService(context, 0, getIntent(MediaRecorderService.REQUEST_TYPE_STOP, context, serviceClass),
                        PendingIntent.FLAG_CANCEL_CURRENT);

        MediaControllerCompat controller = mediaSession.getController();
        MediaMetadataCompat mediaMetadata = controller.getMetadata();
        MediaDescriptionCompat description = mediaMetadata.getDescription();
        // Start foreground service to avoid unexpected kill
        Notification notification = new NotificationCompat.Builder(context)
                .setContentTitle(description.getTitle())
                .setContentText(description.getSubtitle())
                .setSubText(description.getDescription())
                .setLargeIcon(description.getIconBitmap())
                .setDeleteIntent(stopIntent)
                // Add a pause button
                .addAction(new android.support.v7.app.NotificationCompat.Action(
                        R.drawable.ic_stop_black_24dp, context.getString(R.string.stop),
                        MediaButtonReceiver.buildMediaButtonPendingIntent(context,
                                PlaybackStateCompat.ACTION_STOP)))
                .setStyle(new android.support.v7.app.NotificationCompat.MediaStyle()
                        .setMediaSession(mediaSession.getSessionToken())
                        .setShowActionsInCompactView(0)
                        .setShowCancelButton(true)
                        .setCancelButtonIntent(MediaButtonReceiver.buildMediaButtonPendingIntent(context,
                                PlaybackStateCompat.ACTION_STOP)))
                .setSmallIcon(R.drawable.ic_album_black_24dp)
                .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)
                .build();

        context.startForeground(NOTIFICATION_ID, notification);
    }
项目:RepWifiApp    文件:Commons.java   
public static void updateNotification(Context context) {

        ConnectionStatus status = connectionEngine.getConnectionStatus();

        Notification.Builder builder = new Notification.Builder(context);

        Intent intent = new Intent(context, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, intent, 0);
        builder.setContentIntent(pendingIntent);

        int iconId = R.drawable.ic_stat_discon;
        String msg = "RepWifi";
        if (status != null) {
            if (status.isConnected()) {
                iconId = R.drawable.ic_stat_repwifi;
                msg += " - " + status.SSID;
            } else {
                msg += " - " + status.status;
            }

        }

        builder.setSmallIcon(iconId);

        builder.setContentTitle(msg);
        builder.setContentText("Touch to open.");

        Notification n = builder.build();
        n.flags |= Notification.FLAG_NO_CLEAR;

        NotificationManager notificationManager = (NotificationManager) context
                        .getSystemService(Service.NOTIFICATION_SERVICE);
        notificationManager.notify(NOTIFICATION_ID, n);

    }
项目:stay-awake-app    文件:HandleNotifications.java   
/** Get pending intent to launch the activity. */
private static PendingIntent getLaunchActivityPI(Service context) {
    PendingIntent piLaunchMainActivity;
    {
        Intent iLaunchMainActivity = new Intent(context, MainActivity.class);
        piLaunchMainActivity =
                PendingIntent.getActivity(context, getRandomNumber(), iLaunchMainActivity, 0);
    }
    return piLaunchMainActivity;
}
项目:DroidPlugin    文件:ServcesManager.java   
public IBinder onBind(Context context, Intent intent) throws Exception {
    Intent targetIntent = intent.getParcelableExtra(Env.EXTRA_TARGET_INTENT);
    if (targetIntent != null) {
        ServiceInfo info = PluginManager.getInstance().resolveServiceInfo(targetIntent, 0);
        Service service = mNameService.get(info.name);
        if (service == null) {
            handleCreateServiceOne(context, intent, info);
        }
        return handleOnBindOne(targetIntent);
    }
    return null;
}
项目:DroidPlugin    文件:ServcesManager.java   
public void onTaskRemoved(Context context, Intent intent) throws Exception {
    Intent targetIntent = intent.getParcelableExtra(Env.EXTRA_TARGET_INTENT);
    if (targetIntent != null) {
        ServiceInfo info = PluginManager.getInstance().resolveServiceInfo(targetIntent, 0);
        Service service = mNameService.get(info.name);
        if (service == null) {
            handleCreateServiceOne(context, intent, info);
        }
        handleOnTaskRemovedOne(targetIntent);
    }
}
项目:stay-awake-app    文件:HandleNotifications.java   
@NonNull
private static String createChannel(Service context) {
    // Create a channel.
    NotificationManager notificationManager =
            (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
    CharSequence channelName = "Playback channel";
    int importance = NotificationManager.IMPORTANCE_DEFAULT;
    NotificationChannel notificationChannel =
            new NotificationChannel(CHANNEL_ID, channelName, importance);
    notificationManager.createNotificationChannel(notificationChannel);
    return CHANNEL_ID;
}
项目:Hold    文件:PpwMaskService.java   
@SuppressLint("InflateParams")
private void initView() {
    mReceiver = new HomeKeyEventBroadCastReceiver();
    registerReceiver(mReceiver, new IntentFilter(Intent.ACTION_SCREEN_OFF));

    PowerManager powerManager = (PowerManager) this.getSystemService(Service.POWER_SERVICE);
    //noinspection deprecation
    mWakeLock = powerManager.newWakeLock(android.os.PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "My Lock");
    mWakeLock.acquire();
    mWindowView = LayoutInflater.from(getApplication()).inflate(R.layout.ppw_mask, null);
}