2012-08-07 61 views
1

我正在研究的應用程序中,當用戶從手機取下耳機時,它的顯示警報 對話框,以及當用戶按下ok按鈕時,它開始新的活動。我的代碼活動code`如何當我從手機上取下耳機時在主屏幕上顯示警報對話框

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 file.`

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

      > 
     </activity> 

` 作秀警告對話框的Android原生畫面上phone.but它不是work.when我deattached 耳機那裏沒有對話框在主屏幕上。當我按下應用程序圖標,然後它的顯示對話框在application.please任何機構給我一些想法。 在此先感謝

回答

1

對於您的問題,你必須註冊爲ACTION_HEADSET_PLUG intent一個接收器,並從,你可以實現你自己的邏輯receiver class to catch that broadcast

Check this answer以供參考。

1

我想在使用耳機時,廣播接收機就是您要找的。他們幫助您處理註冊事件的現場活動。看看this post

相關問題