Java Code Examples for android.app.Service
The following code examples are extracted from open source projects. You can click to
vote up the examples that are useful to you.
Example 1
From project android_aosp_packages_apps_Settings, under directory /src/com/android/settings/.
Source file: AccessibilitySettings.java

/** * Adds {@link CheckBoxPreference} for enabling or disabling an accessibility services. */ private void addAccessibilitServicePreferences(){ AccessibilityManager accessibilityManager=(AccessibilityManager)getSystemService(Service.ACCESSIBILITY_SERVICE); List<ServiceInfo> installedServices=accessibilityManager.getAccessibilityServiceList(); mAccessibilityServicesCategory=(PreferenceGroup)findPreference(ACCESSIBILITY_SERVICES_CATEGORY); if (installedServices.isEmpty()) { getPreferenceScreen().removePreference(mAccessibilityServicesCategory); mAccessibilityServicesCategory=null; return; } for (int i=0, count=installedServices.size(); i < count; ++i) { ServiceInfo serviceInfo=installedServices.get(i); String key=serviceInfo.packageName + "/" + serviceInfo.name; mAccessibilityServices.put(key,serviceInfo); CheckBoxPreference preference=new CheckBoxPreference(this); preference.setKey(key); preference.setTitle(serviceInfo.loadLabel(getPackageManager())); mAccessibilityServicesCategory.addPreference(preference); } }
Example 2
From project Android-Terminal-Emulator, under directory /src/jackpal/androidterm/compat/.
Source file: ServiceForegroundCompat.java

public ServiceForegroundCompat(Service service){ this.service=service; mNM=(NotificationManager)service.getSystemService(Context.NOTIFICATION_SERVICE); Class<?> clazz=service.getClass(); try { mStartForeground=clazz.getMethod("startForeground",mStartForegroundSig); mStopForeground=clazz.getMethod("stopForeground",mStopForegroundSig); } catch ( NoSuchMethodException e) { mStartForeground=mStopForeground=null; } try { mSetForeground=clazz.getMethod("setForeground",mSetForegroundSig); } catch ( NoSuchMethodException e) { mSetForeground=null; } if (mStartForeground == null && mSetForeground == null) { throw new IllegalStateException("Neither startForeground() or setForeground() present!"); } }
Example 3
From project AndroidBillingLibrary, under directory /AndroidBillingLibrary/src/net/robotmedia/billing/utils/.
Source file: Compatibility.java

private static void initCompatibility(){ try { final Field field=Service.class.getField("START_NOT_STICKY"); START_NOT_STICKY=field.getInt(null); } catch ( Exception e) { START_NOT_STICKY=2; } try { startIntentSender=Activity.class.getMethod("startIntentSender",START_INTENT_SENDER_SIG); } catch ( SecurityException e) { startIntentSender=null; } catch ( NoSuchMethodException e) { startIntentSender=null; } }
Example 4
From project AnySoftKeyboard, under directory /src/com/anysoftkeyboard/ui/.
Source file: MySeekBarPreference.java

@Override protected View onCreateView(ViewGroup parent){ LayoutInflater inflator=(LayoutInflater)mContext.getSystemService(Service.LAYOUT_INFLATER_SERVICE); ViewGroup mySeekBarLayout=(ViewGroup)inflator.inflate(R.layout.my_seek_bar_pref,null); mSeekBar=(SeekBar)mySeekBarLayout.findViewById(R.id.pref_seekbar); if (shouldPersist()) mValue=getPersistedInt(mDefault); mCurrentValue=(TextView)mySeekBarLayout.findViewById(R.id.pref_current_value); mMaxValue=(TextView)mySeekBarLayout.findViewById(R.id.pref_max_value); mMinValue=(TextView)mySeekBarLayout.findViewById(R.id.pref_min_value); mCurrentValue.setText(Integer.toString(mValue)); ((TextView)mySeekBarLayout.findViewById(R.id.pref_title)).setText(mTitle); writeBoundaries(); mSeekBar.setMax(mMax - mMin); mSeekBar.setProgress(mValue - mMin); mSeekBar.setOnSeekBarChangeListener(this); return mySeekBarLayout; }
Example 5
From project BF3-Battlelog, under directory /src/com/ninetwozero/battlelog/service/.
Source file: BattlelogService.java

