设为首页 加入收藏

TOP

Android_实用技术(3)—— Service简析(Ⅲ)(二)
2017-10-13 09:43:03 】 浏览:6407
Tags:Android_ 实用技术 Service 简析
onDestroy();     Log.d(
"MyIntentService", "onDestroy executed");   } }

  以上代码做了几件事:

  1、提供了一个无参的构造方法,并且调用了父类的有参构造函数(这个就不需要我说为什么了吧);

  2、子类实现父类的onHandleIntent()抽象方法,这个方法好就好在,它是一个已经运行在子线程中的方法。也就是说,服务调用了它,那么执行的逻辑就如同Thread子线程。

        onHandleIntent = Thread().start() + stopSelf()

  3、onHandleIntent()执行完后会销毁服务?会selfStop()?接着往下看代码。

----------------------------------------------------------------------------------------------------------------------------------------

  (2)在xml文件中,创建一个MyIntentService服务按钮:

<Button
  android:id="@+id/start_intent_service"
  android:layout_width="match_parent"
  android:layout_height="wrap_content"
  android:text="@string/intent_service"/>

  (3)接下来,修改MainActivity中的代码:

public class MainActivity extends Activity {
  @Override   
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);     setContentView(R.layout.activity_main);     Button startIntentService
= (Button) super.findViewById(R.id.start_intent_service);     startIntentService.setOnClickListener(new View.OnClickListener() {
      @Override       
public void onClick(View v) {         Log.d("MyIntentService", "MainActivity Thread id is " + Thread.currentThread().getId()); // 查看主线程的id         Intent intentService = new Intent(getBaseContext(), MyIntentService.class);         startService(intentService);       }     });   } }

  (4)最后,在AndroidMainfest中注册服务:

<service android:name=".MyIntentService" />

【结果】:直接看一下代码执行的效果。

  从打出的LOG可以看出:

  (1)MyIntentService和MainActivity所在进程的id不一样的;

  (2)onHandleIntent()方法在执行完逻辑后确实销毁了服务,效果等同于stopSelf()。

  从上面的分析可以看出onHandleIntent()方法确实相当的好用!

首页 上一页 1 2 下一页 尾页 2/2/2
】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
上一篇[RxJava^Android]项目经验分享 --.. 下一篇Android应用开发常用方法封装(一..

最新文章

热门文章

Hot 文章

Python

C 语言

C++基础

大数据基础

linux编程基础

C/C++面试题目