Android Studio开发基础之Service

1、Service的使用

       Activity可以呈现一个用户界面,但是Service确实运行在后台,新建一个Myservice.java,会在AndroidManifest中自动配置<Service>标签。

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.lhb.service" >

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true" >
        </service>
    </application>
</manifest>
       在新建的Service中重写onStartCommand()函数,创建一个线程,点击启动线程按钮,让它在后台循环打印,注意按后退键退出Activity,服务仍在进行。

package com.example.lhb.service;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        new Thread(){
            @Override
            public void run() {
                super.run();
                do {
                    System.out.println("Service is running......");
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                } while (true);
            }
        }.start();
        return super.onStartCommand(intent, flags, startId);
    }
}
       主代码如下:
package com.example.lhb.service;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity implements View.OnClickListener{
    private TextView textView;
    private Intent intent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        InitView();
    }
    private void InitView(){
        textView=new TextView(this);
        textView.setText(R.string.hello_world);
        findViewById(R.id.btnStartService).setOnClickListener(this);
        findViewById(R.id.btnStopService).setOnClickListener(this);
        intent=new Intent(MainActivity.this,MyService.class);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnStartService:
                startService(intent);
                break;
            case R.id.btnStopService:
                stopService(intent);
                break;
        }
    }
}

2、绑定Service

       可以以绑定的方式启动MyService,再添加一个绑定Service和解除绑定Service的按钮。

<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"
    android:orientation="vertical"
    tools:context=".MainActivity">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="启动服务"
        android:id="@+id/btnStartService" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="停止服务"
        android:id="@+id/btnStopService" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="绑定服务"
        android:id="@+id/btnBindService" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="解除绑定服务"
        android:id="@+id/btnUnBindService" />
</LinearLayout>

       主程序:

package com.example.lhb.service;

import android.app.Activity;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.view.View;
import android.widget.TextView;

public class MainActivity extends Activity implements View.OnClickListener, ServiceConnection {
    private TextView textView;
    private Intent intent;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        InitView();
    }
    private void InitView(){
        textView=new TextView(this);
        textView.setText(R.string.hello_world);
        findViewById(R.id.btnStartService).setOnClickListener(this);
        findViewById(R.id.btnStopService).setOnClickListener(this);
        findViewById(R.id.btnBindService).setOnClickListener(this);
        findViewById(R.id.btnUnBindService).setOnClickListener(this);
        intent=new Intent(MainActivity.this,MyService.class);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.btnStartService:
                startService(intent);
                break;
            case R.id.btnStopService:
                stopService(intent);
                break;
            case R.id.btnBindService:
                bindService(intent,this, Context.BIND_AUTO_CREATE);
                //直接用this连接会出错,按Alt+Enter,创建下面的onServiceConnected()
                break;
            case R.id.btnUnBindService:
                unbindService(this);
                break;
        }
    }

    @Override
    //服务绑定后执行
    public void onServiceConnected(ComponentName name, IBinder service) {
        System.out.println("Service connected");
    }

    @Override
    //进程奔溃时执行
    public void onServiceDisconnected(ComponentName name) {

    }
}
       注意:完成上述代码之后,要将MyService.java中的IBinder改为return new Binder();,否则会出现错误!
@Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        //throw new UnsupportedOperationException("Not yet implemented");
        return new Binder();
    }
java.lang.RuntimeException: Unable to bind to service com.example.lhb.service.MyService@d3a4c20 with Intent { cmp=com.example.lhb.service/.MyService }: java.lang.UnsupportedOperationException: Not yet implemented
            at android.app.ActivityThread.handleBindService(ActivityThread.java:2771)
            at android.app.ActivityThread.access$1900(ActivityThread.java:144)
            at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1366)
            at android.os.Handler.dispatchMessage(Handler.java:102)
            at android.os.Looper.loop(Looper.java:135)
            at android.app.ActivityThread.main(ActivityThread.java:5221)
            at java.lang.reflect.Method.invoke(Native Method)
            at java.lang.reflect.Method.invoke(Method.java:372)
            at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
            at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)
     Caused by: java.lang.UnsupportedOperationException: Not yet implemented
            at com.example.lhb.service.MyService.onBind(MyService.java:14)
3、Service生命周期
package com.example.lhb.service;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        //throw new UnsupportedOperationException("Not yet implemented");
        return new Binder();
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onCreate() {
        super.onCreate();
        System.out.println("onCreate");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        System.out.println("onDestroy");
    }
}
       运行时发现,同时点击了启动服务和绑定服务,需同时点击停止服务和解除绑定服务才能将服务停下来,点击绑定服务,再退出Activity,程序会抛出异常,然后会执行解除绑定服务,整个程序界面如下图:

Android Studio开发基础之Service_第1张图片




你可能感兴趣的:(Android Studio开发基础之Service)