Android开发Android技术知识

Activity之Service

2019-09-28  本文已影响0人  拨云见日aaa

一、五种进程

(前三种进程一般不会被杀死)

二、Service生命周期

三、用startService方法开启服务

用startService方法打开服务时,即使关闭了app,service依旧运行

(1)用法介绍
(2)代码示例

MyService代码

public class MyService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        Log.i("test","onBind");
        return null;
    }
    public void onCreate(){
        super.onCreate();
        Log.i("test","onCreate");
    }

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

    public void onDestroy(){
        super.onDestroy();
        Log.i("tset","onDestroy");
    }
}

Activity代码

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }
    public void click(View view){
        Intent intent=new Intent(this,MyService.class);
        startService(intent);
    }
}

manifest注册

<service android:name=".MyService"></service>
运行结果:
多次点击开启服务的运行效果

四、bindService打开服务

(1)使用介绍
(2)代码示例
//Service代码和上面一样
//注册也一样
public class MainActivity extends AppCompatActivity {

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

    public void click(View view) {
        Intent intent = new Intent(this, MyService.class);
        bindService(intent, connection, BIND_AUTO_CREATE);
    }
    ServiceConnection connection=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {

        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {

        }
    };
}
运行结果:
bind Service开启服务

五、Service和Activity之间数据交互

(1)用法介绍
(2)代码示例

MyService代码

public class MyService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        Log.i("test","onBind");
        return new MyBInder();
    }
    public void test(){
        Log.i("test","Activity调用我了");
    }
    class MyBInder extends Binder{
        public void binderTest(){
            test();
        }
    }
}
运行效果
Activity调用Service方法

六、前台服务

前台服务就像通知一样会在前台提示用户正在运行中,像音乐播放器那样,前台服务更不容易被系统杀死

(1)用法介绍

它和发通知非常像,构建好Notification以后不用NotificationManager发送出去,而是调用start'Foreground
(Android8.0以后发送通知构建通知渠道NotificationChannel)

(2)代码示例
import androidx.core.app.NotificationCompat;

public class MyService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        Log.i("test","onBind");
        return new MyBInder();
    }
    public void onCreate(){
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O) {//但Android版本大于8.0以后构建通知渠道
            NotificationChannel channel = new NotificationChannel("1", "hello", NotificationManager.IMPORTANCE_HIGH);//第一个参数channel的id,第二个channel的名字,第三个参数channel的优先级
            NotificationManager manager=(NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            manager.createNotificationChannel(channel);
        }
      NotificationCompat.Builder builder=new NotificationCompat.Builder(this,"1");//这里需要用NotificationCompat的builder
      builder.setSmallIcon(R.mipmap.hhhh);
      builder.setContentTitle("hello");
      builder.setContentText("我一直运行中");
      builder.setTicker("hello,看我,快看我");
      Notification notification= builder.build();
      startForeground(1,notification);
    }
    public void test(){
        Log.i("test","Activity调用我了");
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("test","onStartCommand");
       return super.onStartCommand(intent,flags,startId);
    }

    public void onDestroy(){
        super.onDestroy();
        Log.i("tset","onDestroy");
    }
    class MyBInder extends Binder{
        public void binderTest(){
            test();
        }
    }
}
运行结果
前台服务

七、调用系统的服务

(1)常用的系统服务
系统常用的服务
(2)练习

使用AlarmManager实现定时器的功能通过调用AlarmManager.set()功能,传三个参数进去(工作类型,定时任务触发的时间,pendingIntent对象)

public class MyService extends Service {

    @Override
    public IBinder onBind(Intent intent) {
        Log.i("test","onBind");
        return new MyBInder();
    }
    public void onCreate(){
    }
    public void test(){
        Log.i("test","Activity调用我了");
    }
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("test","onStartCommand");
        AlarmManager alarmManager=(AlarmManager) getSystemService(ALARM_SERVICE);
        long time= SystemClock.elapsedRealtime()+200;
        Intent intent2=new Intent("hello");
        PendingIntent intent1=PendingIntent.getBroadcast(this,1,intent2,PendingIntent.FLAG_UPDATE_CURRENT);
        alarmManager.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,time,intent1);
       return super.onStartCommand(intent,flags,startId);
    }

    public void onDestroy(){
        super.onDestroy();
        Log.i("tset","onDestroy");
    }
    class MyBInder extends Binder{
        public void binderTest(){
            test();
        }
    }
}

注册一个广播接收者,代码:

//当定时器触发时调用这个广播,开启Service
class  MyBroadcastReceiver extends BroadcastReceiver{
        public void onReceive(Context context, Intent intent){
            Intent intent1=new Intent(context,MyService.class);
            startService(intent1);
        }
    }

运行结果:
一直重复Log开始,Service你、会被一直开启


Service重复打开

八、IntentService

IntentService是一个异步的可以自己关闭的Service

(1)使用方法
(2)代码示例

IntentService的代码

public class MyIntentService extends IntentService {
    public MyIntentService(){
        super("MyIntentService");
    }
    public void onHandleIntent(Intent intent){
       for(int i=0;i<10;i++){
           Log.i("test","耗时操作");
       }
    }
    public void onDestroy(){
        Log.i("test","自动停止");
    }
}
运行结果:
执行和自动结束
上一篇 下一篇

猜你喜欢

热点阅读