@Override public int onStartCommand(Intent intent,int flags,int startId){ Log.d(Constants.DEBUG_TAG,"Service has reached onStartCommand()"); if (PublicUtils.isNetworkAvailable(this)) { new AsyncServiceTask(this,mSharedPreferences).execute(); } return Service.START_STICKY; }
Example 6
From project creamed_glacier_app_settings, under directory /src/com/android/settings/bluetooth/.
Source file: DockEventReceiver.java

/** * Called back by the service when it has finished processing notifications, releasing the wake lock if the service is now stopping. */ public static void finishStartingService(Service service,int startId){ synchronized (sStartingServiceSync) { if (sStartingService != null) { if (DEBUG) Log.d(TAG,"stopSelf id = " + startId); if (service.stopSelfResult(startId)) { Log.d(TAG,"finishStartingService: stopping service"); sStartingService.release(); } } } }
Example 7
From project danbooru-gallery-android, under directory /src/tw/idv/palatis/danboorugallery/utils/.
Source file: BitmapMemCache.java

private BitmapMemCache(Context context){ ActivityManager manager=(ActivityManager)context.getSystemService(Service.ACTIVITY_SERVICE); int cache_size=manager.getMemoryClass() * 8; D.Log.d("Using %d for cache size",cache_size); cache=Collections.synchronizedMap(new LruCache<String,Bitmap>(cache_size)); }
Example 8
From project droidparts, under directory /base/src/org/droidparts/inject/injector/.
Source file: InjectorDelegate.java

protected Bundle getIntentExtras(Object obj){ Bundle data=null; if (obj instanceof Activity) { data=((Activity)obj).getIntent().getExtras(); } else if (obj instanceof Service) { } return data; }
Example 9
/** * Glue to bind to this service * @param context the client's context * @param client who to notify */ public static void bindTo(Context context,ServiceConnection client){ context=context.getApplicationContext(); Republisher conns=clients.get(context); if (conns == null) { conns=new Republisher(); conns.add(client); clients.put(context,conns); context.bindService(new Intent(context,GPSClient.class),conns,Service.BIND_AUTO_CREATE | Service.BIND_DEBUG_UNBIND); } else conns.add(client); }
Example 10
From project Gibberbot, under directory /src/info/guardianproject/otr/app/im/service/.
Source file: ForegroundStarter.java

public void init(){ mNM=(NotificationManager)mService.getSystemService(Service.NOTIFICATION_SERVICE); try { mStartForeground=mService.getClass().getMethod("startForeground",mStartForegroundSignature); mStopForeground=mService.getClass().getMethod("stopForeground",mStopForegroundSignature); return; } catch ( NoSuchMethodException e) { mStartForeground=mStopForeground=null; } try { mSetForeground=mService.getClass().getMethod("setForeground",mSetForegroundSignature); } catch ( NoSuchMethodException e) { throw new IllegalStateException("OS doesn't have Service.startForeground OR Service.setForeground!"); } }
Example 11
From project HapiPodcastJ, under directory /src/info/xuluan/podcast/.
Source file: AllItemActivity.java

public void getPref(){ SharedPreferences pref=getSharedPreferences(Pref.HAPI_PREFS_FILE_NAME,Service.MODE_PRIVATE); pref_order=pref.getLong("pref_order",2); pref_where=pref.getLong("pref_where",0); pref_select=pref.getLong("pref_select",0); }
Example 12
From project lastfm-android, under directory /app/src/fm/last/android/player/.
Source file: RadioPlayerService.java

private void clearNotification(){ try { Class types[]={boolean.class}; Object args[]={true}; Method method=Service.class.getMethod("stopForeground",types); method.invoke(this,args); } catch ( NoSuchMethodException e) { nm.cancel(NOTIFY_ID); setForeground(false); } catch ( Exception e) { } if (currentStation != null && mStationStartTime > 0) { LastFMApplication.getInstance().tracker.trackEvent("Radio","Stream",currentStation.getType(),(int)((System.currentTimeMillis() - mStationStartTime) / 1000)); mStationStartTime=0; } }
Example 13
From project maven-android-plugin-samples, under directory /apidemos-android-10/application/src/main/java/com/example/android/apis/app/.
Source file: ServiceStartArguments.java

