Android Studio開發基礎之Service

來源:互聯網
上載者:User

標籤:

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 [email protected] 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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.