Can we add a counter when home button is clicked in android?

不问归期 提交于 2019-12-24 05:56:15

问题


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 any functionality of the home button.


回答1:


Try the following code, it works:

HomeWatcher mHomeWatcher = new HomeWatcher(this);
mHomeWatcher.setOnHomePressedListener(new OnHomePressedListener() {
    @Override
    public void onHomePressed() {
        // do something here...
    }
    @Override
    public void onHomeLongPressed() {
    }
});
mHomeWatcher.startWatch();

HomeWatcher Class

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

public class HomeWatcher {

   static final String TAG = "hg";
   private Context mContext;
   private IntentFilter mFilter;
   private OnHomePressedListener mListener;
   private InnerRecevier mRecevier;

   public HomeWatcher(Context context) {
       mContext = context;
       mFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
   }

   public void setOnHomePressedListener(OnHomePressedListener listener) {
       mListener = listener;
       mRecevier = new InnerRecevier();
   }

   public void startWatch() {
       if (mRecevier != null) {
           mContext.registerReceiver(mRecevier, mFilter);
       }
   }

   public void stopWatch() {
       if (mRecevier != null) {
           mContext.unregisterReceiver(mRecevier);
       }
   }

   class InnerRecevier extends BroadcastReceiver {
       final String SYSTEM_DIALOG_REASON_KEY = "reason";
       final String SYSTEM_DIALOG_REASON_GLOBAL_ACTIONS = "globalactions";
       final String SYSTEM_DIALOG_REASON_RECENT_APPS = "recentapps";
       final String SYSTEM_DIALOG_REASON_HOME_KEY = "homekey";

       @Override
       public void onReceive(Context context, Intent intent) {
           String action = intent.getAction();
           if (action.equals(Intent.ACTION_CLOSE_SYSTEM_DIALOGS)) {
               String reason =    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();
                       } else if    (reason.equals(SYSTEM_DIALOG_REASON_RECENT_APPS)) {
                           mListener.onHomeLongPressed();
                       }
                   }
               }
           }
       }
   }
}

OnHomePressed Interface

public interface OnHomePressedListener {
    public void onHomePressed();

    public void onHomeLongPressed();
}



回答2:


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

MainActivty.java

public class MainActivity extends AppCompatActivity {

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

    BroadcastReceiver broadcastRec = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            int datapassed = intent.getIntExtra("value", 0);
            tv_servicecounter.setText(String.valueOf(datapassed));

        }
    };

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    @Override
    protected void onCreate(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(
                new View.OnClickListener() {
                    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR1)
                    @Override
                    public void onClick(View v) {

                        Intent objIntent = new Intent(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(
                new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {

                        Intent objIntent = new Intent(MainActivity.this, ServiceDemo.class);

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

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

    @Override
    protected void onResume() {
        registerReceiver(broadcastRec, new IntentFilter("USER_ACTION"));
        super.onResume();
    }

    @Override
    protected void onStop() {
        this.unregisterReceiver(broadcastRec);
        super.onStop();
    }

    private ServiceConnection myConnection = new ServiceConnection() {

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

        public void onServiceDisconnected(ComponentName arg0) {
            isBound = false;
        }

    };

    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (isBound) {
            unbindService(myConnection);
            isBound = false;
        }
    }

}

DemoService.java

public class ServiceDemo extends Service {
    int i;
    private MyThread mythread;
    public boolean isRunning = false;
    Notification notification;

    @Override
    public void onCreate() {
        super.onCreate();
        Log.d(TAG, "onCreate");
        mythread = new MyThread();

    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {


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

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

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

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

    public void sendBrodcastMsg(int value) {
        Intent intent = new Intent();
        intent.setAction("USER_ACTION");
        intent.putExtra("value", value);
        sendBroadcast(intent);
    }

    @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN)
    class MyThread extends Thread {
        static final long DELAY = 100;

        @Override
        public void run() {
            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)
    public void shownotification() {
        Intent in = new Intent(this, MainActivity.class);
        PendingIntent pIntent = PendingIntent.getActivity(this, (int) System.currentTimeMillis(), in, 0);

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

        startForeground(101, notification);

    }

    public class MyLocalBinder extends Binder {
        ServiceDemo getService() {
            return ServiceDemo.this;
        }
    }

    private final IBinder myBinder = new MyLocalBinder();

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return myBinder;
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns: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">

    <TextView
        android:id="@+id/tv_activity_main_count"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="ABC"
        android:gravity="center"/>

    <Button
        android: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"/>

    <Button
        android: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-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <service
            android:name=".ServiceDemo"
            android:enabled="true">
        </service>

    </application>



回答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.



来源:https://stackoverflow.com/questions/43198159/can-we-add-a-counter-when-home-button-is-clicked-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!