android.app.Service Java Examples

The following examples show how to use android.app.Service. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: ServiceManager.java    From BigApp_Discuz_Android with Apache License 2.0 6 votes vote down vote up
public void startService(final Context context, final Service... services) {

        Thread serviceThread = new Thread(new Runnable() {
            @Override
            public void run() {
                for (Service s : services) {

                    if (!ServiceUtils.isServiceRunning(context, s.getClass()
                            .getName())) {

                        Intent i = new Intent(context, s.getClass());
                        context.startService(i);

                        ZogUtils.printLog(ServiceManager.class,
                                "start service " + s.getClass().getName());
                    }

                }
            }
        });
        serviceThread.start();
    }
 
Example #2
Source File: StepsWidget.java    From GreatFit with MIT License 6 votes vote down vote up
public void init(Service service) {
    this.mService = service;

    if(settings.steps>0){
        this.stepsPaint = new Paint(Paint.ANTI_ALIAS_FLAG);
        this.stepsPaint.setTypeface(ResourceManager.getTypeFace(service.getResources(), settings.font));
        this.stepsPaint.setTextSize(settings.stepsFontSize);
        this.stepsPaint.setColor(settings.stepsColor);
        this.stepsPaint.setTextAlign( (settings.stepsAlignLeft) ? Paint.Align.LEFT : Paint.Align.CENTER );

        if(settings.stepsIcon){
            this.icon = Util.decodeImage(mService.getResources(),"icons/"+settings.is_white_bg+"steps.png");
        }
    }

    if(settings.stepsProg>0 && settings.stepsProgType==0){
        this.ring = new Paint(Paint.ANTI_ALIAS_FLAG);
        this.ring.setStrokeCap(Paint.Cap.ROUND);
        this.ring.setStyle(Paint.Style.STROKE);
        this.ring.setStrokeWidth(settings.stepsProgThickness);
    }
}
 
Example #3
Source File: HeartRateWidget.java    From GreatFit with MIT License 6 votes vote down vote up
@Override
public void init(Service service) {
    this.mService = service;

    this.textPaint = new TextPaint(TextPaint.ANTI_ALIAS_FLAG);
    this.textPaint.setColor(settings.heart_rateColor);
    this.textPaint.setTypeface(ResourceManager.getTypeFace(service.getResources(), settings.font));
    this.textPaint.setTextSize(settings.heart_rateFontSize);
    this.textPaint.setTextAlign( (settings.heart_rateAlignLeft) ? Paint.Align.LEFT : Paint.Align.CENTER );

    if(settings.heart_rateIcon){
        this.heart_rateIcon = Util.decodeImage(service.getResources(),"icons/"+settings.is_white_bg+"heart_rate.png");
        this.heart_rate_flashingIcon = Util.decodeImage(service.getResources(),"icons/"+settings.is_white_bg+"heart_rate_flashing.png");
    }
    
    // Progress Bar Circle
    if(settings.heart_rateProg>0 && settings.heart_rateProgType==0){
        this.ring = new Paint(Paint.ANTI_ALIAS_FLAG);
        this.ring.setStrokeCap(Paint.Cap.ROUND);
        this.ring.setStyle(Paint.Style.STROKE);
        this.ring.setStrokeWidth(settings.heart_rateProgThickness);
    }
}
 
Example #4
Source File: LocationService.java    From open-quartz with Apache License 2.0 6 votes vote down vote up
@Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        if (mLiveCard == null) {
            Log.d(LocationService.TAG, "Publishing LiveCard");
//            mLiveCard = mTimelineManager
//                    .createLiveCard(LocationService.LIVE_CARD_TAG);

            // Keep track of the callback to remove it before unpublishing.
            mCallback = new ChronometerDrawer(this);
            mLiveCard.setDirectRenderingEnabled(true).getSurfaceHolder()
                    .addCallback(mCallback);

            final Intent menuIntent = new Intent(this, MenuActivity.class);
            menuIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                    | Intent.FLAG_ACTIVITY_CLEAR_TASK);
            mLiveCard.setAction(PendingIntent.getActivity(this, 0,
                    menuIntent, 0));

            mLiveCard.publish(PublishMode.REVEAL);
            Log.d(LocationService.TAG, "Done publishing LiveCard");
        } else {
            // TODO(alainv): Jump to the LiveCard when API is available.
        }

        return Service.START_STICKY;
    }
 