@Override public void handleMessage(Message msg){ Bundle arguments=(Bundle)msg.obj; String txt=arguments.getString("name"); Log.i("ServiceStartArguments","Message: " + msg + ", "+ arguments.getString("name")); if ((msg.arg2 & Service.START_FLAG_REDELIVERY) == 0) { txt="New cmd #" + msg.arg1 + ": "+ txt; } else { txt="Re-delivered #" + msg.arg1 + ": "+ txt; } showNotification(txt); long endTime=System.currentTimeMillis() + 5 * 1000; while (System.currentTimeMillis() < endTime) { synchronized (this) { try { wait(endTime - System.currentTimeMillis()); } catch ( Exception e) { } } } hideNotification(); Log.i("ServiceStartArguments","Done with #" + msg.arg1); stopSelf(msg.arg1); }
Example 14
From project MIT-Mobile-for-Android, under directory /src/edu/mit/mitmobile2/alerts/.
Source file: NotificationService.java

/** */ protected void rescheduleShuttleAlarm(String title,String stop,String route,long alarmTime){ AlarmManager alarmManager=(AlarmManager)ctx.getSystemService(Service.ALARM_SERVICE); Intent i=new Intent(ctx,NotificationsAlarmReceiver.class); i.putExtra(ShuttleModel.KEY_STOP_TITLE,title); i.putExtra(ShuttleModel.KEY_STOP_ID,stop); i.putExtra(ShuttleModel.KEY_ROUTE_ID,route); i.putExtra(ShuttleModel.KEY_TIME,alarmTime); PendingIntent pendingIntent=PendingIntent.getBroadcast(ctx,0,i,0); alarmManager.set(AlarmManager.RTC_WAKEUP,alarmTime - 4 * 60 * 1000,pendingIntent); }
Example 15
From project OpenAndroidWeather, under directory /OpenAndroidWeather/src/no/firestorm/wsklima/.
Source file: GetWeather.java

private void updateLocation() throws NoLocationException { Location loc=getLastLocation(); if (loc != null && isAccurateEnough(loc)) { mLocation=loc; return; } final LocationManager locMan=(LocationManager)mContext.getSystemService(Service.LOCATION_SERVICE); final Criteria criteria=new Criteria(); criteria.setPowerRequirement(Criteria.POWER_LOW); final String provider=locMan.getBestProvider(criteria,true); if (provider != null) { UpdateLocation getLocation=new UpdateLocation(this,mContext); locMan.requestLocationUpdates(provider,0,0,getLocation,Looper.getMainLooper()); synchronized (this) { try { this.wait(2 * 60 * 1000); } catch ( final InterruptedException e) { getLocation.stop(); loc=getLocation.getLocation(); if (loc == null) { throw new NoLocationException(null); } else { mLocation=loc; } } } } else throw new NoLocationException(null); }
Example 16
From project packages_apps_Calendar, under directory /src/com/android/calendar/alerts/.
Source file: AlertReceiver.java

/** * Called back by the service when it has finished processing notifications, releasing the wake lock if the service is now stopping. */ public static void finishStartingService(Service service,int startId){ synchronized (mStartingServiceSync) { if (mStartingService != null) { if (service.stopSelfResult(startId)) { mStartingService.release(); } } } }
Example 17
From project platform_packages_apps_calendar, under directory /src/com/android/calendar/alerts/.
Source file: AlertReceiver.java

/** * Called back by the service when it has finished processing notifications, releasing the wake lock if the service is now stopping. */ public static void finishStartingService(Service service,int startId){ synchronized (mStartingServiceSync) { if (mStartingService != null) { if (service.stopSelfResult(startId)) { mStartingService.release(); } } } }
Example 18
From project platform_packages_apps_mms, under directory /src/com/android/mms/transaction/.
Source file: SmsReceiver.java

/** * Called back by the service when it has finished processing notifications, releasing the wake lock if the service is now stopping. */ public static void finishStartingService(Service service,int startId){ synchronized (mStartingServiceSync) { if (mStartingService != null) { if (service.stopSelfResult(startId)) { mStartingService.release(); } } } }
Example 19
From project platform_packages_apps_settings, under directory /src/com/android/settings/bluetooth/.
Source file: DockEventReceiver.java

/** * Called back by the service when it has finished processing notifications, releasing the wake lock if the service is now stopping. */ public static void finishStartingService(Service service,int startId){ synchronized (sStartingServiceSync) { if (sStartingService != null) { if (DEBUG) Log.d(TAG,"stopSelf id = " + startId); if (service.stopSelfResult(startId)) { Log.d(TAG,"finishStartingService: stopping service"); sStartingService.release(); } } } }
Example 20
From project roboject, under directory /roboject-tutorial/src/main/java/de/akquinet/android/roboject/tutorial/activities/.
Source file: AdderActivity.java

