Android Service教程含代碼

Android Service教程

Android服務 是一個組件,用于在后臺執行操作,例如播放音樂,處理網絡事務,與內容提供程序交互等。愛掏網 - it200.com它沒有任何用戶界面(UI)。愛掏網 - it200.com

即使應用程序被銷毀,該服務也會在后臺無限期運行。愛掏網 - it200.com

此外,服務可以由組件綁定,以進行交互和進程間通信(IPC)。愛掏網 - it200.com

android.app.Service是ContextWrapper類的子類。愛掏網 - it200.com

注意:Android服務不是線程或單獨的進程。愛掏網 - it200.com

Android服務的生命周期

服務有兩種形式。愛掏網 - it200.com服務的生命周期可以遵循兩條不同的路徑:啟動或綁定。愛掏網 - it200.com

  1. 啟動
  2. 綁定

1)啟動的服務

當組件(如活動)調用 startService() 方法時,服務會啟動,現在它在后臺無限期運行。愛掏網 - it200.com通過 stopService() 方法可以停止服務。愛掏網 - it200.com服務可以通過調用 stopSelf() 方法來停止自身。愛掏網 - it200.com

2)綁定的服務

當另一個組件(例如客戶端)調用 bindService() 方法時,服務會綁定。愛掏網 - it200.com客戶端可以通過調用 unbindService() 方法解綁服務。愛掏網 - it200.com

只有當所有客戶端解綁服務后,服務才能停止。愛掏網 - it200.com

理解通過背景音樂示例開始和綁定服務

假設我想在后臺播放音樂,所以調用startService()方法。愛掏網 - it200.com但是我想獲得當前播放的歌曲的信息,我將綁定提供有關當前歌曲信息的服務。愛掏網 - it200.com

Android服務示例

讓我們看一個在Android中在后臺播放音頻的服務示例。愛掏網 - it200.com即使您切換到另一個活動,音頻也不會停止。愛掏網 - it200.com要停止音頻,您需要停止服務。愛掏網 - it200.com

activity_main.xml

從工具箱中拖動3個按鈕,現在activity_main.xml文件的樣子如下:

<?xml version="1.0" encoding="utf-8"?>  
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:app="http://schemas.android.com/apk/res-auto"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context="example.javatpoint.com.androidservice.MainActivity">  


    <Button  
        android:id="@+id/buttonStart"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentTop="true"  
        android:layout_centerHorizontal="true"  
        android:layout_marginTop="74dp"  
        android:text="Start Service" />  

    <Button  
        android:id="@+id/buttonStop"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_centerHorizontal="true"  
        android:layout_centerVertical="true"  
        android:text="Stop Service" />  

    <Button  
        android:id="@+id/buttonNext"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_alignParentBottom="true"  
        android:layout_centerHorizontal="true"  
        android:layout_marginBottom="63dp"  
        android:text="Next Page" />  
</RelativeLayout>  

activity_next.xml

這是下一個活動的布局文件。愛掏網 - it200.com

它只包含一個文本視圖,顯示消息”下一頁”

<?xml version="1.0" encoding="utf-8"?>  
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"  
    xmlns:app="http://schemas.android.com/apk/res-auto"  
    xmlns:tools="http://schemas.android.com/tools"  
    android:layout_width="match_parent"  
    android:layout_height="match_parent"  
    tools:context="example.javatpoint.com.androidservice.NextPage">  

    <TextView  
        android:id="@+id/textView"  
        android:layout_width="wrap_content"  
        android:layout_height="wrap_content"  
        android:layout_marginEnd="8dp"  
        android:layout_marginStart="8dp"  
        android:layout_marginTop="200dp"  
        android:text="Next Page"  
        app:layout_constraintEnd_toEndOf="parent"  
        app:layout_constraintStart_toStartOf="parent"  
        app:layout_constraintTop_toTopOf="parent" />  
</android.support.constraint.ConstraintLayout>  

服務類

現在通過繼承服務類并重寫其回調方法來創建服務實現類。愛掏網 - it200.com

package example.javatpoint.com.androidservice;