Example #5
Source File: ThreeLinesStepsWidget.java    From AmazfitAPKs with Apache License 2.0 6 votes vote down vote up
@Override
public List<SlptViewComponent> buildSlptViewComponent(Service service) {
    init(service);

    final float totalHeight = fontHeight * nLines - verticalOffset;
    final float x = 160;
    float y = 160 - totalHeight/2 ;

    SlptLinearLayout steps = new SlptLinearLayout();
    steps.add(new SlptTodayStepNumView());
    steps.setTextAttrForAll(
            service.getResources().getDimension(R.dimen.threelines_font_size),
            service.getResources().getColor(R.color.threelines_steps_color),
            ResourceManager.getTypeFace(service.getResources(), ResourceManager.Font.OPEN24)
    );
    steps.centerHorizontal = 1;

    y += fontHeight*2;

    steps.setStart((int)x,(int)y);

    return Collections.<SlptViewComponent>singletonList(steps);
}
 
Example #6
Source File: UploadPhotoService.java    From Klyph with MIT License 6 votes vote down vote up
private void showNotification()
{
	if (service.get() == null)
		return;

	Service s = service.get();

	builder.setTicker(s.getString(R.string.uploading_image_of, total - images.size(), total));
	builder.setContentText(s.getString(R.string.uploading_image_of, total - images.size(), total));
	builder.setProgress(100, 0, true);

	final NotificationManager mNotificationManager = (NotificationManager) s
			.getSystemService(Context.NOTIFICATION_SERVICE);

	mNotificationManager.notify(AttrUtil.getString(s, R.string.app_name), notificationId, builder.build());
}
 
Example #7
Source File: Secy.java    From JIMU with Apache License 2.0 6 votes vote down vote up
@NonNull
private synchronized MessageBridgeAttacher createAttacher(String processName) {
    if (TextUtils.isEmpty(processName)) {
        ILogger.logger.error(ILogger.defaultTag, "cannot execute for a empty process name");
        throw new IllegalArgumentException("processName cannot be empty");
    }
    Class<? extends Service> bridgeServiceClz = null;
    if (processMsgBridgeServiceMapper.containsKey(processName))
        bridgeServiceClz = processMsgBridgeServiceMapper.get(processName);
    else {
        String errorMsg = "cannot find target bridge service for" + processName + " are you missing decline it?";
        ILogger.logger.error(ILogger.defaultTag, errorMsg);
        throw new RuntimeException(errorMsg);
    }

    MessageBridgeAttacher attacher = new MessageBridgeAttacher(processName, bridgeServiceClz, application);

    return attacher;
}
 
Example #8
Source File: GrblBluetoothSerialService.java    From grblcontroller with GNU General Public License v3.0 6 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    this.start();

    if(intent != null){
        String deviceAddress = intent.getStringExtra(KEY_MAC_ADDRESS);
        if(deviceAddress != null){
            try{
                BluetoothDevice device = mAdapter.getRemoteDevice(deviceAddress.toUpperCase());
                this.connect(device, false);
            }catch(IllegalArgumentException e){
                EventBus.getDefault().post(new UiToastEvent(e.getMessage(), true, true));
                disconnectService();
                stopSelf();
            }
        }
    }else{
        EventBus.getDefault().post(new UiToastEvent(getString(R.string.text_unknown_error), true, true));
        disconnectService();
        stopSelf();
    }

    return Service.START_NOT_STICKY;
}
 
Example #9
Source File: UploadPhotoService.java    From Klyph with MIT License 6 votes vote down vote up
private void showFileNotFoundNotification(String uri)
{
	if (service.get() == null)
		return;

	Service s = service.get();
	
	final int notificationId = (int) System.currentTimeMillis();

	NotificationCompat.Builder builder = new NotificationCompat.Builder(service.get()).setSmallIcon(R.drawable.ic_notification)
			.setTicker(service.get().getString(R.string.upload_error)).setAutoCancel(true)
			.setOnlyAlertOnce(true);
	NotificationUtil.setDummyIntent(service.get(), builder);

	builder.setContentTitle(service.get().getString(R.string.upload_error));
	builder.setContentText(service.get().getString(R.string.file_not_found, uri));

	final NotificationManager mNotificationManager = (NotificationManager) s
			.getSystemService(Context.NOTIFICATION_SERVICE);

	mNotificationManager.notify(AttrUtil.getString(s, R.string.app_name), notificationId, builder.build());
}
 
