Service和IntentService

来源:互联网 发布:网络状况调查报告交流 编辑:程序博客网 时间:2024/05/17 08:59

    • 服务Service的含义
    • Service和IntentService的区别
      • 主函数
      • MyService
      • MyIntentService
      • 布局

服务(Service)的含义

服务(Service)是Android中实现程序后台运行的解决方案,它非常适合用于去执行那些不需要和用户交互而且还要长期运行的任务,服务的运行不依赖于任何用户界面,即使当程序被切换到后台,或者用户打开了另外一个应用程序服务仍然能够保持正常运行。

需要注意的是:

服务并不是运行在一个独立的进程当中的,而是依赖于创建服务时所在的应用程序进程。当某个应用程序被杀掉时,所有依赖于该进程的服务也会停止运行。
另外,服务并不会自动开启线程,所有的代码都是默认运行在主线程当中的,也就是说,我们需要在服务的内部手动创建子线程,并在这里执行具体的任务,否则就有可能出现主线程被阻塞住的情况。

每一个*服务都需要在AndroidManifest.xml文件中进行注册才能生效,当然这是四大组件共有的特点——<service android :name=".MyService"></service>*

Service和IntentService的区别

1、Service中的onCreate()方法是在服务第一次创建时调用的,而onStartCommand()方法则在每次启动服务的时候都会调用,所以如果我们希望服务一旦启动就立刻执行某个动作,就可以将逻辑写在onStartCommand()方法里。
2、IntentService是继承Service的,它包含了Service的全部特性,当然也包含service的生命周期,与service不同的是,IntentService在执行onCreate操作的时候,内部开了一个线程,去执行自己的耗时操作。

主函数

public class MainActivity extends AppCompatActivity implements View.OnClickListener {private Button mButtonStart;    private Button mButtonStop;    private Button mButtonStartDownload;    private ProgressBar mProgressBar;    private  MyDownLoadReceiver receiver;    public static final  String DOWN_LOAD_ACTION="com.example.test";    @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);        //因为用到了BroadcastReceiver,所以这里需要一个继承了BroadcastReceiver类的(MyDownLoadReceiver)类的实例,        receiver=new MyDownLoadReceiver();        IntentFilter filter=new IntentFilter();        filter.addAction(DOWN_LOAD_ACTION);        registerReceiver(receiver,filter);//有了这个注册,下面必须要写一个对应的反注册才不会出错。        mButtonStart= (Button) findViewById(R.id.button_start_service);        mButtonStop= (Button) findViewById(R.id.button_stop_service);        mButtonStart.setOnClickListener(this);        mButtonStop.setOnClickListener(this);        mButtonStartDownload= (Button) findViewById(R.id.button_start_download);        mButtonStartDownload.setOnClickListener(this);        mProgressBar= (ProgressBar) findViewById(R.id.progressBar);    }    @Override    protected void onDestroy() {        super.onDestroy();        unregisterReceiver(receiver);//对应上面的registerReceiver    }    @Override    public void onClick(View v) {        switch (v.getId()){            case R.id.button_start_service://                Intent intent=new Intent(getApplicationContext(),MyService.class);//                startService(intent);                break;            case R.id.button_stop_service://                Intent intent1=new Intent(getApplicationContext(),MyService.class);                Intent intent1=new Intent(getApplicationContext(),MyIntentService.class);            stopService(intent1);                break;            case R.id.button_start_download://                Intent intent2=new Intent (getApplicationContext(),MyService.class);                Intent intent2=new Intent (getApplicationContext(),MyIntentService.class);                startService(intent2);            default:                break;        }    }    class MyDownLoadReceiver extends BroadcastReceiver{        @Override        public void onReceive(Context context, Intent intent) {            int count=intent.getIntExtra("count",0);            mProgressBar.setProgress(count);        }    }}

MyService

/** * Created by Administrator on 2015/9/8. */public class MyService extends Service{    //服务是可在后台运行的    private int count=0;    @Override    public void onCreate() {        super.onCreate();        Log.d("", "onCreate");    }    @Override    public int onStartCommand(Intent intent, int flags, int startId) {        Log.d("","onStartCommand");        new Thread(new Runnable() {            @Override            public void run() {                while(true){                    if(count>100){                        count=0;                    }                    count++;                    Intent intent=new Intent();                    intent.setAction(MainActivity.DOWN_LOAD_ACTION);                    intent.putExtra("count", count);                    sendBroadcast(intent);                    try {                        Thread.sleep(200);                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                }            }        }).start();        return super.onStartCommand(intent, flags, startId);    }    @Override    public void onDestroy() {        super.onDestroy();        Log.d("", "onDestroy");    }    @Nullable    @Override    public IBinder onBind(Intent intent) {        return null;    }}

MyIntentService

/** * Created by Administrator on 2015/9/9. */public class MyIntentService extends IntentService {    private int count=0;public MyIntentService(String name){    super(name);}    public  MyIntentService(){        this("");    }    @Override    public void onDestroy() {        Log.d("intentService","服务关闭");        super.onDestroy();    }    @Override    protected void onHandleIntent(Intent intent) {        Log.d("intentService","运行到IntentService");                while(true){                    if(count>100){                        count=0;                    }                    count++;                    Intent intent1=new Intent();                    intent1.setAction(MainActivity.DOWN_LOAD_ACTION);                    intent1.putExtra("count", count);                    sendBroadcast(intent1);                    try {                        Thread.sleep(200);                    } catch (InterruptedException e) {                        e.printStackTrace();                    }                }            }}

布局

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent"    android:layout_height="match_parent" android:paddingLeft="@dimen/activity_horizontal_margin"    android:paddingRight="@dimen/activity_horizontal_margin"    android:paddingTop="@dimen/activity_vertical_margin"    android:paddingBottom="@dimen/activity_vertical_margin" tools:context=".MainActivity"    android:orientation="vertical">    <Button        android:id="@+id/button_start_service"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:visibility="gone"        android:text="启动服务"/>    <Button        android:id="@+id/button_stop_service"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="停止服务"/>    <ProgressBar        style="?android:attr/progressBarStyleHorizontal"        android:id="@+id/progressBar"        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_gravity="center_horizontal"       android:minHeight="50dp"        android:progress="50"/>    <Button        android:id="@+id/button_start_download"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="开始下载"/></LinearLayout>
0 0
原创粉丝点击