Android Service

来源:互联网 发布:论文数据造假有人查吗 编辑:程序博客网 时间:2024/04/29 21:41
1.首先来了解Service
    service就是一个服务的后勤人员,就像(快递员不停的收快递,发快递,来保证顾客的需求)
    Service,看名字就知道跟正常理解的“服务”差不多,后台运行,可交互这样的一个东西。它跟Activity的级别差不多,但是他不能自己运行,
  需要通过某一个Activity或者其他Context对象来调用, Context.startService() 和Context.bindService()。
  两种启动Service的方式有所不同。这里要说明一下的是如果你在Service的onCreate或者onStart做一些很耗时间的事情,
  最好在Service里启动一个线程来完成,因为Service是跑在主线程中,会影响到你的UI操作或者阻塞主线程中的其他事情。
  什么时候需要Service呢?比如播放多媒体的时候用户启动了其他Activity这个时候程序要在后台继续播放,比如检测网络的变化,
  再或者在后台记录你地理信息位置的改变等等,总之服务就是你看不见的但是能感受到的而且很重要的东西.
2.看看看service的生命周期(即从创建到销毁的过程)
              
3.具体代码演示
  首先要创建一个类并继承Srvice  自然要实现父类的方法

public class MyService extends Service {   
    private static final String TAG = "MyService";   
    private NotificationManager _nm;   
  
   @Override  
    public void onCreate() {   
        Log.e(TAG, "============> TestService.onCreate");   
        _nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);   
        showNotification();   
    }
    @Override  
    public IBinder onBind(Intent i) {   
        Log.e(TAG, "============> MyService.onBind");   
        return null;   
    }   
  
    public class LocalBinder extends Binder {   
        TestService getService() {   
            return TestService.this;   
        }   
    }   
  
    @Override  
    public boolean onUnbind(Intent i) {   
        Log.e(TAG, "============> MyService.onUnbind");   
        return false;   
    }   
  
    @Override  
    public void onRebind(Intent i) {   
        Log.e(TAG, "============> TestService.onRebind");   
    }   
  
    @Override  
    public void onCreate() {   
        Log.e(TAG, "============> MyService.onCreate");   
        _nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);   
        showNotification();   
    }   
  
    @Override  
    public void onStart(Intent intent, int startId) {   
        Log.e(TAG, "============> MyService.onStart");   
    }   
  
    @Override  
    public void onDestroy() {   
        _nm.cancel(R.string.service_started);   
        Log.e(TAG, "============> MyService.onDestroy");   
    }   
  
    private void showNotification() {   
        Notification notification = new Notification(R.drawable.face_1,   
                "Service started", System.currentTimeMillis());   
  
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,   
                new Intent(this, TestServiceHolder.class), 0);   
  
        // must set this for content view, or will throw a exception   
        notification.setLatestEventInfo(this, "Test Service",   
                "Service started", contentIntent);   
  
        _nm.notify(R.string.service_started, notification);   
    }   
}
其中用到Notification是为了明显地表明Service存活的状
public class LocalBinder extends Binder {   
        TestService getService() {   
            return TestService.this;   
        }   
    }   
这个方法是为了让调用者得到这个Service并操作它。Service本身就这样简单了,你需要做什么就在onCreate和onStart里做好了,起个线程什么的。


在Activity中调用service

public class TestServiceHolder extends Activity {   
    private boolean _isBound;   
    private TestService _boundService;   
  
    public void onCreate(Bundle savedInstanceState) {   
        super.onCreate(savedInstanceState);   
        setContentView(R.layout.test_service_holder);   
        setTitle("Service Test");   
  
        initButtons();   
    }   
     //构造服务连接对象  
    private ServiceConnection _connection = new ServiceConnection() {   
        public void onServiceConnected(ComponentName className, IBinder service) {   
            _boundService = ((TestService.LocalBinder)service).getService();   
               
            Toast.makeText(TestServiceHolder.this, "Service connected",   
                    Toast.LENGTH_SHORT).show();   
        }   
  
        public void onServiceDisconnected(ComponentName className) {   
            // unexpectedly disconnected,we should never see this happen.   
            _boundService = null;   
            Toast.makeText(TestServiceHolder.this, "Service connected",   
                    Toast.LENGTH_SHORT).show();   
        }   
    };   
  
    private void initButtons() {   
        Button buttonStart = (Button) findViewById(R.id.start_service);   
        buttonStart.setOnClickListener(new OnClickListener() {   
            public void onClick(View arg0) {   
                startService();   
            }   
        });   
  
        Button buttonStop = (Button) findViewById(R.id.stop_service);   
        buttonStop.setOnClickListener(new OnClickListener() {   
            public void onClick(View arg0) {   
                stopService();   
            }   
        });   
  
        Button buttonBind = (Button) findViewById(R.id.bind_service);   
        buttonBind.setOnClickListener(new OnClickListener() {   
            public void onClick(View arg0) {   
                bindService();   
            }   
        });   
  
        Button buttonUnbind = (Button) findViewById(R.id.unbind_service);   
        buttonUnbind.setOnClickListener(new OnClickListener() {   
            public void onClick(View arg0) {   
                unbindService();   
            }   
        });   
    }   
  
    private void startService() {   
        Intent i = new Intent(this, TestService.class);   
        this.startService(i);   
    }   
  
    private void stopService() {   
        Intent i = new Intent(this, TestService.class);   
        this.stopService(i);   
    }   
  
    private void bindService() {   
        Intent i = new Intent(this, TestService.class);   
         bindService(i, _connection, Context.BIND_AUTO_CREATE);   
         _isBound = true;   
    }   
  
    private void unbindService() {  
     
        if (_isBound) {   
            unbindService(_connection);   
            _isBound = false;   
        }   
    }   
}  
 
这里可以看到两种启动方法,start和bind,当然也是通过intent调用的,在intent中指明指定要启动的Service的名字,stop也一样 :


private void startService() {   
        Intent i = new Intent(this, MyService.class);   
        this.startService(i);   
    }   
  
private void stopService() {   
        Intent i = new Intent(this, MyService.class);   
        this.stopService(i);   
    }  
对于bind的话,需要一个ServiceConnection对象


private ServiceConnection _connection = new ServiceConnection() {   
        public void onServiceConnected(ComponentName className, IBinder service) {   
            _boundService = ((MyService.LocalBinder)service).getService();   
               
            Toast.makeText(MyServiceHolder.this, "Service connected",   
                    Toast.LENGTH_SHORT).show();   
        }   
  
        public void onServiceDisconnected(ComponentName className) {   
            // unexpectedly disconnected,we should never see this happen.   
            _boundService = null;   
            Toast.makeText(MyServiceHolder.this, "Service connected",   
                    Toast.LENGTH_SHORT).show();   
        }   
    };  
用来把Activity和特定的Service连接在一起,共同存亡。
0 0
原创粉丝点击