Example #10
Source File: LocationSharingService.java    From Telegram with GNU General Public License v2.0 6 votes vote down vote up
public int onStartCommand(Intent intent, int flags, int startId) {
    if (getInfos().isEmpty()) {
        stopSelf();
    }
    if (builder == null) {
        Intent intent2 = new Intent(ApplicationLoader.applicationContext, LaunchActivity.class);
        intent2.setAction("org.tmessages.openlocations");
        intent2.addCategory(Intent.CATEGORY_LAUNCHER);
        PendingIntent contentIntent = PendingIntent.getActivity(ApplicationLoader.applicationContext, 0, intent2, 0);

        builder = new NotificationCompat.Builder(ApplicationLoader.applicationContext);
        builder.setWhen(System.currentTimeMillis());
        builder.setSmallIcon(R.drawable.live_loc);
        builder.setContentIntent(contentIntent);
        NotificationsController.checkOtherNotificationsChannel();
        builder.setChannelId(NotificationsController.OTHER_NOTIFICATIONS_CHANNEL);
        builder.setContentTitle(LocaleController.getString("AppName", R.string.AppName));
        Intent stopIntent = new Intent(ApplicationLoader.applicationContext, StopLiveLocationReceiver.class);
        builder.addAction(0, LocaleController.getString("StopLiveLocation", R.string.StopLiveLocation), PendingIntent.getBroadcast(ApplicationLoader.applicationContext, 2, stopIntent, PendingIntent.FLAG_UPDATE_CURRENT));
    }

    updateNotification(false);
    startForeground(6, builder.build());
    return Service.START_NOT_STICKY;
}
 
Example #11
Source File: CaloriesWidget.java    From AmazfitAPKs with Apache License 2.0 6 votes vote down vote up
@Override
public List<SlptViewComponent> buildSlptViewComponent(Service service) {
    SlptLinearLayout caloriesLayout = new SlptLinearLayout();
    SlptPictureView caloriesUnit = new SlptPictureView();
    caloriesUnit.setStringPicture(" kcal");
    caloriesLayout.add(new SlptTodayCaloriesView());
    caloriesLayout.add(caloriesUnit);
    caloriesLayout.setStart(
            (int) service.getResources().getDimension(R.dimen.widget_text_left_slpt),
            (int) service.getResources().getDimension(R.dimen.widget_text_top_slpt)
    );
    Typeface caloriesFont = ResourceManager.getTypeFace(service.getResources(), ResourceManager.Font.BEBAS_NEUE);
    caloriesLayout.setTextAttrForAll(
            service.getResources().getDimension(R.dimen.circles_font_size_slpt),
            -16777216 ,
            caloriesFont
    );
    caloriesLayout.alignX = 2;
    caloriesLayout.alignY = 0;
    caloriesLayout.setRect(60,60);

    return Collections.<SlptViewComponent>singletonList(caloriesLayout);
}
 
Example #12
Source File: ShadowsocksNotification.java    From Maying with Apache License 2.0 6 votes vote down vote up
public ShadowsocksNotification(Service service, String profileName, boolean visible) {
    this.service = service;
    this.profileName = profileName;
    this.visible = visible;

    keyGuard = (KeyguardManager) service.getSystemService(Context.KEYGUARD_SERVICE);
    nm = (NotificationManager) service.getSystemService(Context.NOTIFICATION_SERVICE);
    pm = (PowerManager) service.getSystemService(Context.POWER_SERVICE);

    // init notification builder
    initNotificationBuilder();
    style = new NotificationCompat.BigTextStyle(builder);

    // init with update action
    initWithUpdateAction();

    // register lock receiver
    registerLockReceiver(service, visible);
}
 
