android判断程序是否前台显示---及判断屏幕是否是亮的----附赠BAIDU定位的工具类实现代码

 

本帖最后由 cj6585256 于 2013-6-20 13:31 编辑

protected static boolean isTopActivity(Activity activity){

        String packageName = "xxxxx";

        ActivityManager activityManager = (ActivityManager) activity.getSystemService(Context.ACTIVITY_SERVICE);

        List<RunningTaskInfo>  tasksInfo = activityManager.getRunningTasks(1);  

        if(tasksInfo.size() > 0){  

            System.out.println("---------------包名-----------"+tasksInfo.get(0).topActivity.getPackageName());

            //应用程序位于堆栈的顶层  

            if(packageName.equals(tasksInfo.get(0).topActivity.getPackageName())){  

                return true;  

            }  

        }  

        return false;

    }
记得添加权限:permission.GET_TASKS

PowerManager pm = (PowerManager)getSystemService(Context.POWER_SERVICE);
pm.isScreenOn()

 

package com.chexiaodi.location;

import java.util.List;

import android.app.Activity;
import android.app.ActivityManager;
import android.app.ActivityManager.RunningTaskInfo;
import android.content.Context;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.os.Bundle;
import android.os.PowerManager;
import android.util.Log;
import android.widget.Toast;
import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.location.LocationClientOption;
import com.chexiaodi.android.cxd.Constands;
import com.chexiaodi.android.cxd.MyApplication;

public class LocationHelper implements LocationListener, BDLocationListener {
    private static final long MINTIME = 3000;
    private static final float MINDISTANCE = 0.0f;
    private static final boolean DEBUG_TOAST = true;

    private Context mContext;
    private LocationManager mLocationManager;
    private Location savedLocation;
    private BDLocation savedBaiduLocation;
    private LocationClient mBDLocationClient;
    private static LocationHelper mInstance = null;

    private static LocationClientOption option;
    
    private static String packageName;

    private LocationHelper(Context c) {
        this.mContext = c;
        option = new LocationClientOption();
        option.setOpenGps(true);
        option.setAddrType("all");// 返回的定位结果包含地址信息
        option.setCoorType("bd09ll");// 返回的定位结果是百度经纬度,默认值gcj02
        option.setScanSpan(5000);// 设置发起定位请求的间隔时间为5000ms
        option.disableCache(true);// 禁止启用缓存定位
        option.setPoiNumber(5); // 最多返回POI个数
        option.setProdName("CheXiaoDi");
        option.setPoiDistance(1000); // poi查询距离
        option.setPoiExtraInfo(true); // 是否需要POI的电话和地址等详细信息
        mBDLocationClient = new LocationClient(mContext);
        mBDLocationClient.setLocOption(option);
        mBDLocationClient.registerLocationListener(this);
    }

    public synchronized static LocationHelper fromContext(Context c) {
        if (mInstance == null)
            mInstance = new LocationHelper(c);
        return mInstance;
    }

    /**
     * get the current location of device
     * 
     * @return
     */
    public Location getCurrentLocation() {
        if (savedLocation == null) {
            Criteria c = new Criteria();
            c.setAccuracy(Criteria.ACCURACY_FINE);
            c.setAltitudeRequired(false);
            c.setBearingRequired(false);
            c.setCostAllowed(false);
            String provider = mLocationManager.getBestProvider(c, true);
            savedLocation = mLocationManager.getLastKnownLocation(provider);
            packageName = Constands.Package_NAME;
        }
        return savedLocation;
    }

    /**
     * check whether GPS is provided by device
     * 
     * @return
     */

    public boolean isGPSProvided() {
        if (mLocationManager.isProviderEnabled(android.location.LocationManager.GPS_PROVIDER)) {
            return true;
        }
        return false;
    }

    /**
     * check whether GPS is currently enabled.
     * 
     * @return
     */
    public boolean isGPSEnabled() {
        return this.isGPSProvided();
    }

