您的位置:首页 > 移动开发 > Android开发

Android Service使用技巧

2016-07-25 08:31 399 查看

Android Service 使用技巧

使用前台服务

使用IntentService

使用前台服务

前台服务与普通服务的区别。普通服务在当系统出现内存不足的情况时,就有可能会回收掉正在后台运行的服务,而前台服务会一直保持运行状态,而且会在系统的状态栏一直显示一个正在运行的图标。下拉状态栏后可以看到详细的信息。

package com.example.scott.frontservice;

import android.annotation.TargetApi;
import android.app.Notification;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Build;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.util.Log;

/**
* Created by SCOTT on 2016/7/24.
*/
public class MyService extends Service {
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}

@TargetApi(Build.VERSION_CODES.JELLY_BEAN)
@Override
public void onCreate() {
super.onCreate();
Intent notificationIntent = new Intent(this,MainActivity.class);
PendingIntent pendingIntent = PendingIntent.getActivity(this,0,notificationIntent,0);
Notification notification = new Notification.Builder(this)
//没加setSmallIcon()方法就不显示设置的通知图标
.setSmallIcon(R.drawable.ic_launcher)
.setContentTitle("scott")
.setContentText("la la la")
.setContentIntent(pendingIntent)
.build();
//在这里用startForeground()代替原理通知中的notify()的方法。
startForeground(1, notification);
Log.d("MyService","onCreate executed");
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
return super.onStartCommand(intent, flags, startId);
}

@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyService","onDestroy executed");
}
}


调用startForeground() 就可以让MyService变成一个前台服务,

如图:





使用IntentService

为什么要使用IntentService 。比如我们想执行一个计时的操作,在计时完成后服务自动关闭。正常的做法是在onStartCommand()中创建一个线程去处理集体的耗时的操作,然后再线程处理完结束的时候 加上stopSelf();

new Thread(){

public void run(){

//处理具体的逻辑

stopSelf();

}

}


现在Android专门提供了一个IntentService类来完成上面的操作。

public class MyIntrentService extends IntentService {

public MyIntrentService(){
super("MyIntentService");//调用父类中的有参构造函数
}

@Override
protected void onHandleIntent(Intent intent) {
Log.d("MyIntentService","Thread id is"+Thread.currentThread().getId());

}

@Override
public void onDestroy() {
super.onDestroy();
Log.d("MyIntentService","onDestroy executed");
}
}


启用Service 后的调试日志输出结果如图



日志中主线程与服务的线程不是同一个线程。然后服务运行结束后就自动停止了。

好了就到这里了,以后遇到别的继续补充。

关注微信公众号,每天都有优质技术文章,搞笑GIF图片推送哦。



2016-7-25

Scott
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android Service