您的位置:首页 > 移动开发 > Android开发

Android四大组件---Service

2015-09-09 20:59 696 查看
服务是Android实现后台运行的解决方案,用于执行那些不需要和用户交互还要求长期运行的任务,服务运行不依赖界面,及时打开了另一个程序,服务依旧在后台运行。服务依赖于创建服务的应用程序进程,进程被杀掉服务就停止。

下图是Service的生命周期:




Service的用法:

首先在Manifest里面activity下声明service,但Service是在主线程中,如果执行耗时操作会阻塞主线程。这里用IntentService,它本身包含一个子线程,一个消息队列(按优先级排序执行),当然Service和IntentService用法一样Service中是写在onStartCommand方法中。

用IntentService做一个简单的主线程与子线程发送广播,结构图如下:




代码:

<!--service的声明-->
<service android:name=".Myservice"></service>
<!--IntentService的声明-->
<service android:name=".MyIntentService"></service>
public class MainActivity extends Activity implements View.OnClickListener {
    private Button mBtn_start;
    private Button mBtn_stop;
    private Button mBtn_download;
    private ProgressBar progressBar;
    private Myreceiver myreceiver;
    public static String DOWNLOAD = "com.android.download";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        myreceiver = new Myreceiver();//绑定广播***
        IntentFilter filter = new IntentFilter();
        filter.addAction(DOWNLOAD);
        registerReceiver(myreceiver, filter);
        mBtn_start = (Button) findViewById(R.id.button_startservice);
        mBtn_stop = (Button) findViewById(R.id.button_stopservice);
        mBtn_download = (Button) findViewById(R.id.button_startdownload);
        progressBar = (ProgressBar) findViewById(R.id.progressBar);
        mBtn_start.setOnClickListener(this);
        mBtn_stop.setOnClickListener(this);
        mBtn_download.setOnClickListener(this);
    }

    @Override
    protected void onDestroy() {
        unregisterReceiver(myreceiver);
        super.onDestroy();
    }

    class Myreceiver extends BroadcastReceiver {
        //广播***
        @Override
        public void onReceive(Context context, Intent intent) {
            int count = intent.getIntExtra("count", 0);
            progressBar.setProgress(count);
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.button_stopservice:
                Intent intent1 = new Intent(getApplication(), MyIntentService.class);//这里使用了.class调用无参构造器,不写会报错
                stopService(intent1);
                break;
            case R.id.button_startdownload:
                Intent intent2 = new Intent(getApplicationContext(), MyIntentService.class);
                startService(intent2);
                break;
        }
    }
}


MyIntentService代码:

public class MyIntentService extends IntentService {
    private int count;
    /**
     * Creates an IntentService.  Invoked by your subclass's constructor.
     *
     * @param name Used to name the worker thread, important only for debugging.
     */
    public MyIntentService(String name) {
        super(name);
    }
    public MyIntentService(){//不写这个无参构造器会报错
        this("");
    }
    @Override
    protected void onHandleIntent(Intent intent) {
        Thread thread =new Thread(new Runnable() {//写一个线程用于发送广播
            @Override
            public void run() {
                while(count<101){
                    count++;
                    Intent intent=new Intent();//以下4句发送广播
                    intent.setAction(MainActivity.DOWNLOAD);
                    intent.putExtra("count", count);//把count传过去
                    sendBroadcast(intent);
                    try {
                        Thread.sleep(200);//让进度条慢点跑~
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        thread.start();
    }
}


结束服务后线程没跑完继续跑,线程跑完后会自动回收内存
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: