16 Service

简单练习:

一、创建Started service


1. 继承IntentService


package com.test;
import android.app.IntentService;
import android.content.Intent;
import android.widget.Toast;
import androidx.annotation.Nullable;
public class HelloIntentService extends IntentService {
    public HelloIntentService(){
        super("HelloIntentService");
    }
    @Override
    public int onStartCommand(@Nullable Intent intent, int flags, int startId) {
        Toast.makeText(this,"service start.......",Toast.LENGTH_LONG).show();
        return super.onStartCommand(intent, flags, startId);
    }
    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        long endTime = System.currentTimeMillis() + 5 * 1000;
        while(System.currentTimeMillis()<endTime){
            synchronized (this){
                try {
                    wait(endTime-System.currentTimeMillis());
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

2.继承Service:


package com.test;

import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.text.format.Time;
import android.util.Log;

import androidx.annotation.Nullable;


public class HIntService extends Service {



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

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Time time=new Time();
        time.setToNow();
        String format = time.format("%Y-%m-%d %H:%M:%S");
        Log.i("HIntService",format);
        return START_STICKY;
    }
}

调用


package com.test;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.widget.Button;

import androidx.annotation.Nullable;

import com.example.textmethod.R;

public class newActivity  extends Activity {

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

        Button btn=findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {

               startService(new Intent(newActivity.this,HIntService.class));
            }
        });
    }
}




二、创建bound Service

1 继承binder

package com.test;

import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.text.format.Time;
import android.util.Log;

import androidx.annotation.Nullable;

import java.util.Random;


public class HIntService extends Service {
LocalBinder localBinder=new LocalBinder();
Random random=new Random();
class LocalBinder extends Binder{

    public HIntService getService(){
        return HIntService.this;

    }
}

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return localBinder;
    }
public int getRadmon(){
    return random.nextInt(100);
}
}
package com.test;

import android.app.Activity;
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.text.format.Time;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.example.textmethod.R;

public class newActivity  extends Activity {
    HIntService.LocalBinder localBinder;
    HIntService hIntService;
    boolean bond=false;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_main);

        Button btn=findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (bond){
                    int num = hIntService.getRadmon();
                    Toast.makeText(newActivity.this,"随机数"+num,Toast.LENGTH_LONG).show();
                }


            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent=new Intent(newActivity.this,HIntService.class);
        bindService(intent,conn, Context.BIND_AUTO_CREATE);
    }

    public ServiceConnection conn=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            localBinder= (HIntService.LocalBinder) iBinder;
             hIntService = localBinder.getService();
            hIntService.getRadmon();
            bond=true;


        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            if (bond){
                unbindService(conn);
                bond=false;
            }

        }
    };

    @Override
    protected void onStop() {
        super.onStop();
        if (bond){
            unbindService(conn);
            bond=false;
        }
    }
}

 

2使用Messager

package com.test;

import android.app.IntentService;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.text.format.Time;
import android.util.Log;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.util.Random;


public class HIntService extends Service {

    static final int HELL_WORLD = 1;

    class MessengHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case HELL_WORLD:
                    Toast.makeText(getApplicationContext(), "helllo world", Toast.LENGTH_LONG).show();
                    break;
                default:
                    super.handleMessage(msg);
            }

        }
    }

    final Messenger messenger = new Messenger(new MessengHandler());


    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        Toast.makeText(getApplicationContext(), "Binding", Toast.LENGTH_LONG).show();
        return messenger.getBinder();
    }
}

package com.test;

import android.app.Activity;
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.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.text.format.Time;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

import androidx.annotation.Nullable;

import com.example.textmethod.R;

public class newActivity  extends Activity {
    Messenger messenger=null;
    boolean bond=false;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.new_main);

        Button btn=findViewById(R.id.btn);
        btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (!bond)
                    return;
                Message msg=Message.obtain(null,HIntService.HELL_WORLD,0,0);
                try {
                    messenger.send(msg);
                } catch (RemoteException e) {
                    e.printStackTrace();
                }


            }
        });
    }

    @Override
    protected void onStart() {
        super.onStart();
        Intent intent=new Intent(newActivity.this,HIntService.class);
        bindService(intent,conn, Context.BIND_AUTO_CREATE);
    }

    public ServiceConnection conn=new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName componentName, IBinder iBinder) {
            messenger=new Messenger(iBinder);

            bond=true;


        }

        @Override
        public void onServiceDisconnected(ComponentName componentName) {
            if (bond){
                unbindService(conn);
                messenger=null;
                bond=false;
            }

        }
    };

    @Override
    protected void onStop() {
        super.onStop();
        if (bond){
            unbindService(conn);
            bond=false;
        }
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值