intentService是一种异步(子线程)、自动停止的服务,这个例子测试IntentService的特征
下面是核心代码:
MyIntentService
public class MyIntentService extends IntentService {
/**
*构造方法必须这样写
*/
public MyIntentService() {
super("MyIntentService");//调用父类有参的
}
/**
* 子线程
*/
@Override
protected void onHandleIntent(Intent intent) {
//打印当前线程的id,证明子线程的存在
Log.d("1", "MyIntentService当前线程的id"+Thread.currentThread().getId());
}
/**
* 自动结束
*/
@Override
public void onDestroy() {
super.onDestroy();
Log.i("i", "onDestroy执行了");//证明会不会自动停止
}
}//class
主清单注册
<service
android:name="com.zhh.android.MyIntentService"
></service>
MainActivity中
public class MainActivity extends Activity implements OnClickListener{
private Button btn_intent_Service;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn_intent_Service=(Button) findViewById(R.id.start_inservice);
btn_intent_Service.setOnClickListener(this);
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.start_inservice:
Log.i("1", "activity当前线程的id"+Thread.currentThread().getId());
Intent intentService=new Intent(this, MyIntentService.class);
startService(intentService);
break;
}
}
}//class
如果没有明白,下载我的例子
http://download.csdn.net/detail/zhaihaohao1/8291833