service:服务。
- 开始服务
- 停止服务
- 通信,绑定活动
- 通信,解绑活动
新建service
package com.example.bbw.servicesdemo;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.support.annotation.IntDef;
import android.util.Log;
public class MyService extends Service {
private DownloadBinder binder = new DownloadBinder();
public MyService() {
}
@Override
public void onCreate() {
Log.d("MyService","created");
super.onCreate();
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
Log.d("MyService","start");
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
Log.d("MyService","stop");
super.onDestroy();
}
@Override
public IBinder onBind(Intent intent) {
return binder;
}
class DownloadBinder extends Binder{
public void startLoad(){
Log.d("MyService","start Download");
}
public int getProgress(){
Log.d("myservice","getProgress");
return 0;
}
}
}
布局文件
<Button
android:id="@+id/startService"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="startService"/>
<Button
android:id="@+id/stopService"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="stopService"/>
<Button
android:id="@+id/bindService"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="bindService"/>
<Button
android:id="@+id/unBindService"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="unBindService"/>
开始服务
startServices.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent startIntent = new Intent(getApplicationContext(),MyService.class);
startService(startIntent);
}
});
结束服务
stopServices.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent stopIntent = new Intent(getApplicationContext(),MyService.class);
stopService(stopIntent);
}
});
网友评论