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来实现。




更多相关文章

  1. Android(安卓)返回键退出APP
  2. Android启动和关闭Activity
  3. Android为返回键设置动画效果
  4. Android(安卓)接收开机广播启动service/activity
  5. 自定义按钮实现android 返回按钮 事件
  6. Android问题集
  7. Android计时器
  8. Android(安卓)Studio实现Activity生命周期的7个方法Log打印日志
  9. android再点一次返回退出

随机推荐

  1. 基于android的远程视频监控系统
  2. Android 5.0特征补充4-DrawerLayout
  3. Android 可拖动的进度条:SeekBar之简单使
  4. 菜鸟窝-仿京东淘宝项目学习笔记(二)ToolBar
  5. MediaPlayer源码存在的内存泄漏问题,释放
  6. Android进程间(IPC机制)通信(Bundler,Messe
  7. 从零开始的Android新项目10 - React Nati
  8. Android自定义控件---打造不一样的FlowLa
  9. Android中bindService的细节之二:从进程的
  10. 微信抢红包插件与Android辅助功能