@Override protected void onCreate(Bundle savedInstanceState){ super.onCreate(savedInstanceState); setContentView(R.layout.adder_layout); number1Input=(EditText)findViewById(R.id.number1Input); number2Input=(EditText)findViewById(R.id.number2Input); addNumbers=(Button)findViewById(R.id.addNumbersButton); resultText=(TextView)findViewById(R.id.addResultText); addNumbers.setOnClickListener(new View.OnClickListener(){ @Override public void onClick( View view){ if (adderService != null) { try { int number1=Integer.parseInt(number1Input.getText().toString()); int number2=Integer.parseInt(number2Input.getText().toString()); resultText.setText("Result is " + adderService.add(number1,number2)); } catch ( NumberFormatException e) { Toast toast=Toast.makeText(getApplicationContext(),"Please enter two integer values",3); toast.show(); } } } } ); Intent intent=new Intent(); intent.setClassName(getApplicationContext(),TestService.class.getName()); getApplicationContext().bindService(intent,new AdderConnection(),Service.BIND_AUTO_CREATE); }
Example 21
From project Sage-Mobile-Calc, under directory /src/org/connectbot/service/.
Source file: ConnectionNotifier.java

public PreEclair(){ try { setForeground=Service.class.getMethod("setForeground",setForegroundSignature); } catch ( Exception e) { } }
Example 22
From project SMSSync, under directory /smssync/src/org/addhen/smssync/services/.
Source file: SmsReceiverService.java

/** * Called back by the service when it has finished processing notifications, releasing the wake lock and wifi lock if the service is now stopping. * @param Service service - The calling service. * @param int startId - The service start id. * @return void */ public static void finishStartingService(Service service,int startId){ synchronized (mStartingServiceSync) { if (mStartingService != null) { if (service.stopSelfResult(startId)) { mStartingService.release(); } } } }
Example 23
From project subsonic, under directory /subsonic-android/src/github/daneren2005/dsub/util/.
Source file: Util.java

private static void startForeground(Service service,int notificationId,Notification notification){ try { Method method=Service.class.getMethod("startForeground",int.class,Notification.class); method.invoke(service,notificationId,notification); Log.i(TAG,"Successfully invoked Service.startForeground()"); } catch ( Throwable x) { NotificationManager notificationManager=(NotificationManager)service.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(Constants.NOTIFICATION_ID_PLAYING,notification); Log.i(TAG,"Service.startForeground() not available. Using work-around."); } }
Example 24
From project Subsonic-Android, under directory /src/net/sourceforge/subsonic/androidapp/util/.
Source file: Util.java

private static void startForeground(Service service,int notificationId,Notification notification){ try { Method method=Service.class.getMethod("startForeground",int.class,Notification.class); method.invoke(service,notificationId,notification); Log.i(TAG,"Successfully invoked Service.startForeground()"); } catch ( Throwable x) { NotificationManager notificationManager=(NotificationManager)service.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(Constants.NOTIFICATION_ID_PLAYING,notification); Log.i(TAG,"Service.startForeground() not available. Using work-around."); } }
Example 25
From project subsonic_1, under directory /subsonic-android/src/net/sourceforge/subsonic/androidapp/util/.
Source file: Util.java

private static void startForeground(Service service,int notificationId,Notification notification){ try { Method method=Service.class.getMethod("startForeground",int.class,Notification.class); method.invoke(service,notificationId,notification); Log.i(TAG,"Successfully invoked Service.startForeground()"); } catch ( Throwable x) { NotificationManager notificationManager=(NotificationManager)service.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(Constants.NOTIFICATION_ID_PLAYING,notification); Log.i(TAG,"Service.startForeground() not available. Using work-around."); } }
Example 26
From project subsonic_2, under directory /subsonic-android/src/net/sourceforge/subsonic/androidapp/util/.
Source file: Util.java

private static void startForeground(Service service,int notificationId,Notification notification){ try { Method method=Service.class.getMethod("startForeground",int.class,Notification.class); method.invoke(service,notificationId,notification); Log.i(TAG,"Successfully invoked Service.startForeground()"); } catch ( Throwable x) { NotificationManager notificationManager=(NotificationManager)service.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(Constants.NOTIFICATION_ID_PLAYING,notification); Log.i(TAG,"Service.startForeground() not available. Using work-around."); } }
Example 27
From project Supersonic, under directory /subsonic-android/src/net/sourceforge/subsonic/androidapp/util/.
Source file: Util.java