    @Override
    public void onLocationChanged(Location location) {
        this.savedLocation = location;
        android.util.Log.i("GPS", "onLocationChanged : " + location);
        if (DEBUG_TOAST)
            Toast.makeText(mContext, "Location =" + location.toString(), Toast.LENGTH_LONG).show();
    }

    @Override
    public void onStatusChanged(String provider, int status, Bundle extras) {
        android.util.Log.i("GPS", "onStatusChanged : " + provider);
    }

    @Override
    public void onProviderEnabled(String provider) {
        android.util.Log.i("GPS", "onProviderEnabled : " + provider);
    }

    @Override
    public void onProviderDisabled(String provider) {
        android.util.Log.i("GPS", "onProviderDisabled : " + provider);
    }

    /***************************************************************/
    /************************** 百度地图位置信息回调 ************************/
    /***************************************************************/
    @Override
    public void onReceiveLocation(BDLocation location) {
        if (location == null)
            return;
        StringBuffer sb = new StringBuffer(256);
        sb.append("time : ");
        sb.append(location.getTime());
        sb.append("\nerror code : ");
        sb.append(location.getLocType());
        sb.append("\nlatitude : ");
        sb.append(location.getLatitude());
        sb.append("\nlontitude : ");
        sb.append(location.getLongitude());
        sb.append("\nradius : ");
        sb.append(location.getRadius());
        if (location.getLocType() == BDLocation.TypeGpsLocation) {
            sb.append("\nspeed : ");
            sb.append(location.getSpeed());
            sb.append("\nsatellite : ");
            sb.append(location.getSatelliteNumber());
        } else if (location.getLocType() == BDLocation.TypeNetWorkLocation) {
            sb.append("\naddr : ");
            sb.append(location.getAddrStr());
        }
        savedBaiduLocation = location;
        // stopBaiduLocation(); //一次定位之后关闭定位动能
    }

    @Override
    public void onReceivePoi(BDLocation arg0) {
    }

    private void logMsg(String log) {
        android.util.Log.d("GPS", log);
    }

    public void startBaiduLocation() {
        Log.i("0726inHELPER", "STARTBAIDU");

        if (!mBDLocationClient.isStarted()) {
            mBDLocationClient.start(); // 如果还没开启定位则开启
        }

        if (mBDLocationClient != null && mBDLocationClient.isStarted()) {
            mBDLocationClient.requestLocation();
        } else {
        }
    }

    public void stopBaiduLocation(    ) {
        Log.i("07240726inHELPER","stopbaidu, appNotOnTop=="+String.valueOf(isScreenOff()));
        //综合判断,如果判断出认为程序在使用则不停baiduLoc
        if(mBDLocationClient.isStarted()&&(appNotOnTop()||isScreenOff())) {
            Log.d("07260724inHELPER","stopbaidu, appNotOnTop=="+String.valueOf(appNotOnTop()));
            mBDLocationClient.unRegisterLocationListener(this);
            
            mBDLocationClient.stop();
        }
    }

    public BDLocation getLocationFromBaiduLoc() {
        return savedBaiduLocation;
    }
    public boolean isScreenOff(){
        PowerManager pm = (PowerManager)mContext.getSystemService(Context.POWER_SERVICE);
        
        return !(pm.isScreenOn());
    }

    public boolean appNotOnTop(){
        ActivityManager manager = (ActivityManager) mContext.getSystemService(Context.ACTIVITY_SERVICE);
        List<RunningTaskInfo> runningTaskInfos = manager.getRunningTasks(100);
        
        if(runningTaskInfos.size() > 0){  

            System.out.println("---------------包名-----------"+runningTaskInfos.get(0).topActivity.getPackageName());

            //应用程序位于堆栈的顶层  

            if("com.chexiaodi.android.cxd".equals(runningTaskInfos.get(0).topActivity.getPackageName())){  

                return false;  

            }  

        }  

        return true;
    }
}

 

posted @ 2013-07-24 14:36  linsen@java  阅读(640)  评论(0编辑  收藏  举报