使用总结
- Service 的生命周期相对与Activity 比较简单,只有3个分别为:onCreate、onStartCommand各onDestory。
- 在项目的任何位置调用了Context的startService() 函数,相应的服务就会开启。
首次创建时会调用onCreate方法,然后会回调onStartCommand()函数。 - 服务开启后一直保持运行,直到调用stopService()或stopSelf(),服务会停止。
- 每调用一次startService(),onStartCommand(),就会运行一次,但实际上服务只会创建一个实例。
- service 是运行在UI 线程中,不要直接做耗时操作,否则是新那些子线程。
service 创建
public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
doMyJob();
return super.onStartCommand(intent, flags, startId);
}
/**模拟耗时方法*/
private void doMyJob() {
new Thread() {
@Override
public void run() {
super.run();
Log.i("tag", "在service中工作");
}
}.start();
}
}
service 注册
<service android:name=".MyService" />
service 调用
val intent=Intent(activity, MyService::class.java)
activity.startService(intent)
运行结果:
image.png
IntentService 使用总结
IntentService 是 Android 提供直接运行在子线程的Service.这个只会只会执行一次,执行完后会自动高stopSelf自我销毁。
IntentService 创建
public class MyIntentService extends IntentService {
public MyIntentService( ) {
super("");
}
/**
* Creates an IntentService. Invoked by your subclass's constructor.
*
* @param name Used to name the worker thread, important only for debugging.
*/
public MyIntentService(String name) {
super(name);
}
@Override
protected void onHandleIntent(@Nullable Intent intent) {
Log.i("tag","C当前线程是"+ Thread.currentThread().getName());
}
}
IntentService 注册
<service android:name=".MyIntentService" />
IntentService 调用
activity.startService(Intent(activity, MyIntentService::class.java))
运行结果:
image.png
运行在前台的Service
- startForeground 函数将服务设置为前台服务。
private void showNotification() {
NotificationCompat.Builder builder = new NotificationCompat.Builder(this.getApplication())
.setSmallIcon(R.mipmap.ic_launcher)
.setContentTitle("标题")
.setContentText("我是内容");
//创建通知被点击时触发 Intent
Intent resultIntent = new Intent(this, MainActivity.class);
//创建任务栈Builder
TaskStackBuilder taskStackBuilder = TaskStackBuilder.create(this);
taskStackBuilder.addParentStack(MainActivity.class);
taskStackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent = taskStackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT);
builder.setContentIntent(resultPendingIntent);
NotificationManager notificationManager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
//构建通知
final Notification notification = builder.build();
//显示通知
notificationManager.notify(NOTIVICAIONT_ID, notification);
//启动为前台服务
startForeground(NOTIVICAIONT_ID, notification);
}
网友评论