Android开发之旅一监听程序的前后台运行状态

package com.mobile.utilitys; 
import java.util.List;

import android.app.ActivityManager;
import android.app.ActivityManager.RunningAppProcessInfo;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.os.IBinder;
import android.os.Message;

import com.consumer.asmart.service.FloatWinService;
import com.mobile.activity.MainActivity;
import com.mobile.consumer.R;

/**
 * 监听程序是否在前后台运行Service
 * 监听程序是否在前后台运行Service
 * 
 * joke
 * 
 */
public class AppStatusService extends Service{
    private static final String TAG = "AppStatusService"; 
    private ActivityManager activityManager; 
    private String packageName;
    private boolean isStop = false;
    private   NotificationManager notificationManager;
    
    @Override
    public IBinder onBind(Intent intent) {
        // TODO Auto-generated method stub
        return null;
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        // TODO Auto-generated method stub
        activityManager = (ActivityManager) this.getSystemService(Context.ACTIVITY_SERVICE); 
        packageName = this.getPackageName(); 
//        System.out.println("启动服务");
        
        new Thread() { 
            public void run() { 
                try { 
                    while (!isStop) { 
                        Thread.sleep(1000); 
                        
                        if (isAppOnForeground()){ 
//                        	System.out.println("-----前台运行--------");
                        
                        	if(null != notificationManager){
                        		notificationManager.cancel(1);
                        	}
                        	
                        	if(FloatWinService.handler != null ){
                        		Message msg=FloatWinService.handler.obtainMessage();
                        		msg.what=MsgUtil.MSG_QIPAO;
                        		FloatWinService.handler.sendMessage(msg);
                        	}
                        	
                        } else { 
                        	
                        	if(FloatWinService.handler != null ){
                        		Message msg=FloatWinService.handler.obtainMessage();
                        		msg.what=MsgUtil.MSG_NOQIPAO;
                        		FloatWinService.handler.sendMessage(msg);
                        	}
//                        	System.out.println("-----后台运行--------");
                            showNotification();
                        } 
                    } 
                } catch (Exception e) { 
                    e.printStackTrace(); 
                } 
            } 
        }.start(); 
        
        return super.onStartCommand(intent, flags, startId);
    }
    
    /**
     * 程序是否在前台运行
     * @return
     */
    public boolean isAppOnForeground() { 
        // Returns a list of application processes that are running on the device 
        List<RunningAppProcessInfo> appProcesses = activityManager.getRunningAppProcesses(); 
        if (appProcesses == null) return false; 
        
        for (RunningAppProcessInfo appProcess : appProcesses) { 
            // The name of the process that this object is associated with. 
            if (appProcess.processName.equals(packageName) 
                    && appProcess.importance == RunningAppProcessInfo.IMPORTANCE_FOREGROUND) { 
                return true; 
            } 
        } 
        
        return false; 
    } 
    
    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        super.onDestroy();
        System.out.println("终止服务");
        notificationManager.cancel(1);
        isStop = true;
    }
    
    // 显示Notification
    public void showNotification() {
        // 创建一个NotificationManager的引用
      notificationManager = (
                NotificationManager)getSystemService(
                        android.content.Context.NOTIFICATION_SERVICE);
        
        // 定义Notification的各种属性
        Notification notification = new Notification(
                R.drawable.ic_launcher,"蜂众网", 
                System.currentTimeMillis());
        // 将此通知放到通知栏的"Ongoing"即"正在运行"组中
        notification.flags |= Notification.FLAG_ONGOING_EVENT;
        // 点击后自动清除Notification
        notification.flags |= Notification.FLAG_AUTO_CANCEL;
        notification.flags |= Notification.FLAG_SHOW_LIGHTS;
        notification.defaults = Notification.DEFAULT_LIGHTS;
        notification.ledARGB = Color.BLUE;
        notification.ledOnMS = 5000;
                
        // 设置通知的事件消息
        CharSequence contentTitle = "test"; // 通知栏标题
        CharSequence contentText = "test"; // 通知栏内容
        
        Intent notificationIntent = new Intent(AppStatusService.this,MainActivity.class);
        notificationIntent.setAction(Intent.ACTION_MAIN);
        notificationIntent.addCategory(Intent.CATEGORY_LAUNCHER);
        PendingIntent contentIntent = PendingIntent.getActivity(
        		AppStatusService.this, 1, notificationIntent,PendingIntent.FLAG_UPDATE_CURRENT);
        notification.setLatestEventInfo(
        		AppStatusService.this, contentTitle, contentText, contentIntent);
        // 把Notification传递给NotificationManager
        notificationManager.notify(1, notification);
    }
}

记得在manifest加上
 <!-- 程序前台后台运行服务 -->
        <service android:name="com.mobile.utilitys.AppStatusService" >
        </service>




  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值