Android_带你了解Service

转载请注明出处:http://my.csdn.net/Android___vv

Service作为Android四大组件之一,在每一个应用程序中都扮演着非常重要的角色。它主要用于在后台处理一些耗时的逻辑,或者去执行某些需要长期运行的任务。必要的时候我们甚至可以在程序退出的情况下,让Service在后台继续保持运行状态

一:简单使用

首先创建MyService继承自Service,重写父类的onCreate()、onStartCommand()和onDestroy()方法

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

/**
 * Created by Administrator on 2017/12/13 0013.
 */

public class MyService extends Service{

    private static final String TAG = "MyService";

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("TAG", "onCreate");
    }

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

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("TAG", "onDestroy");
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
}
不要忘记清单文件注册


布局两个点击按钮

<?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="com.example.service.MainActivity"
    android:orientation="vertical">

    <Button
        android:id="@+id/start"
        android:text="Start Service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/stop"
        android:text="Stop Service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    

</LinearLayout>


代码

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.start)
    Button start;
    @BindView(R.id.stop)
    Button stop;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }
    
    @OnClick({R.id.start, R.id.stop})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.start:
                //开启服务
                Intent intent = new Intent(this, MyService.class);
                startService(intent);
                break;
            case R.id.stop:
                //停止服务
                Intent intent2 = new Intent(this, MyService.class);
                stopService(intent2);
                break;
        }
    }
}

二:Service和Activity通信

Myservice做了一些改动

package com.example.service;

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

/**
 * Created by Administrator on 2017/12/13 0013.
 */

public class MyService2 extends Service {

    public static final String TAG = "MyService";

    private MyBinder mBinder = new MyBinder();
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("TAG", "onCreate");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("TAG", "onStartCommand");
        new Thread(new Runnable() {
            @Override
            public void run() {
                // 开始执行后台任务
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("TAG", "onDestroy");
    }

    @Override
    public IBinder onBind(Intent intent) {
        return mBinder;
    }

    //新增了一个MyBinder类继承自Binder类,然后在MyBinder中添加了一个startDownload()方法用于在后台执行任务
    class MyBinder extends Binder {

        public void startDownload() {
            Log.d("TAG", "startDownload2() executed");
            new Thread(new Runnable() {
                @Override
                public void run() {
                    // 执行具体的任务
                }
            }).start();
        }
    }
}

布局中添加了两个按钮

<?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="com.example.service.MainActivity"
    android:orientation="vertical">

    <Button
        android:id="@+id/start"
        android:text="Start Service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />
    <Button
        android:id="@+id/stop"
        android:text="Stop Service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content" />

    <Button
        android:id="@+id/bind_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Bind Service" />

    <Button
        android:id="@+id/unbind_service"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Unbind Service" />

</LinearLayout>

代码

package com.example.service;

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

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    @BindView(R.id.start)
    Button start;
    @BindView(R.id.stop)
    Button stop;
    @BindView(R.id.bind_service)
    Button bind;
    @BindView(R.id.unbind_service)
    Button unbind;
    private MyService2.MyBinder myBinder2;

    /*
    *首先创建了一个ServiceConnection的匿名类,
    *在里面重写了onServiceConnected()方法和onServiceDisconnected()方法,
    *这两个方法分别会在Activity与Service建立关联和解除关联的时候调用。
    *在onServiceConnected()方法中,我们又通过向下转型得到了MyBinder的实例,
    *有了这个实例,Activity和Service之间的关系就变得非常紧密了。
    *现在我们可以在Activity中根据具体的场景来调用MyBinder中的任何public方法,
    *即实现了Activity指挥Service干什么Service就去干什么的功能
     */
    private ServiceConnection connection = new ServiceConnection() {

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }

        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            myBinder2 = (MyService2.MyBinder) service;
            myBinder2.startDownload();
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    /*
    *如果我们既点击了Start Service按钮,又点击了Bind Service按钮会怎么样呢?
    * 这个时候你会发现,不管你是单独点击Stop Service按钮还是Unbind Service按钮,Service都不会被销毁,
    * 必要将两个按钮都点击一下,Service才会被销毁。也就是说,点击Stop Service按钮只会让Service停止,
    * 点击Unbind Service按钮只会让Service和Activity解除关联,一个Service必须要在既没有和任何Activity关联又处理停
    * 止状态的时候才会被销毁
     */
    /*
    *销毁
    *先点击一下Start Service按钮,再点击一下Bind Service按钮,
    *这样就将Service启动起来,并和Activity建立了关联。
    *然后点击Stop Service按钮后Service并不会销毁,再点击一下Unbind Service按钮,Service就会销毁了
     */
    @OnClick({R.id.start, R.id.stop,R.id.bind_service, R.id.unbind_service})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.start:
                //开启服务
                Intent intent = new Intent(this, MyService.class);
                startService(intent);
                break;
            case R.id.stop:
                //停止服务
                Intent intent2 = new Intent(this, MyService.class);
                stopService(intent2);
                break;
            case R.id.bind_service:
                //绑定服务
                Intent bindIntent = new Intent(this, MyService2.class);
                /*
                *第一个参数就是刚刚构建出的Intent对象
                * 第二个参数是前面创建出的ServiceConnection的实例
                * 第三个参数是一个标志位
                * 这里传入BIND_AUTO_CREATE表示在Activity和Service建立关联后自动创建Service,
                * 这会使得MyService中的onCreate()方法得到执行,但onStartCommand()方法不会执行
                 */
                bindService(bindIntent, connection, BIND_AUTO_CREATE);
                break;
            case R.id.unbind_service:
                //解绑服务
                unbindService(connection);
                break;
        }
    }
}


三:前台Service

前台Service和普通Service的区别就在于,它会一直有一个正在运行的图标在系统的状态栏显示,下拉状态栏后可以看到更加详细的信息,只需要在MyService的onCreat方法中做以下操作

 @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("TAG", "onCreate() executed");
        //1 创建通知布局对象     new  Notification.builder
        Notification.Builder builder = new Notification.Builder(this);
        //2 为对象设置3个必填项     setsmallIcon()小图标 ;  setContentTitle();通知标题   setContentText(); 主体内容
        builder.setSmallIcon(R.mipmap.ic_launcher).setContentTitle("唯品会").setContentText("11点11分两亿现金大放送");
        //3 为对象设置可选项  设置通知方式(声音,震动,闪光)  setDefaults(Notification.All)
        builder.setDefaults(Notification.DEFAULT_ALL);
        //4 为对象设置点击内容进行跳转                 setContentIntent(PedingIntent  );
//        Intent intent = new Intent(this,MainActivity2.class);
//        PendingIntent intent2 = PendingIntent.getActivity(this, 1, intent, PendingIntent.FLAG_UPDATE_CURRENT);
//        builder.setContentIntent(intent2);
        //5  通过Builder.build  创建出来Notification对象
        Notification build = builder.build();
        //6 创建NotificationManager 通知管理对象创建  getSystemService
        NotificationManager m = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
        //7   通过管理器进行通知  magager.notitiy(id, Notification);
        m.notify(1,build);
    }



清单文件

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

    <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>
        <service android:name=".MyService"></service>
        <service android:name=".MyService2"></service>
    </application>

</manifest>







  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值