Android后台服务不会在退出菜单上停止

时间:2016-09-26 14:03:51

标签: android

以下是我的代码,我在其中调用了runService()方法来启动服务 服务开始工作但是当我点击注销菜单时我的服务没有停止,我已经写了代码来停止Constants.NavigationItems.NAV_SIGN_OUT上的服务:

家庭活动

public class Home extends AppCompatActivity implements ListView.OnItemClickListener {
    // Alert Dialog Manager
    AlertDialogManager alert = new AlertDialogManager();
    private static final String TAG = "DEEPAK-TEA-GPSTracking";
    private static double latitude; // latitude
    private static double longitude; // longitude

    // Session Manager Class
    SessionManager session;
    public static int backpress;
    private static FragmentManager fm;
    NavigationView navigationView;
    TextView tv_header_name;
    CircularImageView profileimg;
    //ImageView profileimg;

    PowerManager.WakeLock wakeLock;
    private Calendar mCalendar2 = Calendar.getInstance();

    //Defining Variables
    private Toolbar toolbar;
    private DrawerLayout drawerLayout;
    private RelativeLayout navHeaderlayout;
    private ListView lvNavList;
    private CharSequence mTitle;
    private ActionBarDrawerToggle actionBarDrawerToggle;

    Bundle userIdBundle = new Bundle();
    /* --------------ALARM Manager declaration----------*/
    private PendingIntent pendingIntent;
    DataBaseHelper dbHelper;
    CommonUtil commonUtil = new CommonUtil();
    Cursor cursor;
    Context context;
    private String UserId, Username, EmpName, CityId;
    private String encodeimg = "";

    /*Search Data*/


    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        // Session class instance
        dbHelper = new DataBaseHelper(Home.this);

