标签:android开发
package com.example.android_intentservice; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; public class ServiceAndIntentService extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } //1.启动普通Service按钮方法 public void startService(View source) { Intent intent = new Intent(this,MyService.class); //创建需要启动的service的Intent startService(intent); //启动Intent指定的Service } //2.启动IntentService按钮方法 public void startIntentService(View source) { Intent intent = new Intent(this,MyIntentService.class); startService(intent); } }
...... <Button android:onClick="startService" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="启动普通Service" /> <Button android:onClick="startIntentService" android:layout_width="186dp" android:layout_height="wrap_content" android:text="启动IntentService" />
package com.example.android_intentservice; import android.app.Service; import android.content.Intent; import android.os.IBinder; public class MyService extends Service { @Override public IBinder onBind(Intent intent) { return null; } //当启动Service,调用该方法执行相应代码 @Override public int onStartCommand(Intent intent, int flags, int startId) { long endTime = System.currentTimeMillis()+20*1000; System.out.println("onStart"); while(System.currentTimeMillis()<endTime) { synchronized(this) { try { wait(endTime-System.currentTimeMillis()); }catch(Exception e) { } } } System.out.println("---普通Service耗时任务执行完成---"); return START_STICKY; } }
package com.example.android_intentservice; import android.app.IntentService; import android.content.Intent; public class MyIntentService extends IntentService { public MyIntentService() { super("MyIntentService"); } //IntentService会使用单独的线程来执行方法的代码 @Override protected void onHandleIntent(Intent intent) { //该方法内可以执行任何耗时任务,比如下载文件等,此处只是让线程暂停20s long endTime = System.currentTimeMillis()+20*1000; System.out.println("onStart"); while(System.currentTimeMillis()<endTime) { synchronized(this) { try { wait(endTime-System.currentTimeMillis()); }catch(Exception e) { } } } System.out.println("---IntentService耗时任务执行完成---"); } }
<application android:allowBackup="true" android:icon="@drawable/ic_launcher" android:label="@string/app_name" android:theme="@style/AppTheme" > <activity .......... </activity> <!--配置service--> <service android:name=".MyService"/> <service android:name=".MyIntentService"/> </application>
Android学习笔记二十五.Service组件入门(三)使用IntentService
标签:android开发
原文地址:http://blog.csdn.net/u012637501/article/details/42834013