Example #13
Source File: AlarmSyncService.java    From aptoide-client-v8 with GNU General Public License v3.0 6 votes vote down vote up
@Override public int onStartCommand(Intent intent, int flags, int startId) {
  if (intent != null && AlarmSyncScheduler.ACTION_SYNC.equals(intent.getAction())) {

    final String syncId = intent.getData()
        .getFragment();

    final Sync sync = storage.get(syncId);
    final boolean reschedule = intent.getBooleanExtra(AlarmSyncScheduler.EXTRA_RESCHEDULE, false);

    if (sync != null) {
      sync.execute()
          .doOnTerminate(() -> {
            if (reschedule) {
              scheduler.reschedule(sync);
            }
            stopSelf(startId);
          })
          .subscribe(() -> {
          }, throwable -> crashReport.log(throwable));
    } else {
      scheduler.cancel(syncId);
    }
  }
  return Service.START_REDELIVER_INTENT;
}
 
Example #14
Source File: SdlRouterService.java    From sdl_java_suite with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
private void exitForeground(){
	synchronized (NOTIFICATION_LOCK) {
		if (isForeground && !isPrimaryTransportConnected()) {	//Ensure that the service is in the foreground and no longer connected to a transport
			DebugTool.logInfo("SdlRouterService to exit foreground");
			if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
				this.stopForeground(Service.STOP_FOREGROUND_DETACH);
			}else{
				stopForeground(false);
			}
			NotificationManager notificationManager = (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
			if (notificationManager!= null){
				try {
					notificationManager.cancelAll();
					if( Build.VERSION.SDK_INT >= Build.VERSION_CODES.O && !getBooleanPref(KEY_AVOID_NOTIFICATION_CHANNEL_DELETE,false)) {
						notificationManager.deleteNotificationChannel(SDL_NOTIFICATION_CHANNEL_ID);
					}
				} catch (Exception e) {
					DebugTool.logError("Issue when removing notification and channel", e);
				}
			}
			isForeground = false;
		}
	}
}
 
Example #15
Source File: PhoneUtils.java    From Common with Apache License 2.0 5 votes vote down vote up
/**
 * Return the IMSI.
 * <p>Must hold {@code <uses-permission android:name="android.permission.READ_PHONE_STATE" />}</p>
 *
 * @return the IMSI
 */
@SuppressLint("HardwareIds")
@RequiresPermission(READ_PHONE_STATE)
public static String getIMSI(@NonNull Context context) {
    TelephonyManager tm = (TelephonyManager) context.getSystemService(Service.TELEPHONY_SERVICE);
    return tm.getSubscriberId();
}
 
Example #16
Source File: VibrateHelper.java    From KUAS-AP-Material with MIT License 5 votes vote down vote up
public static void setCourseAlarm(Context context, String time, int dayOfWeek, int id,
                                  boolean isVibrate) {
	if (!time.contains(":")) {
		return;
	}

	Intent intent = new Intent(context, CourseVibrateAlarmService.class);

	Bundle bundle = new Bundle();
	bundle.putBoolean("mode", isVibrate);
	intent.putExtras(bundle);

	Calendar calendar = Calendar.getInstance();
	calendar.set(Calendar.DAY_OF_WEEK, dayOfWeek);
	calendar.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time.split(":")[0]));
	calendar.set(Calendar.MINUTE, Integer.parseInt(time.split(":")[1]));
	calendar.set(Calendar.SECOND, 0);
	PendingIntent pendingIntent =
			PendingIntent.getService(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
	Date now = new Date(System.currentTimeMillis());
	if (calendar.getTime().before(now)) {
		calendar.add(Calendar.DAY_OF_MONTH, 7);
	}

	AlarmManager alarm = (AlarmManager) context.getSystemService(Service.ALARM_SERVICE);
	alarm.cancel(pendingIntent);
	alarm.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
			AlarmManager.INTERVAL_DAY * 7, pendingIntent);
}
 
Example #17
Source File: ServcesManager.java    From DroidPlugin with GNU Lesser General Public License v3.0 5 votes vote down vote up
public int onStart(Context context, Intent intent, int flags, int startId) throws Exception {
    Intent targetIntent = intent.getParcelableExtra(Env.EXTRA_TARGET_INTENT);
    if (targetIntent != null) {
        ServiceInfo targetInfo = PluginManager.getInstance().resolveServiceInfo(targetIntent, 0);
        if (targetInfo != null) {
            Service service = mNameService.get(targetInfo.name);
            if (service == null) {

                handleCreateServiceOne(context, intent, targetInfo);
            }
            handleOnStartOne(targetIntent, flags, startId);
        }
    }
    return -1;
}
 
