1. 程式人生 > >Application 判斷 是否在主程序、主執行緒

Application 判斷 是否在主程序、主執行緒

package com.moretv.android;

import android.app.ActivityManager;
import android.app.Application;
import android.content.Context;
import android.os.Looper;

import com.lib.core.CoreServer;
import com.lib.service.ServiceManager;


/**
 * test
 */

public class App extends Application {

    public static App instance;
    /**
     * 是否為主執行緒
     */
    private boolean isMainThread = Looper.getMainLooper() == Looper.myLooper();

    /**
     * 是否為主程序
     */
    private boolean isMainProcess ;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;

        isMainProcess = getApplicationContext().getPackageName().equals(getCurrentProcessName());
        ServiceManager.log().develop("bruce", "是否為主執行緒" + isMainThread);
        ServiceManager.log().develop("bruce", "是否為主程序" + isMainProcess);

    }

    /**
     * 獲取當前程序名
     */
    private String getCurrentProcessName() {
        int pid = android.os.Process.myPid();
        String processName = "";
        ActivityManager manager = (ActivityManager) getApplicationContext().getSystemService
                (Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningAppProcessInfo process : manager.getRunningAppProcesses()) {
            if (process.pid == pid) {
                processName = process.processName;
            }
        }
        return processName;
    }

}