        this.context = this;
        session = new SessionManager(getApplicationContext());

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy =
                    new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        // Initialize Toolbar (Actionbar)
        //   mTitle = getTitle();
        //   getSupportActionBar().hide();
        toolbar = (Toolbar) findViewById(R.id.toolbar1);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        }
        // Initialize Navigation Drawer
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawerLayout.setBackgroundColor(Color.TRANSPARENT);
        navHeaderlayout = (RelativeLayout) findViewById(R.id.LL_navheaderlayout);
        navHeaderlayout.setBackgroundColor(Color.TRANSPARENT);
        fm = getSupportFragmentManager();
        //Navigation View Initialization
        navigationView = (NavigationView) findViewById(R.id.navigation_view);
        lvNavList = (ListView) findViewById(R.id.lv_nav_list);
        navigationView.setItemIconTintList(null);

        List<MenuItems> listViewItems = new ArrayList<MenuItems>();
        listViewItems.add(new MenuItems("Home", R.drawable.ic_home));
        listViewItems.add(new MenuItems("Profile", R.drawable.ic_menu_profile));
        /*listViewItems.add(new MenuItems("Feedback", R.drawable.ic_callus));
        listViewItems.add(new MenuItems("Rate Us", R.drawable.ic_menu_star));
        listViewItems.add(new MenuItems("Share", R.drawable.ic_menu_share));*/
        listViewItems.add(new MenuItems("About Us", R.drawable.ic_menu_about));
        listViewItems.add(new MenuItems("Logout", R.drawable.ic_menu_user));
        lvNavList.setAdapter(new CustomAdapter(Home.this, listViewItems));

        lvNavList.setOnItemClickListener(this);

        //profileimg = (CircleImageView) findViewById(R.id.profile_image);
        profileimg = (CircularImageView) findViewById(R.id.profile_image);
        //profileimg.setImageDrawable(R.drawable.ic_men_user2);

        tv_header_name = (TextView) findViewById(R.id.username);
        actionBarDrawerToggle = new ActionBarDrawerToggle(Home.this, drawerLayout, toolbar, R.string.OpenNavigationDrawer, R.string.CloseNavigationDrawer) {

            @Override
            public void onDrawerClosed(View drawerView) {
                // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
                super.onDrawerClosed(drawerView);
                // getSupportActionBar().setTitle(mTitle);
                //invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()

            }

            @Override
            public void onDrawerOpened(View drawerView) {
                // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank

                super.onDrawerOpened(drawerView);
                //getSupportActionBar().setTitle(mTitle);
                CommonUtil.closeKeyboard(Home.this);
                // invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()

            }
        };
        drawerLayout.addDrawerListener(actionBarDrawerToggle);
        actionBarDrawerToggle.syncState();


             /*--- Retrieve a PendingIntent that will perform a broadcast------------------------------- */
           /* Intent alarmIntent = new Intent(Home.this, AlarmReceiver.class);
            alarmIntent.putExtra("userid", String.valueOf(UserId));
            Log.i("SEND TO BroadCAST Receiver","USERID :"+ String.valueOf(UserId));
            pendingIntent = PendingIntent.getBroadcast(Home.this,0,alarmIntent,0);

            // Start Alarm at 9:30 AM Daily.
            startAt930();

            // Stop Alarm at 7:30 PM Daily.
           *//* stopAt730();*/
        try {
            boolean isGPSENABLE = CommonUtil.isGPS(getApplicationContext());
            if (isGPSENABLE == true) {

                if (CommonUtil.isInternetAvailable(getApplicationContext()) == true) {
                    // Shopcategory Fragment call by default on Home screen
                    // sendUserID();
                    CommonUtil.showProgressDialog(Home.this, "Please wait while loading data...");
                    fragmentcall(Home.this, new ShopCategoryFragment(), fm);
                    backpress = 0;
                    getSessionDetails(); // Check and get session data.
                    tv_header_name.setText(tv_header_name.getText().toString() + " " + EmpName + ",");
                    Log.i("SyncProcess", "Running  Called");
                    SyncProcess syncProcess = new SyncProcess(Home.this, false);
                    syncProcess.execute(Home.this);

                    //   Toast.makeText(getApplicationContext(), "UserID :" + UserId, Toast.LENGTH_LONG).show();
                    getdata(); // Get Employee Data
                    if (encodeimg.equals("")) {
                        Log.i("IMAGE", "IS NULL");
                        if (android.os.Build.VERSION.SDK_INT >= 21) {

                            profileimg.setImageDrawable(getResources().getDrawable(R.drawable.ic_men_user2, getTheme()));
                        } else {

                            profileimg.setImageDrawable(getResources().getDrawable(R.drawable.ic_men_user2));
                        }

                    } else {
                        Log.v("BASE64Converstion", encodeimg);
                        Bitmap photo = CommonUtil.base64ToBitmap(encodeimg);
                        profileimg.setImageBitmap(photo);

                    }

               /* PowerManager mgr = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
                wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
                wakeLock.acquire();*/
                    Log.i("Application", "Running  Online....");
                    if (!runtimePermission()) {

                        runService();

                       /* Log.i("Location:", " " + Coordinates);
                        Toast.makeText(getApplicationContext(),"Locations:"+Coordinates,Toast.LENGTH_SHORT).show();
*/

                    }
                    CommonUtil.cancelProgressDialog();

                } else {
                    // Shopcategory Fragment call by default on Home screen
                    //sendUserID();
                 //   CommonUtil.showProgressDialog(Home.this, "Please wait while loading data...");
                    fragmentcall(Home.this, new ShopCategoryFragment(), fm);
                //    CommonUtil.cancelProgressDialog();
                    backpress = 0;
                    getSessionDetails(); // Check and get session data.

                    tv_header_name.setText(tv_header_name.getText().toString() + " " + EmpName + ",");
                    getdata(); // Get Employee Data
                    if (encodeimg.equals("")) {
                        Log.i("IMAGE", "IS NULL");

                        if (android.os.Build.VERSION.SDK_INT >= 21) {

                            profileimg.setImageDrawable(getResources().getDrawable(R.drawable.ic_men_user2, getTheme()));
                        } else {

                            profileimg.setImageDrawable(getResources().getDrawable(R.drawable.ic_men_user2));
                        }


                    } else {
                        Log.v("BASE64Converstion", encodeimg);
                        Bitmap photo = CommonUtil.base64ToBitmap(encodeimg);
                        profileimg.setImageBitmap(photo);

                    }
                    if (CommonUtil.isInternetAvailable(Home.this)) {
                        SyncProcess syncProcess = new SyncProcess(Home.this, false);
                        syncProcess.execute(Home.this);
                    }
                    Log.i("Application", "Running  Offline....");


                    if (!runtimePermission()) {
                        runService();
                       /*/ Log.i("Location:", " " + Coordinates);
                        Toast.makeText(getApplicationContext(),"Locations:"+Coordinates,Toast.LENGTH_SHORT).show();
*/

                    }

                    //Toast.makeText(this, R.string.app_offline, Toast.LENGTH_SHORT).show();
                }


            } else { // NO GPS
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Location Services Disabled");
                // builder.setCustomTitl
                builder.setMessage("Please enable location services.");
                builder.setIcon(R.drawable.nogps);
                builder.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        Login login = new Login();
                        login.GPSSettings();
                    }
                });
                AlertDialog alert = builder.create();
                alert.show();

            }


        } catch (Exception e) {
            e.printStackTrace();
        }


        //}
        CommonUtil.cancelProgressDialog();

    }
     public void runService() {
   Intent i = new Intent(getApplicationContext(), TestService.class);
        context.startService(i);

    }

     @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        boolean isGPSENABLE = CommonUtil.isGPS(getApplicationContext());

        switch (position) {
            case Constants.NavigationItems.NAV_HOME:
                try {
                    if (isGPSENABLE == true) {
                        if (CommonUtil.isInternet(this)) {
                            Log.i("Application", "Running  Online....");
                            ///sendUserID();
                            fragmentcall(Home.this, new ShopCategoryFragment(), fm);
                            Log.i("HOME", "ShopCategoryFragment Called.");
                            backpress = 0;
                        } else {
                            Log.i("Application", "Running  Offline....");
                            Toast.makeText(this, R.string.app_offline, Toast.LENGTH_SHORT).show();
                            // sendUserID();
                            fragmentcall(Home.this, new ShopCategoryFragment(), fm);
                            Log.i("HOME", "ShopCategoryFragment Called.");
                            backpress = 0;
                        }


                    } else {
                        // NO GPS
                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                        builder.setTitle("Location Services Disabled");
                        // builder.setCustomTitl
                        builder.setMessage("Please enable location services.");
                        builder.setIcon(R.drawable.nogps);
                        builder.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Login login = new Login();
                                login.GPSSettings();
                            }
                        });
                        AlertDialog alert = builder.create();
                        alert.show();

                    }

                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "Something Went Wrong!", Toast.LENGTH_SHORT).show();
                }
                break;
            case Constants.NavigationItems.NAV_PROFILE:
                try {
                    if (isGPSENABLE == true) {
                        if (CommonUtil.isInternet(this)) {
                            Log.i("Application", "Running  Online....");
                            Intent profileIntent = new Intent(Home.this, ProfileActivity.class);
                            this.startActivity(profileIntent);

                            backpress = 0;
                        } else {
                            Log.i("Application", "Running  Offline....");
                            Intent profileIntent = new Intent(Home.this, ProfileActivity.class);
                            this.startActivity(profileIntent);
                            backpress = 0;
                        }


                    } else {
                        // NO GPS
                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                        builder.setTitle("Location Services Disabled");
                        // builder.setCustomTitl
                        builder.setMessage("Please enable location services.");
                        builder.setIcon(R.drawable.nogps);
                        builder.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Login login = new Login();
                                login.GPSSettings();
                            }
                        });
                        AlertDialog alert = builder.create();
                        alert.show();

                    }

                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "Something Went Wrong!", Toast.LENGTH_SHORT).show();
                }
                break;


            case Constants.NavigationItems.NAV_ABOUTUS:
                try {
                    Toast.makeText(getApplicationContext(), "About Us", Toast.LENGTH_SHORT).show();
                    fragmentcall(Home.this, new AboutFragment(), fm);
                    backpress = 0;
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "Something Went Wrong!", Toast.LENGTH_SHORT).show();
                }
                break;
            case Constants.NavigationItems.NAV_SIGN_OUT:
                try {
                  /*  Intent alarmIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
                    AlarmUtil.cancelAlarm(getApplicationContext(),alarmIntent,1);*/
                    context.stopService(new Intent(this, TestService.class));
                    session.logoutUser();
                   /* context.stopService(new Intent(this, TestService.class));
                    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
                    alarmManager.cancel(pendingIntent);*/
                    Log.i("MyLocationService", "Stopped...");
                    startActivity(new Intent(Home.this, Login.class));
                    Toast.makeText(getApplicationContext(), "You have Successfully Logged Out...", Toast.LENGTH_SHORT).show();
                    finish();
                    // fragmentcall(LetUsTell.this, new AboutFragment(), fm);
                    //   backpress = 6;
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "Something Went Wrong!", Toast.LENGTH_SHORT).show();
                }
                break;

            default:
                if (isGPSENABLE == true) {
                    if (CommonUtil.isInternet(this)) {
                        Log.i("Application", "Running  Online....");
                        // Shopcategory Fragment call by default on Home screen
                        //   sendUserID();
                        fragmentcall(Home.this, new ShopCategoryFragment(), fm);
                        backpress = 9;

                        Log.i("HOME", "ShopCategoryFragment Called.");

                    } else {
                        Log.i("Application", "Running  Offline....");
                        Toast.makeText(this, R.string.app_offline, Toast.LENGTH_SHORT).show();
                        /// sendUserID();
                        fragmentcall(Home.this, new ShopCategoryFragment(), fm);
                        backpress = 9;

                        Log.i("HOME", "ShopCategoryFragment Called.");
                    }


                } else { // No GPS
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("Location Services Disabled");
                    // builder.setCustomTitl
                    builder.setMessage("Please enable location services.");
                    builder.setIcon(R.drawable.nogps);
                    builder.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            Login login = new Login();
                            login.GPSSettings();
                        }
                    });
                    AlertDialog alert = builder.create();
                    alert.show();

                }
                break;

        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
    }
 }

