android - 我们可以在 android 中单击主页按钮时添加一个计数器吗?

标签 android android-homebutton

我知道无法停止或覆盖主页按钮。有没有办法以某种方式扩展主页按钮,然后当它被点击时,我的计数器应该增加而不会干扰主页按钮的任何功能。

最佳答案

希望这对你有帮助。您应该为此使用服务和广播接收器。

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>

关于android - 我们可以在 android 中单击主页按钮时添加一个计数器吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43198159/

相关文章:

java - Android:线程停止工作

Android,如何通过广播接收器接收主页按钮点击?

android - 使用androidx的BottomNavigationView

android - 如何知道哪个 View 触发了我的 ActionMode?

android - 应用更新主题订阅

android - 拦截 Android 上的主页按钮

android - 从主屏幕开始 Activity

android - 在 android 布局中设置 id 失败

安卓长按home键

android - 按下主页按钮时如何终止 Activity ?