Service的简单使用

目录

 

1.简介

2.建立服务

2.1新建

2.2重写方法

2.3启动服务:

2.4停止服务:

3.Activity和Service之间通信

3.1onBind方法。

3.2activity中:

3.3邦定Service

3.4解绑Service

4.前台服务的使用:

4.1在myService中:

4.2启动的话:

5.IntentService的使用:

5.1多线程的使用

5.2IntentServier的使用

5.3启动服务:

6.完整代码:

6.1MainActivity

6.1.1对应的XML:

6.2myService:

6.3MyIntentService :


1.简介

Service是一个服务,android的四大组件之一。他的使用也很简单。

2.建立服务

2.1新建

首先我们新建一个Sercve,点击右键New->Service->Service:

然后:

我们将服务命名为Myservice2,Exported属性表示是否允许除了当前程序之外其他的程序访问这个程序,Enabled表示是否启用这个服务。

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

    /**
     * Service 中唯一一个抽象方法
     * @param intent
     * @return
     */
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
}

这就是一个service了。

2.2重写方法

在重写几个方法:

/**
 * 创建服务的时候调用
 */
@Override
public void onCreate() {
    super.onCreate();
    Log.d("TAG", "onCreate");   

}

/**
 * 服务每次启动的时候调用
 * 服务一点启动立刻执行什么操作可以写在这里
 *
 * @param intent
 * @param flags
 * @param startId
 * @return
 */
@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");
}

 

2.3启动服务:

Intent intent = new Intent(MainActivity.this, MyService.class);
startService(intent);//开启服务

2.4停止服务:

Intent intent = new Intent(MainActivity.this, MyService.class);
stopService(intent);//关闭服务

点击开启服务的时候第一次是:onCreate  onStartCommand

开启第二次:onStartCommand

第三次:onStartCommand

.....

关闭的时候:onDestroy

3.Activity和Service之间通信

3.1onBind方法。

我们在myService中添加一个下载否方法

public class MyService extends Service {

    private DownloadBinder downloadBinder = new DownloadBinder();
/**
     * Service 中唯一一个抽象方法
     *
     * @param intent
     * @return
     */
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        Log.d("TAG", "onBind");
//        throw new UnsupportedOperationException("Not yet implemented");
        return downloadBinder;
    }
class DownloadBinder extends Binder {
    public void startDownload() {
        Log.d("TAG", "startDownload");
    }

    public int getProgress() {
        Log.d("TAG", "getProgress");
        return 0;
    }
}

}

 

3.2activity中:

private MyService.DownloadBinder downloadBinder;
private ServiceConnection connection = new ServiceConnection() {
    /**
     * 活动与服务邦定成功
     * @param name
     * @param service
     */
    @Override
    public void onServiceConnected(ComponentName name, IBinder service) {
        downloadBinder = (MyService.DownloadBinder) service;
        downloadBinder.startDownload();
        downloadBinder.getProgress();
    }

    /**
     * 活动与服务解除邦定成功
     * @param name
     */
    @Override
    public void onServiceDisconnected(ComponentName name) {

    }
};

3.3邦定Service

Intent intent = new Intent(MainActivity.this, MyService.class);
bindService(intent, connection, BIND_AUTO_CREATE);//BIND_AUTO_CREATE 活动与服务邦定成功后自动创建服务

3.4解绑Service

unbindService(connection);

点击绑定服务:onCreate-》onBind

第二次点击绑定服务:

解绑服务:onDestroy

4.前台服务的使用:

4.1在myService中:

/**
 * 创建服务的时候调用
 */
@Override
public void onCreate() {
    super.onCreate();
    Log.d("TAG", "onCreate");
    //前台服务
    Intent intent = new Intent(this, MainActivity.class);
    PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
    Notification build = new NotificationCompat.Builder(this)
            .setContentTitle("标题")
            .setContentText("文本")
            .setWhen(System.currentTimeMillis())
            .setSmallIcon(R.drawable.ic_launcher_background)
            .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
            .build();
    startForeground(1,build);

}

4.2启动的话:

不变。

5.IntentService的使用:

5.1多线程的使用

当我们在用多线程的时候就会在服务中开启一个子线程,

/**
 * 服务每次启动的时候调用
 * 服务一点启动立刻执行什么操作可以写在这里
 *
 * @param intent
 * @param flags
 * @param startId
 * @return
 */
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    Log.d("TAG", "onStartCommand");
    //开启子线程执行操作 避免耗时操作导致ANR
    new Thread(new Runnable() {
        @Override
        public void run() {
            //具体处理逻辑
            //但是必须使用 stopService() 或者 stopSelf()方法才能让服务停下来,所以想让一个服务完成操作停下来可以
            stopSelf();
        }
    }).start();
    return super.onStartCommand(intent, flags, startId);
}

