Android monitors headphone plugging and unplugging without opening the APP
漂亮男人
漂亮男人 2017-06-24 09:42:57
0
2
1011

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??

漂亮男人
漂亮男人

reply all(2)
扔个三星炸死你

The problem is how the service process survives

Peter_Zhu

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);
            }
        }
    }
};

}

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!