zoukankan      html  css  js  c++  java
  • 03-Android基础知识---07-认识 Android Service

    使用Service:

    activity.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 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=".MainActivity"
        android:orientation="vertical">
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    
        <Button
            android:id="@+id/btnStartService"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="启动服务" />
    
        <Button
            android:id="@+id/btnStopService"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="停止服务" />
    
    </LinearLayout>

    Mainactivity.java:

    package com.imooc.learnservice;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    import android.content.Intent;
    import android.os.Bundle;
    import android.view.View;
    
    public class MainActivity extends AppCompatActivity {
    
    
    //第二种方式:
    
        private Intent intent;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            intent = new Intent(MainActivity.this,MyService.class);
    
    
            findViewById(R.id.btnStartService).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startService(intent);
                }
            });
    
            findViewById(R.id.btnStopService).setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    startService(intent);
                }
            });
    
    //第一种方式:
    //        findViewById(R.id.btnStartService).setOnClickListener(new View.OnClickListener() {
    //            @Override
    //            public void onClick(View v) {
    //                startService(new Intent(MainActivity.this,MyService.class));
    //            }
    //        });
    //
    //        findViewById(R.id.btnStopService).setOnClickListener(new View.OnClickListener() {
    //            @Override
    //            public void onClick(View v) {
    //                startService(new Intent(MainActivity.this,MyService.class));
    //            }
    //        });
        }
    }

    MyService.java:

    package com.imooc.learnservice;
    
    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();
                    while (true) {
                        System.out.println("服务正在进行...");
    
                        try {
                            sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
    
    
            return super.onStartCommand(intent, flags, startId);
        }
    }

    AndroidManifes.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <manifest xmlns:android="http://schemas.android.com/apk/res/android"
        package="com.imooc.learnservice">
    
        <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/Theme.LearnService">
    
    
            <service
                android:name=".MyService"
                android:enabled="true"
                android:exported="true"></service>
    
            <activity
                android:name=".MainActivity"
                android:exported="true">
                <intent-filter>
                    <action android:name="android.intent.action.MAIN" />
    
                    <category android:name="android.intent.category.LAUNCHER" />
                </intent-filter>
            </activity>
        </application>
    
    </manifest>

    绑定Service:

     activity_main.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout 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=".MainActivity"
        android:orientation="vertical">
    
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Hello World!"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintRight_toRightOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
    
        <Button
            android:id="@+id/btnStartService"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="启动服务" />
    
        <Button
            android:id="@+id/btnStopService"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="停止服务" />
        <Button
            android:id="@+id/btnBindService"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="绑定服务" />
    
        <Button
            android:id="@+id/btnUnBindService"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="解除绑定服务" />
    
    </LinearLayout>

    MainActivity.java:

    package com.imooc.learnservice;
    
    import androidx.appcompat.app.AppCompatActivity;
    
    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;
    
    public class MainActivity extends AppCompatActivity implements View.OnClickListener, ServiceConnection {
    
    
    //第二种方式:
    
        private Intent intent;
    
        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            intent = new Intent(MainActivity.this,MyService.class);
    
    
            findViewById(R.id.btnStartService).setOnClickListener(this);
    
            findViewById(R.id.btnStopService).setOnClickListener(this);
    
            findViewById(R.id.btnBindService).setOnClickListener(this);
    
            findViewById(R.id.btnUnBindService).setOnClickListener(this);
            //要是有很多个按钮都需要运行这事件,那么可以用this来代替
    
    //第一种方式:
    //        findViewById(R.id.btnStartService).setOnClickListener(new View.OnClickListener() {
    //            @Override
    //            public void onClick(View v) {
    //                startService(new Intent(MainActivity.this,MyService.class));
    //            }
    //        });
    //
    //        findViewById(R.id.btnStopService).setOnClickListener(new View.OnClickListener() {
    //            @Override
    //            public void onClick(View v) {
    //                startService(new Intent(MainActivity.this,MyService.class));
    //            }
    //        });
        }
    
        @Override
        public void onClick(View v) {
            switch (v.getId()){
                case R.id.btnStartService:
                    startService(intent);
                case R.id.btnStopService:
                    stopService(intent);
                case R.id.btnBindService:
                    bindService(intent,this, Context.BIND_AUTO_CREATE);
                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:

    package com.imooc.learnservice;
    
    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.
            return new Binder();
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
    
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    while (true) {
                        System.out.println("服务正在进行...");
    
                        try {
                            sleep(1000);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                }
            }.start();
    
    
            return super.onStartCommand(intent, flags, startId);
        }
    }

    Service生命周期:

    package com.imooc.learnservice;
    
    import android.app.Service;
    import android.content.Intent;
    import android.os.Binder;
    import android.os.IBinder;
    
    public class MyService extends Service {
    
        private boolean serviceRunning = false;
    
        public MyService() {
        }
    
        @Override
        public IBinder onBind(Intent intent) {
            // TODO: Return the communication channel to the service.
            return new Binder();
        }
    
        @Override
        public int onStartCommand(Intent intent, int flags, int startId) {
    
    //        new Thread() {
    //            @Override
    //            public void run() {
    //                super.run();
    //                while (serviceRunning) {
    //                    System.out.println("服务正在进行...");
    //
    //                    try {
    //                        sleep(1000);
    //                    } catch (InterruptedException e) {
    //                        e.printStackTrace();
    //                    }
    //                }
    //            }
    //        }.start();
    
            System.out.println("OnSatrtCommand");
            return super.onStartCommand(intent, flags, startId);
    
        }
    
        @Override
        public void onCreate() {
            super.onCreate();
    
            System.out.println("service cerate");
    
            new Thread() {
        @Override
            public void run() {
                super.run();
                while (serviceRunning) {
                    System.out.println("服务正在进行...");
    
                    try {
                        sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
                        }.start();
    
            serviceRunning = true;
        }
    
        @Override
        public void onDestroy() {
            super.onDestroy();
    
            System.out.println("service destory");
    
            serviceRunning = false;
    
        }
    }
  • 相关阅读:
    CSS之旅——第二站 如何更深入的理解各种选择器
    CSS之旅——第一站 为什么要用CSS
    记录一些在用wcf的过程中走过的泥巴路 【第一篇】
    asp.net mvc 之旅—— 第二站 窥探Controller下的各种Result
    asp.net mvc 之旅—— 第一站 从简单的razor入手
    Sql Server之旅——终点站 nolock引发的三级事件的一些思考
    Sql Server之旅——第十四站 深入的探讨锁机制
    Sql Server之旅——第十三站 对锁的初步认识
    Sql Server之旅——第十二站 sqltext的参数化处理
    Sql Server之旅——第十一站 简单说说sqlserver的执行计划
  • 原文地址:https://www.cnblogs.com/juham/p/15205807.html
Copyright © 2011-2022 走看看