Android Service在后台一直运行监测案例

1、定义 Service

package com.example.scangundemo_as;

import android.app.ActivityManager;
import android.app.Service;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.res.Resources;
import android.os.IBinder;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;

import java.util.List;
import java.util.logging.Logger;

public class APPService extends Service {

    private static final String packageName = "com.example.scangundemo_as";
    private static final String className = "MainActivity";

    @Override
    public void onCreate() {
        super.onCreate();
        Log.i("Service","-------create-------");
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.i("Service","-------onDestroy-------");
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("Service","-----service onStartCommand...");
        new Thread(){
            @Override
            public void run() {
                super.run();
                while(true){
                    try {
                        Thread.sleep(5000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    //一直运行
                    boolean isRunningForeground = isRunningForeground(APPService.this);
//                    Log.i("Service","-----service isRunningForeground="+isRunningForeground);
                    if(!isRunningForeground){
                        Log.i("Service","-----start activity-----");
                        startActivityTool(APPService.this);
                    }
                }
            }
        }.start();
        return super.onStartCommand(intent, flags, startId);
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }
public static boolean isRunningForeground (Context context) { ActivityManager am = (ActivityManager)context.getSystemService(Context.ACTIVITY_SERVICE); ComponentName cn = am.getRunningTasks(1).get(0).topActivity; String currentPackageName = cn.getPackageName(); if(!TextUtils.isEmpty(currentPackageName) && currentPackageName.equals(context.getPackageName())) { return true ; } return false ; } public static void startActivityTool(Context context){ Intent intent = new Intent(); intent.setClass(context, MainActivity.class); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK ); context.startActivity(intent); } }

2、启动Service

  //启动service
Intent intent = new Intent(this,APPService.class);
startService(intent);

3、清单文件AndroidManifest.xml 声明Service

  <service android:name=".APPService" android:enabled="true" android:exported="true">
  </service>

 

posted @ 2020-07-21 18:41  大空白纸  阅读(905)  评论(0编辑  收藏  举报