Home  >  Q&A  >  body text

Android monitors headphone plugging and unplugging without opening the APP

The current demand is. Monitor the plugging and unplugging of headphones after turning on the phone or without opening the app. to perform different operations.
The current thinking is.
Start a service after booting, and monitor the headphone plugging and unplugging status in the service. If headphones are plugged in, open an Activity. Otherwise close the current Activity.
Is there something wrong with the whole idea??

漂亮男人漂亮男人2689 days ago1062

reply all(2)I'll reply

  • 扔个三星炸死你

    扔个三星炸死你2017-06-24 09:44:57

    The problem is how the service process survives

    reply
    0
  • 天蓬老师

    天蓬老师2017-06-24 09:44:57

    import android.app.ActivityManager;
    import android.app.Service;
    import android.content.BroadcastReceiver;
    import android.content.Context;
    import android.content.Intent;
    import android.content.IntentFilter;
    import android.os.IBinder;
    import android.util.Log;

    import java.util.List;

    public class HeadPhoneService extends Service {

    public HeadPhoneService() {
    }
    @Override
    public IBinder onBind(Intent intent) {
        // TODO: Return the communication channel to the service.
        throw new UnsupportedOperationException("Not yet implemented");
    }
    
    @Override
    public void onCreate() {
        super.onCreate();
        Log.e("xxxx","service start");
    }
    
    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(Intent.ACTION_HEADSET_PLUG);
        registerReceiver(headsetReceiver, intentFilter);
        return super.onStartCommand(intent, flags, startId);
    }
    
    @Override
    public void onDestroy() {
        Intent service = new Intent(this, HeadPhoneService.class);
        this.startService(service);
        super.onDestroy();
    }
    
    private BroadcastReceiver headsetReceiver=new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (Intent.ACTION_HEADSET_PLUG.equals(action)) {
                Log.e("xxxx","headsetchange");
                if (intent.hasExtra("state")) {
                    int state = intent.getIntExtra("state", 0);
                    if (state == 1) {
    
                    } else if(state == 0){
    
                    }
                    Log.e("xxxx","headphone"+state);
                }
            }
        }
    };
    

    }

    reply
    0
  • Cancelreply