您的位置:首页 > 其它

service详解

2015-11-03 16:26 197 查看
Thread 主要用来执行异步操作service 是android的一种机制, 比如在后台执行播放音乐之类的生命周期: onCreate  onStartCommand  onUnbind  onDestroyIntent intent = new Intent(ServiceTestActivity.this,                         MyService.class);                 startService(intent); // 会调用  onCreate   onStartCommand   如果已启动servce 只会调用onStartCommand   
public class CountService extends Service {
    private boolean threadDisable;
    private int count;
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        super.onCreate();
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (!threadDisable) {
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                    }
                    count++;
                    Log.v("CountService", "Count is " + count);
                }
            }
        }).start();
    }
    @Override
    public void onDestroy() {
        super.onDestroy();
        this.threadDisable = true;
        Log.v("CountService", "on destroy");
    }
    public int getCount() {
        return count;
    }
}
public class LocalServiceDemoActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        this.startService(new Intent(this, CountService.class));
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        this.stopService(new Intent(this, CountService.class));
    }
}

                                            
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: