下面列出了怎么用android.app.Service的API类实例代码及写法,或者点击链接到github查看源代码。
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());
}
@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;
}
@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;
}
@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);
}
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;
}
}
}
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();
}
@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;
}
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);
}
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;
}
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());
}
@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);
}
@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;
}
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);
}
}
@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);
}
}
@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;
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (context instanceof Service)
((Service) context).stopService(new Intent(context, DownloadService.class));
Intent zipedFiles = new Intent(AppConstants.Download.INTENT);
zipedFiles.putExtra(AppConstants.Download.DOWNLOAD, AppConstants.Download.UNZIP);
LocalBroadcastManager.getInstance(context).sendBroadcast(zipedFiles);
}
public static void cancelCourseAlarm(Context context, String room, String title, String time,
int id) {
Intent intent = new Intent(context, CourseAlarmService.class);
Bundle bundle = new Bundle();
bundle.putString("room", room);
bundle.putString("title", title);
bundle.putString("time", time);
intent.putExtras(bundle);
PendingIntent pendingIntent =
PendingIntent.getService(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarm = (AlarmManager) context.getSystemService(Service.ALARM_SERVICE);
alarm.cancel(pendingIntent);
}
@Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
if (context instanceof Service)
((Service) context).stopService(new Intent(context, DownloadTafseerService.class));
Intent zipedFiles = new Intent(AppConstants.Download.INTENT);
zipedFiles.putExtra(AppConstants.Download.DOWNLOAD, AppConstants.Download.UNZIP);
zipedFiles.putExtra(AppConstants.Download.TYPE , downloadType);
LocalBroadcastManager.getInstance(context).sendBroadcast(zipedFiles);
}
private ITestRemoteLockRpc bindTestingRpc(Class<? extends Service> serviceClass)
throws TimeoutException {
ITestRemoteLockRpc rpc =
ITestRemoteLockRpc.Stub.asInterface(
rule.bindService(new Intent(InstrumentationRegistry.getTargetContext(), serviceClass)));
return rpc;
}
public Builder(Context context, Class<? extends Service> serviceClass,
M playlistManager, ImageProvider<I> imageProvider, Listener<I> listener) {
this.context = context;
this.serviceClass = serviceClass;
this.playlistManager = playlistManager;
this.imageProvider = imageProvider;
this.listener = listener;
}
public static void start(Context context)
{
initNotification(context);
if(!isStart)
{
if(context instanceof Service)
((Service)context).startForeground(ANTFOREST_NOTIFICATION_ID, mNotification);
else
getNotificationManager(context).notify(ANTFOREST_NOTIFICATION_ID, mNotification);
isStart = true;
}
}
public MonitorView(Application context) {
mMonitorView = LayoutInflater.from(context).inflate(R.layout.monitor_view, null);
mFrameStatusView = mMonitorView.findViewById(R.id.v_frame);
mFrameValueView = (TextView) mMonitorView.findViewById(R.id.tv_frame);
mCPUStatusView = mMonitorView.findViewById(R.id.v_cpu);
mCPUValueView = (TextView) mMonitorView.findViewById(R.id.tv_cpu);
mMemStatusView = mMonitorView.findViewById(R.id.v_mem);
mMemValueView = (TextView) mMonitorView.findViewById(R.id.tv_mem);
mNetStatusView = mMonitorView.findViewById(R.id.v_net);
mNetValueView = (TextView) mMonitorView.findViewById(R.id.tv_net);
mNetTotalView = (TextView) mMonitorView.findViewById(R.id.tv_net_total);
// grab window manager and add view to the window
windowManager = (WindowManager) mMonitorView.getContext().getSystemService(Service.WINDOW_SERVICE);
addViewToWindow();
}
/**
* 启动某个插件Service; 如果Service还没有启动, 那么会创建新的插件Service
*
* @param proxyIntent proxyIntent
* @param startId startId
*/
@SuppressWarnings("deprecation")
void onStart(Intent proxyIntent, int startId) {
Intent targetIntent = proxyIntent.getParcelableExtra(HookAMSForServicePlugin.EXTRA_TARGET_INTENT);
if (targetIntent == null) throw new NullPointerException("targetIntent==null");
ServiceInfo serviceInfo = selectPluginService(targetIntent);
if (serviceInfo == null) {
Log.w(TAG, "can not found service : " + targetIntent.getComponent());
return;
}
try {
String processName0 = ProcessUtil.getProcessNameViaManager(MApplication.getInstance());
Log.d(TAG, "0processName:" + processName0);
Log.d(TAG, "0mServiceMap.size:" + mServiceMap.size());
Log.d(TAG, "0mServiceMap.containsKey(serviceInfo.name):" + serviceInfo.name);
if (!mServiceMap.containsKey(serviceInfo.name)) {
// service还不存在, 先创建
proxyCreateService(serviceInfo);
}
Service service = mServiceMap.get(serviceInfo.name);
if (service == null) throw new NullPointerException("service==null");
service.onStart(targetIntent, startId);
String processName2 = ProcessUtil.getProcessNameViaManager(MApplication.getInstance());
Log.d(TAG, "2processName:" + processName2);
Log.d(TAG, "2mServiceMap.size:" + mServiceMap.size());
Log.d(TAG, "2mServiceMap.get(serviceInfo.name):" + serviceInfo.name);
} catch (Throwable e) {
Log.e(TAG, "Throwable:" + e.getMessage());
e.printStackTrace();
}
}
/**
* 停止某个插件Service, 当全部的插件Service都停止之后, ProxyService也会停止
*
* @param targetIntent targetIntent
* @return int
*/
public int stopService(Intent targetIntent) {
ServiceInfo serviceInfo = selectPluginService(targetIntent);
if (serviceInfo == null) {
Log.w(TAG, "can not found service: " + targetIntent.getComponent());
return 0;
}
String processName3 = ProcessUtil.getProcessNameViaManager(MApplication.getInstance());
Log.d(TAG, "3processName:" + processName3);
Log.d(TAG, "3mServiceMap.size:" + mServiceMap.size());
Log.d(TAG, "3mServiceMap.get(serviceInfo.name):" + serviceInfo.name);
Service service = mServiceMap.get(serviceInfo.name);
if (service == null) {
Log.w(TAG, "can not runnning, are you stopped it multi-times?");
return 0;
}
service.onDestroy();
mServiceMap.remove(serviceInfo.name);
if (mServiceMap.isEmpty()) {
// 没有Service了, 这个没有必要存在了
Log.d(TAG, "service all stopped, stop proxy");
Context appContext = MApplication.getInstance();
appContext.stopService(new Intent().setComponent(new ComponentName(appContext.getPackageName(), PluginProxyService.class.getName())));
}
return 1;
}
private void set(Service service, String name) {
PaLog.d("attach " + name);
Object obj = RefInvoker.getFieldObject(this, Service.class.getName(), name);
if (obj != null) {
RefInvoker.setFieldObject(service, Service.class.getName(), name, obj);
}
}
@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));
}
private static ArrayList<String> extractTextFromNotification(Service service, RemoteViews view) {
LayoutInflater inflater = (LayoutInflater) service.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ArrayList<String> result = new ArrayList<String>();
if (view == null) {
Log.d(TAG, "View is empty");
return null;
}
try {
int layoutid = view.getLayoutId();
ViewGroup localView = (ViewGroup) inflater.inflate(layoutid, null);
view.reapply(service.getApplicationContext(), localView);
ArrayList<View> outViews = new ArrayList<View>();
extractViewType(outViews, TextView.class, localView);
for (View ttv: outViews) {
TextView tv = (TextView) ttv;
String txt = tv.getText().toString();
if (!TextUtils.isEmpty(txt) && tv.getId() != TIMESTAMPID) {
result.add(txt);
}
}
} catch (Exception e) {
Log.d(TAG, "FAILED to load notification " + e.toString());
Log.wtf(TAG, e);
return null;
//notification might have dissapeared by now
}
Log.d(TAG, "Return result" + result);
return result;
}
public static void cancelBusAlarm(Context context, String endStation, String time, int id) {
Intent intent = new Intent(context, BusAlarmService.class);
Bundle bundle = new Bundle();
bundle.putString("endStation", endStation);
bundle.putString("Time", time);
intent.putExtras(bundle);
PendingIntent pendingIntent =
PendingIntent.getService(context, id, intent, PendingIntent.FLAG_UPDATE_CURRENT);
AlarmManager alarm = (AlarmManager) context.getSystemService(Service.ALARM_SERVICE);
alarm.cancel(pendingIntent);
}
@Override public int onStartCommand(Intent intent, int flags, final int startId) {
rxGpsPresenter.attachView(this);
notificationFactory = new NotificationFactory(this, listener);
startForeground(notificationFactory.getNotificationIdServiceStarted(),
notificationFactory.getNotificationServiceStarted(0, 0));
listener.onServiceAlreadyStarted();
return Service.START_NOT_STICKY;
}
@Override
protected void onStart() {
super.onStart();
EventBus.getDefault().register(this);
// 绑定到后台服务
Intent clientServiceIntent = new Intent(this, ClientService.class);
bindService(clientServiceIntent, conn, Service.BIND_AUTO_CREATE);
// 请求二维码权限
requestCodeQRCodePermissions();
}