stopSelf();当服务执行完毕后,停止服务。但是容易忘记这个操作,这时候Android提供了另一个IntentServier解决了这个问题。

5.2IntentServier的使用

package com.example.myservice;

import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.util.Log;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * TODO: Customize class - update intent actions, extra parameters and static
 * helper methods.
 */
public class MyIntentService extends IntentService {
    
    private static final String ACTION_FOO = "com.example.myservice.action.FOO";
    private static final String ACTION_BAZ = "com.example.myservice.action.BAZ";

   
    private static final String EXTRA_PARAM1 = "com.example.myservice.extra.PARAM1";
    private static final String EXTRA_PARAM2 = "com.example.myservice.extra.PARAM2";

    public MyIntentService() {
        super("MyIntentService");
        Log.d("TAG","MyIntentService");
    }

    /**
     * 处理具体逻辑
     * @param intent
     */
    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_FOO.equals(action)) {
                final String param1 = intent.getStringExtra(EXTRA_PARAM1);
                final String param2 = intent.getStringExtra(EXTRA_PARAM2);
                handleActionFoo(param1, param2);
            } else if (ACTION_BAZ.equals(action)) {
                final String param1 = intent.getStringExtra(EXTRA_PARAM1);
                final String param2 = intent.getStringExtra(EXTRA_PARAM2);
                handleActionBaz(param1, param2);
            }
        }
        Log.d("TAG","onHandleIntent:  "+Thread.currentThread().getId());
    }

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

 

5.3启动服务:

Intent intent = new Intent(MainActivity.this, MyIntentService.class);
startService(intent);

 

 

6.完整代码:

6.1MainActivity

package com.example.myservice;

import androidx.appcompat.app.AppCompatActivity;

import android.content.ComponentName;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.Bundle;
import android.os.IBinder;
import android.util.Log;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button start = findViewById(R.id.start);
        Button stop = findViewById(R.id.stop);
        Button bind = findViewById(R.id.bind);
        Button unbind = findViewById(R.id.unbind);
        Button startintent = findViewById(R.id.startintent);
        start.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, MyService.class);
                startService(intent);//开启服务
            }
        });
        stop.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, MyService.class);
                stopService(intent);//关闭服务
            }
        });
        bind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(MainActivity.this, MyService.class);
                bindService(intent, connection, BIND_AUTO_CREATE);//BIND_AUTO_CREATE 活动与服务邦定成功后自动创建服务
            }
        });
        unbind.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                unbindService(connection);
            }
        });
        startintent.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.d("TAG","线程ID:"+Thread.currentThread().getId());
                Intent intent = new Intent(MainActivity.this, MyIntentService.class);
                startService(intent);
            }
        });

    }

    private MyService.DownloadBinder downloadBinder;
    private ServiceConnection connection = new ServiceConnection() {
        /**
         * 活动与服务邦定成功
         * @param name
         * @param service
         */
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            downloadBinder = (MyService.DownloadBinder) service;
            downloadBinder.startDownload();
            downloadBinder.getProgress();
        }

        /**
         * 活动与服务解除邦定成功
         * @param name
         */
        @Override
        public void onServiceDisconnected(ComponentName name) {

        }
    };
}

6.1.1对应的XML:

<?xml version="1.0" encoding="utf-8"?>
<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:orientation="vertical"
    tools:context=".MainActivity">

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

    <Button
        android:id="@+id/stop"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="关闭服务" />
    <Button
        android:id="@+id/bind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Bind服务" />
    <Button
        android:id="@+id/unbind"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="unbind服务" />

    <Button
        android:id="@+id/startintent"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="开启intent服务" />


</LinearLayout>

6.2myService:

package com.example.myservice;

import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.graphics.BitmapFactory;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import androidx.core.app.NotificationCompat;

public class MyService extends Service {

    private DownloadBinder downloadBinder = new DownloadBinder();

    public MyService() {
        Log.d("TAG", "MyService");
    }

