当我从手机上分离耳机时,如何在主屏幕上显示警告对话框

时间:2012-08-07 06:31:23

标签: android android-alertdialog

我正在开发应用程序,当用户将耳机从手机上移除时显示警报 对话框,当用户按下确定按钮然后启动新活动。我的代码活动代码`

package com.gabriel.activity;

import java.util.HashMap;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.res.Resources;
import android.location.Criteria;
import android.location.Location;
import android.location.LocationListener;
import android.location.LocationManager;
import android.net.Uri;
import android.os.Bundle;
import android.provider.MediaStore.Audio;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageView;
import android.widget.RemoteViews;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.ToggleButton;



import com.gabriel.database.AlarmCore;
import com.gabriel.database.ContactObject;
import com.gabriel.database.FBFriendObject;
import com.gabriel.utility.GBAlarmManager;
import com.gabriel.utility.GBConstants;


public class HomeActivity extends Activity implements OnClickListener {

    private TextView _SecurityLevel, _AlarmType, _Trigger;
    static TextView ActiveText;
    private HashMap<String, String> _SettingMap;
    private SharedPreferences _Preferences;
    private ToggleButton _AlarmButton;
    private ImageView _GabrielIconView;
    private Resources _Resources;
    private String _TriggerBy;
    private Context context;
    private GBAlarmManager alarmManager;
    private AlarmCore alarmCore;
    private boolean isTriggered = false;
    private boolean isHeadPhoneAttached = false;
    private Intent serviceIntent;
    private GabrielApplication application;
    private LocationManager locationManager;
    private GpsLocationListener gpsLocationListener;
    private NetworkLocationListener networkLocationListener;

    private ContactObject contactObject;
    private FBFriendObject fBFriendObject;
    /*private static final CharSequence Gabriel = "Gabriel";
    private static final CharSequence HeadphoneDeatched = "Headphone Deattached";
*/
    /*
     * registerObject = new RegisterObject(this); countryObject = new
     * CountryObject(context); registerCore =
     * registerObject.getRegistrationInfo();
     */

    private static final long MINIMUM_DISTANCE_CHANGE_FOR_UPDATES = 0; // in
                                                                        // Meters
    private static final long MINIMUM_TIME_BETWEEN_UPDATES = 0; // in
                                                                // Milliseconds
    private static final int SUCCESS_DIALOG = 200;

    private static final int Headphone_DIALOG = 250;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.home);
        context = this;
        application = (GabrielApplication) getApplication();

        contactObject = new ContactObject(this);
        contactObject.getActiveContacts();

        fBFriendObject = new FBFriendObject(this);
        fBFriendObject.getActiveFriends();

        ActiveText = (TextView) findViewById(R.id.ActiveText);
        _SecurityLevel = (TextView) findViewById(R.id.securityLevelText);
        _AlarmType = (TextView) findViewById(R.id.AlarmTypeText);
        _Trigger = (TextView) findViewById(R.id.TriggerText);
        _AlarmButton = (ToggleButton) findViewById(R.id.AlarmTrigger);
        _GabrielIconView = (ImageView) findViewById(R.id.gabrielIcon);

        _Resources = getResources();
        alarmManager = new GBAlarmManager(context);
        _AlarmButton.setOnClickListener(this);
        _GabrielIconView.setOnClickListener(this);

        // ContactList = (ListView) findViewById(R.id.contactList);

        if (!application.isServiceStarted()) {
            serviceIntent = new Intent(GBConstants.GABRIEL_SERVICE);
            startService(serviceIntent);
        }
        initHeadPhone();

        locationManager = (LocationManager) getSystemService(Context.LOCATION_SERVICE);
        gpsLocationListener = new GpsLocationListener();
        networkLocationListener = new NetworkLocationListener();

        locationManager.requestLocationUpdates(
                LocationManager.NETWORK_PROVIDER, MINIMUM_TIME_BETWEEN_UPDATES,
                MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, networkLocationListener);
        locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER,
                MINIMUM_TIME_BETWEEN_UPDATES,
                MINIMUM_DISTANCE_CHANGE_FOR_UPDATES, gpsLocationListener);
        application.setCurrentLocation(getBestLocation());
    }

    @Override
    protected void onResume() {
            super.onResume();
            if (application.isMessageSent()) {
                    application.setMessageSent(false);
                    showDialog(SUCCESS_DIALOG);
            }
            initSettings();
    }

    private void initSettings() {
        _SettingMap = GBConstants.getSettingsMap();
        _Preferences = getSharedPreferences(GBConstants.GABRIEL_PREF,
                Context.MODE_PRIVATE);
        _SecurityLevel.setText(_Preferences.getString(
                GBConstants.SECURITY_LEVEL,
                _SettingMap.get(GBConstants.SECURITY_LEVEL)));
        _AlarmType.setText(_Preferences.getString(GBConstants.ALARM,
                _SettingMap.get(GBConstants.ALARM)));
        _Trigger.setText(_Preferences.getString(GBConstants.TRIGGER_OPTIONS,
                _SettingMap.get(GBConstants.TRIGGER_OPTIONS)));
        _TriggerBy = _Trigger.getText().toString().trim();
        if (!isTriggered) {
            setGabrielIconRed();
        }
    }

    @Override
    public void onBackPressed() {
        return;
    }

    private void setGabrielIconRed() {
        if (_TriggerBy.equals(GBConstants.PANIC_BUTTON)) {
            _GabrielIconView.setImageDrawable(_Resources
                    .getDrawable(R.drawable.panic_button_black));
        } else {
            _GabrielIconView.setImageDrawable(_Resources
                    .getDrawable(R.drawable.black));
        }
        isTriggered = false;
        _AlarmButton.setChecked(false);
    }

    private void setGabrielIconGreen() {
        if (_TriggerBy.equals(GBConstants.PANIC_BUTTON)) {
            _GabrielIconView.setImageDrawable(_Resources
                    .getDrawable(R.drawable.panic_button_green));
        } else {
            _GabrielIconView.setImageDrawable(_Resources
                    .getDrawable(R.drawable.green));
        }
        isTriggered = true;
    }

    @Override
    public void onClick(View v) {
        ToggleButton triggerBtn;
        switch (v.getId()) {

        case R.id.AlarmTrigger:
            triggerBtn = (ToggleButton) v;
            if (triggerBtn.isChecked()) {
                ActiveText.setText("Activate");
                if (_TriggerBy.equals(GBConstants.HEADPHONE_BUTTON)) {
                    if (contactObject.getActiveContacts().isEmpty() && (fBFriendObject.getActiveFriends().isEmpty())) {
                        ActiveText.setText("Deactivate");
                        _AlarmButton.setChecked(false);
                        Toast.makeText(this, "PLEASE ADD CONTACT/FRIEND",
                                Toast.LENGTH_LONG).show();
                        return;
                    }

                    if (!isHeadPhoneAttached) {
                        ActiveText.setText("Deactivate");
                        _AlarmButton.setChecked(false);
                        Toast.makeText(context, "Please Attached Your Headphones.",
                                Toast.LENGTH_SHORT).show();
                        return;
                    }
                }
                setGabrielIconGreen();
                /*startService(new Intent(this, MyService.class));*/

            } else {
                ActiveText.setText("Deactivate");
                setGabrielIconRed();
            }
            break;

        case R.id.gabrielIcon:
        if (isTriggered && _TriggerBy.equals(GBConstants.PANIC_BUTTON)) {
                if (contactObject.getActiveContacts().isEmpty() && (fBFriendObject.getActiveFriends().isEmpty())) {
                Toast.makeText(this, "PLEASE ADD CONTACT/FRIEND",
                            Toast.LENGTH_LONG).show();
                    return;
                /*}
                if(aactvity.toggleFacebook.isChecked()){
                        core.isFacebookOn();
                }
                else{
                Toast.makeText(this, "FACEBOOK IS NOT CONNECTED",Toast.LENGTH_LONG).show();
                return;
                }   
                        */
                }
                    callTriggerActivity();
                }
                default:
            break;
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
    }

    @Override
    public void finish() {
        super.finish();
        locationManager.removeUpdates(gpsLocationListener);
        locationManager.removeUpdates(networkLocationListener);
    }

    private void callTriggerActivity() {
        Intent intent = new Intent(context, TriggerActivity.class);
        alarmCore = alarmManager.loadAlarmSettings(_AlarmType.getText()
                .toString().trim());
        intent.putExtra(getString(R.string.alarmObj), alarmCore);
        startActivity(intent);

        isTriggered = false;

    }

    public void initHeadPhone() {
        registerReceiver(new BroadcastReceiver() {

            @Override
            public void onReceive(Context context, Intent intent) {

                if (intent.hasExtra("state")) {
                    int state = intent.getIntExtra("state", 0);
                    if (isHeadPhoneAttached && state == 0) {
                        isHeadPhoneAttached = false;
                        if (isTriggered) {
                            if (contactObject.getActiveContacts().isEmpty()) {
                                Toast.makeText(context,
                                        "PLEASE ADD CONTACT/FRIEND",
                                        Toast.LENGTH_LONG).show();
                            } else {
                                /* createNotification();*/
                                /*callTriggerActivity();*/
                                showDialog(Headphone_DIALOG);
                            }
                        }
                    } else if (!isHeadPhoneAttached && state == 1) {
                        isHeadPhoneAttached = true;
                    }
                }
            }
        }, new IntentFilter(Intent.ACTION_HEADSET_PLUG));
    }


    /*public void createNotification() {

        NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);

        for (int i = 0; i <= 10; i++) {

            Notification notification = new Notification(R.drawable.app_icon,
                    HeadphoneDeatched, System.currentTimeMillis());
            Intent notifyIntent = new Intent(Intent.ACTION_MAIN);
            notifyIntent.setClass(getApplicationContext(), Main.class);
            Intent intent = new Intent(Intent.ACTION_MAIN);
            intent.setClass(this,TriggerActivity.class);
            notification.flags |= Notification.FLAG_AUTO_CANCEL;
            PendingIntent pendingIntent=PendingIntent.getActivity(this, 0, intent, 0);
            notification.setLatestEventInfo(this, Gabriel, HeadphoneDeatched, pendingIntent);
            PendingIntent activity = PendingIntent.getActivity(this, 0, intent,
                    0);
            notification.defaults |= Notification.DEFAULT_SOUND;
            notification.sound = Uri.withAppendedPath(Audio.Media.INTERNAL_CONTENT_URI, "6");
            notification.contentIntent = activity;
            notificationManager.notify(0, notification);


            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
            }
        }
    }*/
    private class GpsLocationListener implements LocationListener {

        public void onLocationChanged(Location location) {
            application.setCurrentLocation(location);
        }

        public void onStatusChanged(String s, int i, Bundle b) {

        }

        public void onProviderDisabled(String s) {

        }

        public void onProviderEnabled(String s) {

        }

    }

    private class NetworkLocationListener implements LocationListener {

        public void onLocationChanged(Location location) {
            application.setCurrentLocation(location);
        }

        public void onStatusChanged(String s, int i, Bundle b) {

        }

        public void onProviderDisabled(String s) {

        }

        public void onProviderEnabled(String s) {

        }

    }

    private Location getBestLocation() {
        Criteria criteria = new Criteria();
        criteria.setAccuracy(Criteria.ACCURACY_FINE);
        criteria.setAltitudeRequired(false);
        criteria.setBearingRequired(false);
        criteria.setCostAllowed(true);
        String strLocationProvider = locationManager.getBestProvider(criteria,
                true);
        if (strLocationProvider == null) {
            strLocationProvider = LocationManager.GPS_PROVIDER;
        }
        return locationManager.getLastKnownLocation(strLocationProvider);
    }

    @Override
    protected Dialog onCreateDialog(int id) {
        Dialog dialog = null;
        AlertDialog.Builder builder = new Builder(context);

        switch (id) {
        case SUCCESS_DIALOG:
            builder.setTitle(getString(R.string.app_name));
            builder.setMessage("Panic messages have been sent with your position.");
            builder.setPositiveButton("Continue", null);
            builder.setCancelable(false);
            dialog = builder.create();
            break;

        case Headphone_DIALOG:
        /*  dialog.setContentView(R.layout.home); */
            builder.setTitle(getString(R.string.app_name));
            builder.setMessage("Headphone Is Deattached The Press Ok To Sent Panic Message.");
            builder.setPositiveButton("Ok",new positiveButtonListener());
            builder.setCancelable(false);
            dialog = builder.create();
            break;
        default:
            break;
        }
        return dialog;
    }
    private class positiveButtonListener implements
    android.content.DialogInterface.OnClickListener {

@Override
public void onClick(DialogInterface dialog, int which) {
    callTriggerActivity();
}
}

}

我改变了我的manifest.xml文件。

<activity
            android:name="HomeActivity"
            android:screenOrientation="portrait"
             android:launchMode="singleInstance"
             android:taskAffinity=""
             android:theme="@android:style/Theme.Dialog"

            >
        </activity>

` 在Android手机的原生屏幕上显示警告对话框。但它不起作用。当我脱离时 主屏幕上没有对话框。当我按应用程序图标然后在应用程序中显示对话框。请任何机构给我一些想法。 提前致谢

2 个答案:

答案 0 :(得分:1)

对于您的问题,您必须为 ACTION_HEADSET_PLUG intent 注册一个接收器并从中创建一个receiver class to catch that broadcast,您可以实现自己的逻辑。

Check this answer以获取更多参考资料。

答案 1 :(得分:1)

我想在使用耳机时,您正在寻找广播接收器。它们可以帮助您处理已注册事件的实时事件。看看this post