Example #18
Source File: ZxtMediaPlayer.java    From DroidDLNA with GNU General Public License v3.0 5 votes vote down vote up
public double getVolume() {
    AudioManager audioManager = (AudioManager) mContext.getSystemService(Service.AUDIO_SERVICE);
    double v =  (double)audioManager.getStreamVolume(AudioManager.STREAM_MUSIC)
            / audioManager.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
    Log.i(TAG, "getVolume " + v);
    return v;
}
 
Example #19
Source File: MoonPhaseWidget.java    From GreatFit with MIT License 5 votes vote down vote up
public List<SlptViewComponent> buildSlptViewComponent(Service service, boolean better_resolution) {
    better_resolution = better_resolution && settings.better_resolution_when_raising_hand;

    List<SlptViewComponent> slpt_objects = new ArrayList<>();

    // Do not show in SLPT (but show on raise of hand)
    boolean show_all = (!settings.clock_only_slpt || better_resolution);
    if (!show_all)
        return slpt_objects;

    this.mService = service;

    try  {
        // Get moon data
        int i = mf.getPhaseIndex();
        String filename = (better_resolution) ? String.format("26wc_moon/moon%d.png", i) : String.format("slpt_moon/" + settings.is_white_bg + "moon%d.png", i);

        SlptPictureView moonphaseIcon = new SlptPictureView();
        moonphaseIcon.setImagePicture(SimpleFile.readFileFromAssets(service, filename));
        moonphaseIcon.setStart(
                (int) settings.moonphaseIconLeft,
                (int) settings.moonphaseIconTop
        );
        slpt_objects.add(moonphaseIcon);

    } catch (Exception ex) {
        //Log.e(TAG,ex.toString());
    }

    return slpt_objects;
}
 
Example #20
Source File: ManifestValidator.java    From pusher-websocket-android with MIT License 5 votes vote down vote up
private void checkServicesInManifest(ArrayList<Class<? extends Service>> list, Context context) throws InvalidManifestException {
    for (Class<? extends Service> service : list) {
        if (!isInManifest(context, service)) {

        }
    }
}
 
Example #21
Source File: UpdateService.java    From Ency with Apache License 2.0 5 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    downloadUrl = intent.getStringExtra("downloadurl");
    startDownload();
    // 注册广播接收者,监听下载状态
    registerReceiver(receiver, new IntentFilter(DownloadManager.ACTION_DOWNLOAD_COMPLETE));
    return Service.START_STICKY;
}
 
Example #22
Source File: EditTextShakeHelper.java    From JianDan_OkHttpWithVolley with Apache License 2.0 5 votes vote down vote up
public EditTextShakeHelper(Context context) {

        // 初始化振动器
        shakeVibrator = (Vibrator) context
                .getSystemService(Service.VIBRATOR_SERVICE);
        // 初始化震动动画
        shakeAnimation = new TranslateAnimation(0, 10, 0, 0);
        shakeAnimation.setDuration(300);
        cycleInterpolator = new CycleInterpolator(8);
        shakeAnimation.setInterpolator(cycleInterpolator);

    }
 