1 个答案:

答案 0 :(得分:0)

我稍微改变了你的代码

public class Home extends AppCompatActivity implements ListView.OnItemClickListener {
    // Alert Dialog Manager
    AlertDialogManager alert = new AlertDialogManager();
    private static final String TAG = "DEEPAK-TEA-GPSTracking";
    private static double latitude; // latitude
    private static double longitude; // longitude

    // Session Manager Class
    SessionManager session;
    public static int backpress;
    private static FragmentManager fm;
    NavigationView navigationView;
    TextView tv_header_name;
    CircularImageView profileimg;
    //ImageView profileimg;

    PowerManager.WakeLock wakeLock;
    private Calendar mCalendar2 = Calendar.getInstance();

    //Defining Variables
    private Toolbar toolbar;
    private DrawerLayout drawerLayout;
    private RelativeLayout navHeaderlayout;
    private ListView lvNavList;
    private CharSequence mTitle;
    private ActionBarDrawerToggle actionBarDrawerToggle;

    Bundle userIdBundle = new Bundle();
    /* --------------ALARM Manager declaration----------*/
    private PendingIntent pendingIntent;
    DataBaseHelper dbHelper;
    CommonUtil commonUtil = new CommonUtil();
    Cursor cursor;
    Context context;
    private String UserId, Username, EmpName, CityId;
    private String encodeimg = "";