import android.app.Service;
import android.content.Intent;
import android.media.MediaPlayer;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.widget.Toast;

public class MyService extends Service {
    MediaPlayer myPlayer;
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
    @Override
    public void onCreate() {
        Toast.makeText(this, "Service Created", Toast.LENGTH_LONG).show();

        myPlayer = MediaPlayer.create(this, R.raw.sun);
        myPlayer.setLooping(false); // Set looping
    }
    @Override
    public void onStart(Intent intent, int startid) {
        Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
        myPlayer.start();
    }
    @Override
    public void onDestroy() {
        Toast.makeText(this, "Service Stopped", Toast.LENGTH_LONG).show();
        myPlayer.stop();
    }
}

Activity類

現在創建MainActivity類來執行事件處理。愛掏網 - it200.com在這里,我們編寫代碼來啟動和停止服務。愛掏網 - it200.com此外,通過buttonNext調用第二個活動。愛掏網 - it200.com

package example.javatpoint.com.androidservice;

import android.content.Intent;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
    Button buttonStart, buttonStop,buttonNext;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        buttonStart = findViewById(R.id.buttonStart);
        buttonStop = findViewById(R.id.buttonStop);
        buttonNext =  findViewById(R.id.buttonNext);

        buttonStart.setOnClickListener(this);
        buttonStop.setOnClickListener(this);
        buttonNext.setOnClickListener(this);


    }
    public void onClick(View src) {
        switch (src.getId()) {
            case R.id.buttonStart:

                startService(new Intent(this, MyService.class));
                break;
            case R.id.buttonStop:
                stopService(new Intent(this, MyService.class));
                break;
            case R.id.buttonNext:
                Intent intent=new Intent(this,NextPage.class);
                startActivity(intent);
                break;
        }
    }
}

NextPage類

現在,創建另一個活動。愛掏網 - it200.com

package example.javatpoint.com.androidservice;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;

public class NextPage extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_next);
    }
}

聲明服務在AndroidManifest.xml文件中

最后,在清單文件中聲明服務。愛掏網 - it200.com

讓我們看看完整的AndroidManifest.xml文件

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

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

                <category android:name="android.intent.category.LAUNCHER" />  
            </intent-filter>  
        </activity>  
        <activity android:name=".NextPage"></activity>  
        <service  
            android:name=".MyService"  
            android:enabled="true" />  
    </application>  

</manifest>  

輸出:

聲明:所有內容來自互聯網搜索結果,不保證100%準確性,僅供參考。如若本站內容侵犯了原著者的合法權益,可聯系我們進行處理。
發表評論
更多 網友評論0 條評論)
暫無評論

返回頂部

主站蜘蛛池模板: 亚洲综合小说久久另类区| 国产成人免费在线观看 | 国产第一福利136视频导航| 亚洲一区二区影视| 韩国理论福利片午夜| 扁豆传媒网站免费进入| 作者不详不要…用力呢| 1024手机看片基地| 日本高清视频色wwwwww色| 厨房切底征服岳| 99久久99久久免费精品小说| 欧美一区二区三区精品影视| 国产伦精品一区二区三区四区| 东北大坑第二部txt| 波多野结衣在丈夫面前| 国产欧美日韩综合精品二区 | 成人中文字幕一区二区三区| 亚洲精品视频久久久| 欧美一级久久久久久久大片| 无码一区二区三区在线观看| 伊人久久无码中文字幕| 两个人看的www在线视频| 无遮无挡爽爽免费视频| 人妻少妇精品视频专区| 久久精品久噜噜噜久久| 成人国产一区二区三区| 亚洲欧洲日产国码www| 野花香高清在线观看视频播放免费| 宵宫被爆3d动画羞羞漫画| 亚洲国产理论片在线播放| 色综合久久久无码中文字幕| 夜夜揉揉日日人人青青| 久久精品中文字幕一区| 男女性潮高清免费网站| 国产欧美一区二区精品久久久| 中文字幕在线色| 欧美日韩你懂的| 国产av夜夜欢一区二区三区| 91福利视频免费| 无码人妻精品一二三区免费| 亚洲欧美成人综合久久久|