2011.07.12——— android Foreground service
foreground service ,即在前台显示service,就是在状态栏显示service,借助于notification.
效果如图所示:
1、service
package com.example.android.apis.app;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
// Need the following import to get access to the app resources, since this
// class is in a sub-package.
import com.example.android.apis.R;
public class LocalService extends Service {
private NotificationManager mNM;
/**
* Class for clients to access. Because we know this service always
* runs in the same process as its clients, we don't need to deal with
* IPC.
*/
public class LocalBinder extends Binder {
LocalService getService() {
return LocalService.this;
}
}
@Override
public void onCreate() {
mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
// Display a notification about us starting. We put an icon in the status bar.
showNotification();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.i("LocalService", "Received start id " + startId + ": " + intent);
// We want this service to continue running until it is explicitly
// stopped, so return sticky.
return START_STICKY;
}
@Override
public void onDestroy() {
// Cancel the persistent notification.
mNM.cancel(R.string.local_service_started);
// Tell the user we stopped.
Toast.makeText(this, R.string.local_service_stopped, Toast.LENGTH_SHORT).show();
}
@Override
public IBinder onBind(Intent intent) {
return mBinder;
}
// This is the object that receives interactions from clients. See
// RemoteService for a more complete example.
private final IBinder mBinder = new LocalBinder();
/**
* Show a notification while this service is running.
*/
private void showNotification() {
// In this sample, we'll use the same text for the ticker and the expanded notification
CharSequence text = getText(R.string.local_service_started);
// Set the icon, scrolling text and timestamp
Notification notification = new Notification(R.drawable.stat_sample, text,
System.currentTimeMillis());
// The PendingIntent to launch our activity if the user selects this notification
PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
new Intent(this, LocalServiceActivities.Controller.class), 0);
// Set the info for the views that show in the notification panel.
notification.setLatestEventInfo(this, getText(R.string.local_service_label),
text, contentIntent);
// Send the notification.
// We use a layout id because it is a unique number. We use it later to cancel.
mNM.notify(R.string.local_service_started, notification);
}
}
2、bind
Bound 为Activity或是其它程序部件使用bindService()来启动Service。Bound Service提供了一种Client/Service方法允许调用Service的Activity与Service进行交互:发送请求,取得结果,并支持进程间通信。 一般Bound Service的生命周期和启动它的Activity相同,多个Activity可以同时绑定一个Service。 当所有Activity 都断开与Service之间的绑定时。Service自动结束。
service运行时,应用程序组件(比如Activity)与之绑定,然后接受请求并返回响应或者提供进程间通信机制,它的生命周期通常与调用它的组件(如Activity)相同。
public static class Binding extends Activity {
private boolean mIsBound;
private LocalService mBoundService;
private ServiceConnection mConnection = new ServiceConnection() {
public void onServiceConnected(ComponentName className, IBinder service) {
// This is called when the connection with the service has been
// established, giving us the service object we can use to
// interact with the service. Because we have bound to a explicit
// service that we know is running in our own process, we can
// cast its IBinder to a concrete class and directly access it.
mBoundService = ((LocalService.LocalBinder)service).getService();
// Tell the user about this for our demo.
Toast.makeText(Binding.this, R.string.local_service_connected,
Toast.LENGTH_SHORT).show();
}
public void onServiceDisconnected(ComponentName className) {
// This is called when the connection with the service has been
// unexpectedly disconnected -- that is, its process crashed.
// Because it is running in our same process, we should never
// see this happen.
mBoundService = null;
Toast.makeText(Binding.this, R.string.local_service_disconnected,
Toast.LENGTH_SHORT).show();
}
};
void doBindService() {
// Establish a connection with the service. We use an explicit
// class name because we want a specific service implementation that
// we know will be running in our own process (and thus won't be
// supporting component replacement by other applications).
bindService(new Intent(Binding.this,
LocalService.class), mConnection, Context.BIND_AUTO_CREATE);
mIsBound = true;
}
void doUnbindService() {
if (mIsBound) {
// Detach our existing connection.
unbindService(mConnection);
mIsBound = false;
}
}
@Override
protected void onDestroy() {
super.onDestroy();
doUnbindService();
}
private OnClickListener mBindListener = new OnClickListener() {
public void onClick(View v) {
doBindService();
}
};
private OnClickListener mUnbindListener = new OnClickListener() {
public void onClick(View v) {
doUnbindService();
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.local_service_binding);
// Watch for button clicks.
Button button = (Button)findViewById(R.id.bind);
button.setOnClickListener(mBindListener);
button = (Button)findViewById(R.id.unbind);
button.setOnClickListener(mUnbindListener);
}
}
Client 需要通过 ServiceConnection 接口来监视与Service之间的连接
ServiceConnection接口,onServiceConnected ,onServiceDisconnected分别在Service与Client 之间建立链接和断开链接时调用。其中IBinder service 就是 Service 的onBind的返回对象
3、start
Started 当一个如Activity使用startService()来启动一个Service,一旦Service启动后,就不受启动它的Activity控制,可以在后台长期运行,通常这种Service在后台执行某个费时操作(如下载文件)不会向启动它的Activity返回结果。
public static class Controller extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.local_service_controller);
// Watch for button clicks.
Button button = (Button)findViewById(R.id.start);
button.setOnClickListener(mStartListener);
button = (Button)findViewById(R.id.stop);
button.setOnClickListener(mStopListener);
}
private OnClickListener mStartListener = new OnClickListener() {
public void onClick(View v) {
// Make sure the service is started. It will continue running
// until someone calls stopService(). The Intent we use to find
// the service explicitly specifies our service component, because
// we want it running in our own process and don't want other
// applications to replace it.
startService(new Intent(Controller.this,
LocalService.class));
}
};
private OnClickListener mStopListener = new OnClickListener() {
public void onClick(View v) {
// Cancel a previous call to startService(). Note that the
// service will not actually stop at this point if there are
// still bound clients.
stopService(new Intent(Controller.this,
LocalService.class));
}
};
}
另外 也可以通过 startForeground,stopForeground来实现。
分享到:
相关推荐
Android Media...1、解决Android Q中java.lang.SecurityException: Media projections require a foreground service of type ServiceInfo.FOREGROUND_SERVICE_TYPE_MEDIA_PROJECTION 异常 2、targetSdk 32可用
this code uses to convert a video into frames and contains a code for draw a bounding box around foreground objects
Android5.0之后,利用MediaProjection实现录屏功能。
android-ForegroundService 这是我如何维护在前台运行的绑定服务的生命周期的实践项目。 如果服务在前台启动,应用程序可以打招呼。 到目前为止它的工作,但还没有尝试服务中是否有正在运行的线程。导入方法: 打开...
Android foreground services require a notification to be displayed, and notifications require an icon. For this plugin to work, the icon needs to be in this specific location: res/drawable/org_thebus...
8. Add ability of changing select text foreground color (optional). 9. Allow Replace to stop after replacement (optional). 10. Fix append extension feature not working in save dialog. 11. Add ability ...
Android前台服务 项目只是测试Android Oreo上引入的Backround限制
12 5.9 Text description of logical operations................................................................................................................. 13 5.10 Processes..........................
8. Add ability of changing select text foreground color (optional). 9. Allow Replace to stop after replacement (optional). 10. Fix append extension feature not working in save dialog. 11. Add ability ...
This library draw android view shadow by ShadowLayer. You may don't like the CardView's black shadow which we can't change it's color. Same to CardView wrap content and set shadow radius. You can ...
Android中Service组件的一些高级应用,具体查看博客:http://www.cnblogs.com/plokmju/p/Android_Service2.html
This package contains m-files for the segmentation of a moving foreground from video with a static background
............................................................................................................................................................................12 1.7 Power Grows on You......
Foreground and Background Threads .............................................................................. 10 Thread Priority ......................................................................
kotlin-foregroundService 具有android o通知的前台服务android的Kotlin代码 MainActivity.kt class MainActivity : AppCompatActivity() { var myService: MyService? = null var isBound = false privateval...
Table of Contents Summary of GDB . . . . . . . . ....Free software ....Contributors to GDB ....A Sample GDB Session ....Loading the Executable ....Setting Display width....Setting Breakpoints ....Running the executable ...
8. Add ability of changing select text foreground color (optional). 9. Allow Replace to stop after replacement (optional). 10. Fix append extension feature not working in save dialog. 11. Add ability ...
运动目标检测,混合高斯背景建模,背景建模,matlab 运动目标检测的混合高斯背景建模matlab代码 背景差分 混合高斯 matlab
前景提取四种方法,好学易懂,适合初学者!