Skip to content Skip to sidebar Skip to footer

Can We Add A Counter When Home Button Is Clicked In Android?

I know that home button cannot be stopped or override. Is there a way to extend the home button in a way then when it is click, my counter should be increasing without disturbing a

Solution 1:

May this helps you. You should have to use the service and broadcast receiver for that.

MainActivty.java

publicclassMainActivityextendsAppCompatActivity {

    private Button btn_startservice;
    private Button btn_stopservice;
    private TextView tv_servicecounter;
    ServiceDemo myService;
    boolean isBound;

    BroadcastReceiverbroadcastRec=newBroadcastReceiver() {
        @OverridepublicvoidonReceive(Context context, Intent intent) {
            intdatapassed= intent.getIntExtra("value", 0);
            tv_servicecounter.setText(String.valueOf(datapassed));

        }
    };

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)@OverrideprotectedvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        tv_servicecounter = (TextView) findViewById(R.id.tv_activity_main_count);
        btn_startservice = (Button) findViewById(R.id.btn_activity_main_startservices);
        btn_stopservice = (Button) findViewById(R.id.btn_activity_main_stopservices);

        btn_startservice.setOnClickListener(
                newView.OnClickListener() {
                    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)@OverridepublicvoidonClick(View v) {

                        IntentobjIntent=newIntent(MainActivity.this, ServiceDemo.class);
                        if (!isBound) {
                            bindService(objIntent, myConnection, Context.BIND_AUTO_CREATE);
                            isBound = true;
                            startService(objIntent);
                        } else {
                            isBound = false;
                            unbindService(myConnection);
                        }
                    }
                }

        );

        btn_stopservice.setOnClickListener(
                newView.OnClickListener() {
                    @OverridepublicvoidonClick(View v) {

                        IntentobjIntent=newIntent(MainActivity.this, ServiceDemo.class);

                        if (isBound) {
                            isBound = false;
                            unbindService(myConnection);
                            stopService(objIntent);

                        } else {
                            stopService(objIntent);
                        }
                    }
                }
        );
    }

    @OverrideprotectedvoidonResume() {
        registerReceiver(broadcastRec, newIntentFilter("USER_ACTION"));
        super.onResume();
    }

    @OverrideprotectedvoidonStop() {
        this.unregisterReceiver(broadcastRec);
        super.onStop();
    }

    privateServiceConnectionmyConnection=newServiceConnection() {

        publicvoidonServiceConnected(ComponentName className,
                                       IBinder service) {
            myService = ((ServiceDemo.MyLocalBinder) service).getService();
            isBound = true;
        }

        publicvoidonServiceDisconnected(ComponentName arg0) {
            isBound = false;
        }

    };

    @OverrideprotectedvoidonDestroy() {
        super.onDestroy();
        if (isBound) {
            unbindService(myConnection);
            isBound = false;
        }
    }

}

DemoService.java

publicclassServiceDemoextendsService {
    int i;
    private MyThread mythread;
    publicbooleanisRunning=false;
    Notification notification;

    @OverridepublicvoidonCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");
        mythread = newMyThread();

    }


    @OverridepublicintonStartCommand(Intent intent, int flags, int startId) {


        Toast.makeText(this, "Service Started", Toast.LENGTH_SHORT).show();

        if (!isRunning) {
            mythread.start();
            isRunning = true;
        }
        return START_STICKY;
    }

    @OverridepublicvoidonDestroy() {
        super.onDestroy();

        mythread.interrupt();
        Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
    }

    publicvoidsendBrodcastMsg(int value) {
        Intentintent=newIntent();
        intent.setAction("USER_ACTION");
        intent.putExtra("value", value);
        sendBroadcast(intent);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)classMyThreadextendsThread {
        staticfinallongDELAY=100;

        @Overridepublicvoidrun() {
            while (isRunning) {
                try {
                    i++;
                    Thread.sleep(DELAY);
                    sendBrodcastMsg(i);
                    shownotification();
                } catch (InterruptedException e) {
                    isRunning = false;
                    e.printStackTrace();
                }
            }
            stopSelf();
        }
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)publicvoidshownotification() {
        Intentin=newIntent(this, MainActivity.class);
        PendingIntentpIntent= PendingIntent.getActivity(this, (int) System.currentTimeMillis(), in, 0);

        notification = newNotificationCompat.Builder(this)
                .setContentTitle(String.valueOf(i))
                .setContentText(String.valueOf(i))
                .setSmallIcon(R.drawable.musicplayer)
                .setContentIntent(pIntent)
                .setAutoCancel(true).build();
        ;

        startForeground(101, notification);

    }

    publicclassMyLocalBinderextendsBinder {
        ServiceDemo getService() {
            return ServiceDemo.this;
        }
    }

    privatefinalIBindermyBinder=newMyLocalBinder();

    @Overridepublic IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stubreturn myBinder;
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?><RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:id="@+id/activity_main"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"tools:context="com.yudiz.servicedemo.MainActivity"><TextViewandroid:id="@+id/tv_activity_main_count"android:layout_width="match_parent"android:layout_height="wrap_content"android:text="ABC"android:gravity="center"/><Buttonandroid:id="@+id/btn_activity_main_startservices"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@id/tv_activity_main_count"android:text="Start Services"/><Buttonandroid:id="@+id/btn_activity_main_stopservices"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@id/btn_activity_main_startservices"android:text="Stop Services" /></RelativeLayout>

