VMForegroundService.java 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960
  1. package com.vmloft.develop.daemon.services;
  2. import android.app.Notification;
  3. import android.app.PendingIntent;
  4. import android.app.Service;
  5. import android.content.Intent;
  6. import android.os.IBinder;
  7. import android.support.v7.app.NotificationCompat;
  8. import android.util.Log;
  9. import com.vmloft.develop.daemon.MainActivity;
  10. import com.vmloft.develop.daemon.R;
  11. /**
  12. * 正常的系统前台进程,会在系统通知栏显示一个Notification通知图标,因为这个通知的关系,应用的进程优先级是比较高的,
  13. * 一般系统的内存回收是无法杀死的
  14. *
  15. * Created by lzan13 on 2017/3/7.
  16. */
  17. public class VMForegroundService extends Service {
  18. private final static String TAG = VMForegroundService.class.getSimpleName();
  19. // 通知栏发送的通知 id
  20. private final static int NOTIFY_ID = 1000;
  21. @Override public void onCreate() {
  22. Log.i(TAG, "VMForegroundService->onCreate");
  23. super.onCreate();
  24. }
  25. @Override public int onStartCommand(Intent intent, int flags, int startId) {
  26. Log.i(TAG, "VMForegroundService->onStartCommand");
  27. // 创建个通知,这样可以提高服务的优先级
  28. NotificationCompat.Builder builder = new NotificationCompat.Builder(this);
  29. builder.setSmallIcon(R.mipmap.ic_launcher);
  30. builder.setContentTitle("这是一条前台通知");
  31. builder.setContentText("这是一条前台通知,表示当前程序有一个前台服务在运行");
  32. builder.setContentInfo("前台服务");
  33. builder.setWhen(System.currentTimeMillis());
  34. Intent activityIntent = new Intent(this, MainActivity.class);
  35. PendingIntent pendingIntent = PendingIntent.getActivity(this, 1, activityIntent,
  36. PendingIntent.FLAG_UPDATE_CURRENT);
  37. builder.setContentIntent(pendingIntent);
  38. Notification notification = builder.build();
  39. // 开启前台通知
  40. startForeground(NOTIFY_ID, notification);
  41. return super.onStartCommand(intent, flags, startId);
  42. }
  43. @Override public IBinder onBind(Intent intent) {
  44. // TODO: Return the communication channel to the service.
  45. throw new UnsupportedOperationException("onBind 未实现");
  46. }
  47. @Override public void onDestroy() {
  48. Log.i(TAG, "VMForegroundService->onDestroy");
  49. super.onDestroy();
  50. }
  51. }