Mainactivity:
public class MainActivity extends Activity {
int count=0;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public void clickBtn(View view)
{
int id=view.getId();
if(id==R.id.btn1)
{
Intent intent=new Intent();
intent.setAction("android.intent.action.MyIntentService");
intent.putExtra("task_name", "任务"+count++);
startService(intent);
}else if(id==R.id.btn2)
{
Intent intent=new Intent();
intent.setAction("android.intent.action.MyIntentService");
stopService(intent);
}
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
IntentService:
public class MyIntentService extends IntentService{
public MyIntentService()
{
super("MyIntentService");
}
public MyIntentService(String name) {
super(name);
}
@Override
public void onCreate() {
Log.i("test", "服务创建");
super.onCreate();
}
@Override
public void onDestroy() {
Log.i("test", "服务销毁");
super.onDestroy();
}
//IntentService内部会实现一个请求队列。所有请求的Intent会保存在队列中
//使用一个工作线程挨个处理,所以不会产生多线程问题。当队列处理完毕,服务会自动终止。为了避免干扰它的工作线程
//最好不要调用stopService方法,而是由服务自己自然终止
@Override
protected void onHandleIntent(Intent intent) {
String task_name=intent.getStringExtra("task_name");
for(int i=0;i<20;i++)
{
Log.i("test", task_name+":"+i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
manifest.xml:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=com.intentservice.MainActivity"
android:label="@string/app_name" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name="com.intentservice.MyIntentService" >
<intent-filter>
<action android:name="android.intent.action.MyIntentService"/>
</intent-filter>
</service>
</application>
XMl:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity" >
<Button android:id="@+id/btn1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="clickBtn"
android:text="启动计数"
/>
<Button android:id="@+id/btn2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:onClick="clickBtn"
android:text="停止"
/>
</LinearLayout>