private static void startForeground(Service service,int notificationId,Notification notification){ try { Method method=Service.class.getMethod("startForeground",int.class,Notification.class); method.invoke(service,notificationId,notification); Log.i(TAG,"Successfully invoked Service.startForeground()"); } catch ( Throwable x) { NotificationManager notificationManager=(NotificationManager)service.getSystemService(Context.NOTIFICATION_SERVICE); notificationManager.notify(Constants.NOTIFICATION_ID_PLAYING,notification); Log.i(TAG,"Service.startForeground() not available. Using work-around."); } }
Example 28
From project TeclaAccess, under directory /source/src/ca/idi/tekla/sep/.
Source file: SwitchEventProvider.java

@Override public int onStartCommand(Intent intent,int flags,int startId){ String shieldAddress=null; boolean success=false; if (!mServiceStarted) { if (intent.hasExtra(SepManager.EXTRA_SHIELD_ADDRESS)) { shieldAddress=intent.getExtras().getString(SepManager.EXTRA_SHIELD_ADDRESS); } if (!BluetoothAdapter.checkBluetoothAddress(shieldAddress)) { shieldAddress=TeclaApp.persistence.getShieldAddress(); } if (shieldAddress != null) { success=true; TeclaApp.persistence.setShieldAddress(shieldAddress); startMainThread(); } else { TeclaApp.persistence.setConnectToShield(false); Log.e(TeclaApp.TAG,CLASS_TAG + "Could not connect to shield"); } if (success) { Log.d(TeclaApp.TAG,CLASS_TAG + "Successfully started service"); mServiceStarted=true; } else { Log.d(TeclaApp.TAG,CLASS_TAG + "Failed to start service"); } } else { Log.w(TeclaApp.TAG,CLASS_TAG + "SEP already started, ignored start command."); success=true; } return success ? Service.START_STICKY : Service.START_NOT_STICKY; }
Example 29
From project tinfoil-sms, under directory /branches/prephase3/src/com/tinfoil/sms/.
Source file: MessageService.java

@Override public int onStartCommand(Intent intent,int flags,int startId){ if (contentTitle != null && contentText != null && Prephase3Activity.sharedPrefs.getBoolean("notification_bar",true)) { Intent notifyIntent=null; PendingIntent in=null; Notification notifyDetails=null; String address=contentTitle.toString(); if (dba.getUnreadMessageCount() > 1) { contentTitle=dba.getRow(address).getName(); notifyDetails=new Notification(R.drawable.ic_launcher,contentTitle + ": " + contentText,System.currentTimeMillis()); contentTitle="New Messages"; contentText=dba.getUnreadMessageCount() + " unread messages"; notifyIntent=new Intent(getApplicationContext(),Prephase3Activity.class); notifyIntent.putExtra(multipleNotificationIntent,true); in=PendingIntent.getActivity(this,0,notifyIntent,android.content.Intent.FLAG_ACTIVITY_NEW_TASK); } else { contentTitle=dba.getRow(address).getName(); notifyDetails=new Notification(R.drawable.ic_launcher,contentTitle + ": " + contentText,System.currentTimeMillis()); if (MessageReceiver.myActivityStarted) { notifyIntent=new Intent(getApplicationContext(),MessageView.class); notifyIntent.putExtra(notificationIntent,address); in=PendingIntent.getActivity(this,0,notifyIntent,android.content.Intent.FLAG_ACTIVITY_NEW_TASK); } else { notifyIntent=new Intent(getApplicationContext(),Prephase3Activity.class); notifyIntent.putExtra(notificationIntent,address); in=PendingIntent.getActivity(this,0,notifyIntent,android.content.Intent.FLAG_ACTIVITY_NEW_TASK); } notifyIntent.putExtra(multipleNotificationIntent,false); } notifyDetails.setLatestEventInfo(this,contentTitle,contentText,in); mNotificationManager.notify(INDEX,notifyDetails); } if (MessageReceiver.myActivityStarted) { MessageService.mNotificationManager.cancelAll(); } stopSelf(); return Service.START_NOT_STICKY; }