Example #23
Source File: VideoEncodingService.java    From TelePlus-Android with GNU General Public License v2.0 5 votes vote down vote up
public int onStartCommand(Intent intent, int flags, int startId) {
    path = intent.getStringExtra("path");
    int oldAccount = currentAccount;
    currentAccount = intent.getIntExtra("currentAccount", UserConfig.selectedAccount);
    if (oldAccount != currentAccount) {
        NotificationCenter.getInstance(oldAccount).removeObserver(this, NotificationCenter.FileUploadProgressChanged);
        NotificationCenter.getInstance(currentAccount).addObserver(this, NotificationCenter.FileUploadProgressChanged);
    }
    boolean isGif = intent.getBooleanExtra("gif", false);
    if (path == null) {
        stopSelf();
        return Service.START_NOT_STICKY;
    }
    if (BuildVars.LOGS_ENABLED) {
        FileLog.d("start video service");
    }
    if (builder == null) {
        NotificationsController.checkOtherNotificationsChannel();
        builder = new NotificationCompat.Builder(ApplicationLoader.applicationContext);
        builder.setSmallIcon(android.R.drawable.stat_sys_upload);
        builder.setWhen(System.currentTimeMillis());
        builder.setChannelId(NotificationsController.OTHER_NOTIFICATIONS_CHANNEL);
        builder.setContentTitle(LocaleController.getString("AppName", R.string.AppName));
        if (isGif) {
            builder.setTicker(LocaleController.getString("SendingGif", R.string.SendingGif));
            builder.setContentText(LocaleController.getString("SendingGif", R.string.SendingGif));
        } else {
            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;
}
 
Example #24
Source File: ShadowsocksNotification.java    From Maying with Apache License 2.0 5 votes vote down vote up
private void registerLockReceiver(Service service, boolean visible) {
    IntentFilter screenFilter = new IntentFilter();
    screenFilter.addAction(Intent.ACTION_SCREEN_ON);
    screenFilter.addAction(Intent.ACTION_SCREEN_OFF);
    if (visible && Utils.isLollipopOrAbove()) {
        screenFilter.addAction(Intent.ACTION_USER_PRESENT);
    }
    service.registerReceiver(lockReceiver, screenFilter);
}
 
Example #25
Source File: DownloadManager.java    From QuranAndroid with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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);
        }

    }

}
 
Example #26
Source File: MobileCommProcessor.java    From AssistantBySDK with Apache License 2.0 5 votes vote down vote up
public MobileCommProcessor(Context mContext, SystemVoiceMediator mediator, Handler handler) {
    super(mContext, mediator);
    this.mHandler = handler;
    mAppConfig = (AppConfig) ((Service) mContext).getApplication();
    tPools = new ThreadPoolExecutor(10, 20, 10, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
    phoneCallListener();
    // 注册收件箱内容观察者
    mContext.getContentResolver().registerContentObserver(Uri.parse(PhoneContactUtils.SMS_URI_INBOX),
            true, new SmsObserver(handler));
    // 注册联系人内容观察者
    mContext.getContentResolver().registerContentObserver(ContactsContract.Contacts.CONTENT_URI,
            true, new ContactObserver(handler));
}
 
Example #27
Source File: DebugOverlayService.java    From DebugOverlay-Android with Apache License 2.0 5 votes vote down vote up
@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;
}
 
Example #28
Source File: NotificationService.java    From Klyph with MIT License 5 votes vote down vote up
@Override
public void onCreate()
{
	// Why initialize device values ?
	// Because we need the density to calculate image size
	// In notification request
	KlyphDevice.initDeviceValues(this);
	
	HandlerThread thread = new HandlerThread("ServiceStartArguments", android.os.Process.THREAD_PRIORITY_BACKGROUND);
	thread.start();

	mServiceLooper = thread.getLooper();
	mServiceHandler = new ServiceHandler(mServiceLooper, new WeakReference<Service>(this));
}
 
Example #29
Source File: DownloadManager.java    From QuranAndroid with GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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+" ("+(int)(( values[0] / 1000000*100)/(values[1] / 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.TYPE , downloadType);
            i.putExtra(AppConstants.Download.DOWNLOAD, AppConstants.Download.IN_DOWNLOAD);
            LocalBroadcastManager.getInstance(context).sendBroadcast(i);
        }

    }

}
 
Example #30
Source File: IncomingMessageObserver.java    From mollyim-android with GNU General Public License v3.0 5 votes vote down vote up
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
  super.onStartCommand(intent, flags, startId);

  NotificationCompat.Builder builder = new NotificationCompat.Builder(getApplicationContext(), NotificationChannels.OTHER);
  builder.setContentTitle(getApplicationContext().getString(R.string.app_name));
  builder.setContentText(getApplicationContext().getString(R.string.MessageRetrievalService_background_connection_enabled));
  builder.setPriority(NotificationCompat.PRIORITY_MIN);
  builder.setWhen(0);
  builder.setSmallIcon(R.drawable.ic_signal_background_connection);
  startForeground(FOREGROUND_ID, builder.build());

  return Service.START_STICKY;
}