    /**
     * Service 中唯一一个抽象方法
     *
     * @param intent
     * @return
     */
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        Log.d("TAG", "onBind");
//        throw new UnsupportedOperationException("Not yet implemented");
        return downloadBinder;
    }

    /**
     * 创建服务的时候调用
     */
    @Override
    public void onCreate() {
        super.onCreate();
        Log.d("TAG", "onCreate");
        //前台服务
        Intent intent = new Intent(this, MainActivity.class);
        PendingIntent pi = PendingIntent.getActivity(this, 0, intent, 0);
        Notification build = new NotificationCompat.Builder(this)
                .setContentTitle("标题")
                .setContentText("文本")
                .setWhen(System.currentTimeMillis())
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setLargeIcon(BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher))
                .build();
        startForeground(1,build);

    }

    /**
     * 服务每次启动的时候调用
     * 服务一点启动立刻执行什么操作可以写在这里
     *
     * @param intent
     * @param flags
     * @param startId
     * @return
     */
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.d("TAG", "onStartCommand");
        //开启子线程执行操作 避免耗时操作导致ANR
        new Thread(new Runnable() {
            @Override
            public void run() {
                //具体处理逻辑
                //但是必须使用 stopService() 或者 stopSelf()方法才能让服务停下来,所以想让一个服务完成操作停下来可以
                stopSelf();
            }
        }).start();
        return super.onStartCommand(intent, flags, startId);
    }

    /**
     * 服务销毁的时候调用
     */
    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d("TAG", "onDestroy");
    }

    class DownloadBinder extends Binder {
        public void startDownload() {
            Log.d("TAG", "startDownload");
        }

        public int getProgress() {
            Log.d("TAG", "getProgress");
            return 0;
        }
    }


}

6.3MyIntentService :

package com.example.myservice;

import android.app.IntentService;
import android.content.Intent;
import android.content.Context;
import android.util.Log;

/**
 * An {@link IntentService} subclass for handling asynchronous task requests in
 * a service on a separate handler thread.
 * <p>
 * TODO: Customize class - update intent actions, extra parameters and static
 * helper methods.
 */
public class MyIntentService extends IntentService {
    // TODO: Rename actions, choose action names that describe tasks that this
    // IntentService can perform, e.g. ACTION_FETCH_NEW_ITEMS
    private static final String ACTION_FOO = "com.example.myservice.action.FOO";
    private static final String ACTION_BAZ = "com.example.myservice.action.BAZ";

    // TODO: Rename parameters
    private static final String EXTRA_PARAM1 = "com.example.myservice.extra.PARAM1";
    private static final String EXTRA_PARAM2 = "com.example.myservice.extra.PARAM2";

    public MyIntentService() {
        super("MyIntentService");
        Log.d("TAG","MyIntentService");
    }

    /**
     * Starts this service to perform action Foo with the given parameters. If
     * the service is already performing a task this action will be queued.
     *
     * @see IntentService
     */
    // TODO: Customize helper method
    public static void startActionFoo(Context context, String param1, String param2) {
        Intent intent = new Intent(context, MyIntentService.class);
        intent.setAction(ACTION_FOO);
        intent.putExtra(EXTRA_PARAM1, param1);
        intent.putExtra(EXTRA_PARAM2, param2);
        context.startService(intent);
    }

    /**
     * Starts this service to perform action Baz with the given parameters. If
     * the service is already performing a task this action will be queued.
     *
     * @see IntentService
     */
    // TODO: Customize helper method
    public static void startActionBaz(Context context, String param1, String param2) {
        Intent intent = new Intent(context, MyIntentService.class);
        intent.setAction(ACTION_BAZ);
        intent.putExtra(EXTRA_PARAM1, param1);
        intent.putExtra(EXTRA_PARAM2, param2);
        context.startService(intent);
    }

    /**
     * 处理具体逻辑
     * @param intent
     */
    @Override
    protected void onHandleIntent(Intent intent) {
        if (intent != null) {
            final String action = intent.getAction();
            if (ACTION_FOO.equals(action)) {
                final String param1 = intent.getStringExtra(EXTRA_PARAM1);
                final String param2 = intent.getStringExtra(EXTRA_PARAM2);
                handleActionFoo(param1, param2);
            } else if (ACTION_BAZ.equals(action)) {
                final String param1 = intent.getStringExtra(EXTRA_PARAM1);
                final String param2 = intent.getStringExtra(EXTRA_PARAM2);
                handleActionBaz(param1, param2);
            }
        }
        try {
            Thread.sleep(10*1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Log.d("TAG","onHandleIntent:  "+Thread.currentThread().getId());
    }

    /**
     * Handle action Foo in the provided background thread with the provided
     * parameters.
     */
    private void handleActionFoo(String param1, String param2) {
        // TODO: Handle action Foo
        throw new UnsupportedOperationException("Not yet implemented");
    }

    /**
     * Handle action Baz in the provided background thread with the provided
     * parameters.
     */
    private void handleActionBaz(String param1, String param2) {
        // TODO: Handle action Baz
        throw new UnsupportedOperationException("Not yet implemented");
    }

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

转发表明出处https://blog.csdn.net/qq_35698774/article/details/107595940

点击下载

android互助群:

  • 6
    点赞
  • 27
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

大不懂

码字不易,一块也是爱,么么

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值