栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

IntentService-Android

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

IntentService-Android

IntentService 是 Service 的子类,继承于 Service 类,用于处理后台异步请求任务。用于处理后台长时间的耗时操作,如:下载文件、播放音乐。用完自动结束。如果是普通的Service ,需要使用stopSelf()。

使用方法

IntentService 是抽象类,所以在实际使用中,我们需要创建一个 IntentService 子类来具体实现

  1. 创建 IntentService 子类,并在清单文件中注册。
  2. 在 Activity 中通过调用 startService(Intent) 方法发送任务请求。

activity_intent_service.xml



    

MyIntentService.java

public class MyIntentService extends IntentService {


    private static final String TAG = "MyIntentService";


    public MyIntentService() {
        super("MyIntentService");
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Log.i(TAG, "onHandleIntent: "+Thread.currentThread().getName());

    }

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

AndroidManifest.xml

    

        

IntentServiceActivity.java

public class IntentServiceActivity extends AppCompatActivity {
    private Button bt_start_service;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intent_service);
        bt_start_service = (Button) findViewById(R.id.bt_start_service);
        bt_start_service.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(IntentServiceActivity.this, MyIntentService.class);
                startService(intent);
            }
        });
    }
}

模拟下载任务

IntentServiceActivity.java

public class IntentServiceActivity extends AppCompatActivity {
    private Button bt_start_service;
    private ProgressBar progressbar;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_intent_service);
        bt_start_service = (Button) findViewById(R.id.bt_start_service);
        progressbar = (ProgressBar) findViewById(R.id.progressbar);
        bt_start_service.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //用于创建 Messenger,接收 IntentService 回复的消息
                MessengerHandler messengerHandler = new MessengerHandler(IntentServiceActivity.this);

                //模拟 whq 做下载动作
                Intent intent = new Intent(IntentServiceActivity.this, downLoadIntentService.class);
                intent.setAction(downLoadIntentService.DOWNLOAD_ACTION);
                intent.putExtra(downLoadIntentService.TEST_AUTHOR, "whq");
                //将 Messenger 传递给 IntentService,让其回复消息回来
                intent.putExtra(downLoadIntentService.TEST_MESSENGER, new Messenger(messengerHandler));
                startService(intent);
            }
        });
    }


    
    public static class MessengerHandler extends Handler {
        private WeakReference weakReference;

        MessengerHandler(IntentServiceActivity activity) {
            weakReference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            super.handleMessage(msg);
            //msg 为 IntentService 回复的消息,包含 Bundle 等信息。
            Bundle bundle = msg.getData();
            //获取 IntentService 传递过来的 下载进度 参数
            int downloadProgressBarValue = bundle.getInt(downLoadIntentService.DOWNLOAD_PROGRESS_VALUE_KEY);

            //将下载进度设置成 ProgressBar 的进度,显示出来。
            IntentServiceActivity activity = weakReference.get();
            if (activity != null && !activity.isFinishing()) {
                activity.progressbar.setProgress(downloadProgressBarValue);
            }

        }
    }
}

activity_intent_service.xml



    

downLoadIntentService.java

public class downLoadIntentService extends IntentService {

    private static final String TAG = "downLoadIntentService";

    public static final String DOWNLOAD_ACTION = "DOWNLOAD_ACTION";
    public static final String READ_ACTION = "READ_ACTION";
    public static final String TEST_AUTHOR = "TEST_AUTHOR";
    public static final String TEST_MESSENGER = "TEST_MESSENGER";
    public static final String DOWNLOAD_PROGRESS_VALUE_KEY = "DOWNLOAD_PROGRESS_VALUE";



    public downLoadIntentService() {
        super(TAG);
    }

    @Override
    protected void onHandleIntent(@Nullable Intent intent) {
        Log.i(TAG, "onHandleIntent: "+Thread.currentThread().getName());
        if (intent != null) {
            final String action = intent.getAction();
            String author = intent.getExtras().getString(TEST_AUTHOR);

            //模拟下载动作
            if (DOWNLOAD_ACTION.equals(action)) {
                for (int i = 0; i <= 6; i++) {
                    try {
                        //线程等待1s,模拟耗时操作
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    Log.e(TAG, author + " " + action + " " + i);
                    //获取从 Activity 传入的 Messenger
                    Messenger messenger = (Messenger) intent.getExtras().get(TEST_MESSENGER);
                    //新建消息,设置下载进度参数
                    Message msg = new Message();
                    Bundle bundle = new Bundle();
                    bundle.putInt(DOWNLOAD_PROGRESS_VALUE_KEY, i);
                    msg.setData(bundle);
                    try {
                        //回复消息
                        messenger.send(msg);
                    } catch (RemoteException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        
    }

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


AndroidManifest.xml

        

        



点击一次就会调用onStartCommand一次。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/936606.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号