Androidmanifest.xml

<uses-permissionandroid:name="android.permission.RECEIVE_BOOT_COMPLETED" /><applicationandroid:allowBackup="true"android:icon="@mipmap/ic_launcher"android:label="@string/app_name"android:supportsRtl="true"android:theme="@style/AppTheme"><activityandroid:name=".MainActivity"><intent-filter><actionandroid:name="android.intent.action.MAIN" /><categoryandroid:name="android.intent.category.LAUNCHER" /></intent-filter></activity><serviceandroid:name=".ServiceDemo"android:enabled="true"></service></application>

Solution 2:

Try the following code, it works:

HomeWatcher mHomeWatcher = newHomeWatcher(this);
mHomeWatcher.setOnHomePressedListener(newOnHomePressedListener() {
    @OverridepublicvoidonHomePressed() {
        // do something here...
    }
    @OverridepublicvoidonHomeLongPressed() {
    }
});
mHomeWatcher.startWatch();

HomeWatcher Class

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.util.Log;

publicclassHomeWatcher {

   staticfinalStringTAG="hg";
   private Context mContext;
   private IntentFilter mFilter;
   private OnHomePressedListener mListener;
   private InnerRecevier mRecevier;

   publicHomeWatcher(Context context) {
       mContext = context;
       mFilter = newIntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
   }

   publicvoidsetOnHomePressedListener(OnHomePressedListener listener) {
       mListener = listener;
       mRecevier = newInnerRecevier();
   }

   publicvoidstartWatch() {
       if (mRecevier != null) {
           mContext.registerReceiver(mRecevier, mFilter);
       }
   }

   publicvoidstopWatch() {
       if (mRecevier != null) {
           mContext.unregisterReceiver(mRecevier);
       }
   }

   classInnerRecevierextendsBroadcastReceiver {
       finalStringSYSTEM_DIALOG_REASON_KEY="reason";
       finalStringSYSTEM_DIALOG_REASON_GLOBAL_ACTIONS="globalactions";
       finalStringSYSTEM_DIALOG_REASON_RECENT_APPS="recentapps";
       finalStringSYSTEM_DIALOG_REASON_HOME_KEY="homekey";

       @OverridepublicvoidonReceive(Context context, Intent intent) {
           Stringaction= intent.getAction();
           if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
               Stringreason=    intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);
               if (reason != null) {
                   Log.e(TAG, "action:" + action + ",reason:" + reason);
                   if (mListener != null) {
                       if (reason.equals(SYSTEM_DIALOG_REASON_HOME_KEY)) {
                           mListener.onHomePressed();
                       } elseif    (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
                           mListener.onHomeLongPressed();
                       }
                   }
               }
           }
       }
   }
}

OnHomePressed Interface

publicinterfaceOnHomePressedListener {
    publicvoidonHomePressed();

    publicvoidonHomeLongPressed();
}

Solution 3:

You can create a new Home screen Activity (ACTION_MAIN with category CATEGORY_HOME), count the number of Intents (Home) received and then perhaps start the real Home.

Post a Comment for "Can We Add A Counter When Home Button Is Clicked In Android?"