    /*Search Data*/


    public static void setListViewHeightBasedOnChildren(ListView listView) {
        ListAdapter listAdapter = listView.getAdapter();
        if (listAdapter == null) {
            // pre-condition
            return;
        }
        int totalHeight = 0;
        for (int i = 0; i < listAdapter.getCount(); i++) {
            View listItem = listAdapter.getView(i, null, listView);
            listItem.measure(0, 0);
            totalHeight += listItem.getMeasuredHeight();
        }

        ViewGroup.LayoutParams params = listView.getLayoutParams();
        params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
        listView.setLayoutParams(params);
        listView.requestLayout();
    }

    @Override
    protected void onResume() {
        super.onResume();

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();

    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_home);
        // Session class instance
        dbHelper = new DataBaseHelper(Home.this);

        this.context = this;
        session = new SessionManager(getApplicationContext());

        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy =
                    new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }
        // Initialize Toolbar (Actionbar)
        //   mTitle = getTitle();
//       getSupportActionBar().hide();
        toolbar = (Toolbar) findViewById(R.id.toolbar1);
        if (toolbar != null) {
            setSupportActionBar(toolbar);
            getSupportActionBar().setDisplayHomeAsUpEnabled(true);

        }
        // Initialize Navigation Drawer
        drawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawerLayout.setBackgroundColor(Color.TRANSPARENT);
        navHeaderlayout = (RelativeLayout) findViewById(R.id.LL_navheaderlayout);
        navHeaderlayout.setBackgroundColor(Color.TRANSPARENT);
        fm = getSupportFragmentManager();
        //Navigation View Initialization
        navigationView = (NavigationView) findViewById(R.id.navigation_view);
        lvNavList = (ListView) findViewById(R.id.lv_nav_list);
        navigationView.setItemIconTintList(null);

        List<MenuItems> listViewItems = new ArrayList<MenuItems>();
        listViewItems.add(new MenuItems("Home", R.drawable.ic_home));
        listViewItems.add(new MenuItems("Profile", R.drawable.ic_menu_profile));
      /*  listViewItems.add(new MenuItems("Feedback", R.drawable.ic_callus));
        listViewItems.add(new MenuItems("Rate Us", R.drawable.ic_menu_star));
        listViewItems.add(new MenuItems("Share", R.drawable.ic_menu_share));*/
        listViewItems.add(new MenuItems("About Us", R.drawable.ic_menu_about));
        listViewItems.add(new MenuItems("Logout", R.drawable.ic_menu_user));
        lvNavList.setAdapter(new CustomAdapter(Home.this, listViewItems));

        lvNavList.setOnItemClickListener(this);

        //   profileimg = (CircleImageView) findViewById(R.id.profile_image);
        profileimg = (CircularImageView) findViewById(R.id.profile_image);
        //    profileimg.setImageDrawable(R.drawable.ic_men_user2);

        tv_header_name = (TextView) findViewById(R.id.username);
        actionBarDrawerToggle = new ActionBarDrawerToggle(Home.this, drawerLayout, toolbar, R.string.OpenNavigationDrawer, R.string.CloseNavigationDrawer) {

            @Override
            public void onDrawerClosed(View drawerView) {
                // Code here will be triggered once the drawer closes as we dont want anything to happen so we leave this blank
                super.onDrawerClosed(drawerView);
                // getSupportActionBar().setTitle(mTitle);
                //invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()

            }

            @Override
            public void onDrawerOpened(View drawerView) {
                // Code here will be triggered once the drawer open as we dont want anything to happen so we leave this blank

                super.onDrawerOpened(drawerView);
                //getSupportActionBar().setTitle(mTitle);
                CommonUtil.closeKeyboard(Home.this);
                // invalidateOptionsMenu(); // creates call to onPrepareOptionsMenu()

            }
        };
        drawerLayout.addDrawerListener(actionBarDrawerToggle);
        actionBarDrawerToggle.syncState();


             /*--- Retrieve a PendingIntent that will perform a broadcast------------------------------- */
           /* Intent alarmIntent = new Intent(Home.this, AlarmReceiver.class);
            alarmIntent.putExtra("userid", String.valueOf(UserId));
            Log.i("SEND TO BroadCAST Receiver","USERID :"+ String.valueOf(UserId));
            pendingIntent = PendingIntent.getBroadcast(Home.this,0,alarmIntent,0);

            // Start Alarm at 9:30 AM Daily.
            startAt930();

            // Stop Alarm at 7:30 PM Daily.
           *//* stopAt730();*/
        try {
            boolean isGPSENABLE = CommonUtil.isGPS(getApplicationContext());
            if (isGPSENABLE == true) {

                if (CommonUtil.isInternetAvailable(getApplicationContext()) == true) {
                    // Shopcategory Fragment call by default on Home screen
                    // sendUserID();
                    CommonUtil.showProgressDialog(Home.this, "Please wait while loading data...");
                    fragmentcall(Home.this, new ShopCategoryFragment(), fm);
                    backpress = 0;
                    getSessionDetails(); // Check and get session data.
                    tv_header_name.setText(tv_header_name.getText().toString() + " " + EmpName + ",");
                    Log.i("SyncProcess", "Running  Called");
                    SyncProcess syncProcess = new SyncProcess(Home.this, false);
                    syncProcess.execute(Home.this);

                    //   Toast.makeText(getApplicationContext(), "UserID :" + UserId, Toast.LENGTH_LONG).show();
                    getdata(); // Get Employee Data
                    if (encodeimg.equals("")) {
                        Log.i("IMAGE", "IS NULL");
                        if (android.os.Build.VERSION.SDK_INT >= 21) {

                            profileimg.setImageDrawable(getResources().getDrawable(R.drawable.ic_men_user2, getTheme()));
                        } else {

                            profileimg.setImageDrawable(getResources().getDrawable(R.drawable.ic_men_user2));
                        }

                    } else {
                        Log.v("BASE64Converstion", encodeimg);
                        Bitmap photo = CommonUtil.base64ToBitmap(encodeimg);
                        profileimg.setImageBitmap(photo);

                    }

               /* PowerManager mgr = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
                wakeLock = mgr.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "MyWakeLock");
                wakeLock.acquire();*/
                    Log.i("Application", "Running  Online....");
                    if (!runtimePermission()) {

                        runService();

                       /* Log.i("Location:", " " + Coordinates);
                        Toast.makeText(getApplicationContext(),"Locations:"+Coordinates,Toast.LENGTH_SHORT).show();
*/

                    }
                    CommonUtil.cancelProgressDialog();

                } else {
                    // Shopcategory Fragment call by default on Home screen
                    //sendUserID();
                 //   CommonUtil.showProgressDialog(Home.this, "Please wait while loading data...");
                    fragmentcall(Home.this, new ShopCategoryFragment(), fm);
                //    CommonUtil.cancelProgressDialog();
                    backpress = 0;
                    getSessionDetails(); // Check and get session data.

                    tv_header_name.setText(tv_header_name.getText().toString() + " " + EmpName + ",");
                    getdata(); // Get Employee Data
                    if (encodeimg.equals("")) {
                        Log.i("IMAGE", "IS NULL");

                        if (android.os.Build.VERSION.SDK_INT >= 21) {

                            profileimg.setImageDrawable(getResources().getDrawable(R.drawable.ic_men_user2, getTheme()));
                        } else {

                            profileimg.setImageDrawable(getResources().getDrawable(R.drawable.ic_men_user2));
                        }


                    } else {
                        Log.v("BASE64Converstion", encodeimg);
                        Bitmap photo = CommonUtil.base64ToBitmap(encodeimg);
                        profileimg.setImageBitmap(photo);

                    }
                    if (CommonUtil.isInternetAvailable(Home.this)) {
                        SyncProcess syncProcess = new SyncProcess(Home.this, false);
                        syncProcess.execute(Home.this);
                    }
                    Log.i("Application", "Running  Offline....");


                    if (!runtimePermission()) {
                        runService();
                       /*/ Log.i("Location:", " " + Coordinates);
                        Toast.makeText(getApplicationContext(),"Locations:"+Coordinates,Toast.LENGTH_SHORT).show();
*/

                    }

                    //Toast.makeText(this, R.string.app_offline, Toast.LENGTH_SHORT).show();
                }


            } else { // NO GPS
                AlertDialog.Builder builder = new AlertDialog.Builder(this);
                builder.setTitle("Location Services Disabled");
                // builder.setCustomTitl
                builder.setMessage("Please enable location services.");
                builder.setIcon(R.drawable.nogps);
                builder.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        Login login = new Login();
                        login.GPSSettings();
                    }
                });
                AlertDialog alert = builder.create();
                alert.show();

            }


        } catch (Exception e) {
            e.printStackTrace();
        }


        //}
        CommonUtil.cancelProgressDialog();

    }
     public void runService() {
   Intent i = new Intent(getApplicationContext(), TestService.class);
        startService(i);

    }

     @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        boolean isGPSENABLE = CommonUtil.isGPS(getApplicationContext());

        switch (position) {
            case Constants.NavigationItems.NAV_HOME:
                try {
                    if (isGPSENABLE == true) {
                        if (CommonUtil.isInternet(this)) {
                            Log.i("Application", "Running  Online....");
                            ///sendUserID();
                            fragmentcall(Home.this, new ShopCategoryFragment(), fm);
                            Log.i("HOME", "ShopCategoryFragment Called.");
                            backpress = 0;
                        } else {
                            Log.i("Application", "Running  Offline....");
                            Toast.makeText(this, R.string.app_offline, Toast.LENGTH_SHORT).show();
                            // sendUserID();
                            fragmentcall(Home.this, new ShopCategoryFragment(), fm);
                            Log.i("HOME", "ShopCategoryFragment Called.");
                            backpress = 0;
                        }


                    } else {
                        // NO GPS
                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                        builder.setTitle("Location Services Disabled");
                        // builder.setCustomTitl
                        builder.setMessage("Please enable location services.");
                        builder.setIcon(R.drawable.nogps);
                        builder.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Login login = new Login();
                                login.GPSSettings();
                            }
                        });
                        AlertDialog alert = builder.create();
                        alert.show();

                    }

                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "Something Went Wrong!", Toast.LENGTH_SHORT).show();
                }
                break;
            case Constants.NavigationItems.NAV_PROFILE:
                try {
                    if (isGPSENABLE == true) {
                        if (CommonUtil.isInternet(this)) {
                            Log.i("Application", "Running  Online....");
                            Intent profileIntent = new Intent(Home.this, ProfileActivity.class);
                            this.startActivity(profileIntent);

                            backpress = 0;
                        } else {
                            Log.i("Application", "Running  Offline....");
                            Intent profileIntent = new Intent(Home.this, ProfileActivity.class);
                            this.startActivity(profileIntent);
                            backpress = 0;
                        }


                    } else {
                        // NO GPS
                        AlertDialog.Builder builder = new AlertDialog.Builder(this);
                        builder.setTitle("Location Services Disabled");
                        // builder.setCustomTitl
                        builder.setMessage("Please enable location services.");
                        builder.setIcon(R.drawable.nogps);
                        builder.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
                            public void onClick(DialogInterface dialog, int id) {
                                Login login = new Login();
                                login.GPSSettings();
                            }
                        });
                        AlertDialog alert = builder.create();
                        alert.show();

                    }

                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "Something Went Wrong!", Toast.LENGTH_SHORT).show();
                }
                break;


            case Constants.NavigationItems.NAV_ABOUTUS:
                try {
                    Toast.makeText(getApplicationContext(), "About Us", Toast.LENGTH_SHORT).show();
                    fragmentcall(Home.this, new AboutFragment(), fm);
                    backpress = 0;
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "Something Went Wrong!", Toast.LENGTH_SHORT).show();
                }
                break;
            case Constants.NavigationItems.NAV_SIGN_OUT:
                try {
                  /*  Intent alarmIntent = new Intent(getApplicationContext(), AlarmReceiver.class);
                    AlarmUtil.cancelAlarm(getApplicationContext(),alarmIntent,1);*/
                    stopService(new Intent(this, TestService.class));
                    session.logoutUser();
                   /* context.stopService(new Intent(this, TestService.class));
                    AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
                    alarmManager.cancel(pendingIntent);*/
                    Log.i("MyLocationService", "Stopped...");
                    startActivity(new Intent(Home.this, Login.class));
                    Toast.makeText(getApplicationContext(), "You have Successfully Logged Out...", Toast.LENGTH_SHORT).show();
                    finish();
                    // fragmentcall(LetUsTell.this, new AboutFragment(), fm);
                    //   backpress = 6;
                } catch (Exception e) {
                    Toast.makeText(getApplicationContext(), "Something Went Wrong!", Toast.LENGTH_SHORT).show();
                }
                break;

            default:
                if (isGPSENABLE == true) {
                    if (CommonUtil.isInternet(this)) {
                        Log.i("Application", "Running  Online....");
                        // Shopcategory Fragment call by default on Home screen
                        //   sendUserID();
                        fragmentcall(Home.this, new ShopCategoryFragment(), fm);
                        backpress = 9;

                        Log.i("HOME", "ShopCategoryFragment Called.");

                    } else {
                        Log.i("Application", "Running  Offline....");
                        Toast.makeText(this, R.string.app_offline, Toast.LENGTH_SHORT).show();
                        /// sendUserID();
                        fragmentcall(Home.this, new ShopCategoryFragment(), fm);
                        backpress = 9;

                        Log.i("HOME", "ShopCategoryFragment Called.");
                    }


                } else { // No GPS
                    AlertDialog.Builder builder = new AlertDialog.Builder(this);
                    builder.setTitle("Location Services Disabled");
                    // builder.setCustomTitl
                    builder.setMessage("Please enable location services.");
                    builder.setIcon(R.drawable.nogps);
                    builder.setPositiveButton("Enable", new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int id) {
                            Login login = new Login();
                            login.GPSSettings();
                        }
                    });
                    AlertDialog alert = builder.create();
                    alert.show();

                }
                break;

        }
        DrawerLayout drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
        drawer.closeDrawer(GravityCompat.START);
    }
 }

我希望它会帮助你。