編輯:關於Android編程
在Android下實現檢測耳機插入和拔出,需要建立一個BroadcastReceiver,用來監聽"android.intent.action.HEADSET_PLUG"廣播。
實現步驟:
1.創建一個BroadcastReceiver的子類,並重寫onReceive()方法,在該方法中編寫接收到廣播後的處理邏輯;
2.創建一個Activity類,在onCreate()方法中使用registerReceiver()方法進行注冊監聽廣播;
3.在Activity中重寫onDestory()方法,使用unregisterReceiver()注銷監聽廣播。
具體實現代碼如下:
廣播接收器類
package com.leigo.demo.receiver; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; /** * Created by Administrator on 2014/8/27. */ public class HeadsetDetectReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { String action = intent.getAction(); if (Intent.ACTION_HEADSET_PLUG.equals(action)) { if (intent.hasExtra("state")) { int state = intent.getIntExtra("state", 0); if (state == 1) { Toast.makeText(context, "插入耳機", Toast.LENGTH_SHORT).show(); } else if(state == 0){ Toast.makeText(context, "拔出耳機", Toast.LENGTH_SHORT).show(); } } } } }
package com.leigo.demo; import android.app.Activity; import android.content.BroadcastReceiver; import android.content.Intent; import android.content.IntentFilter; import android.os.Bundle; import android.view.Menu; import android.view.MenuItem; import com.leigo.demo.receiver.HeadsetDetectReceiver; public class MainActivity extends Activity { private BroadcastReceiver receiver; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); /** * Broadcast Action: Wired Headset plugged in or unplugged * The intent will have the following extra values: * state - 0 for unplugged, 1 for plugged. * name - Headset type, human readable string * microphone - 1 if headset has a microphone, 0 otherwise */ receiver = new HeadsetDetectReceiver(); IntentFilter intentFilter = new IntentFilter(); intentFilter.addAction(Intent.ACTION_HEADSET_PLUG); registerReceiver(receiver, intentFilter); } @Override protected void onDestroy() { super.onDestroy(); unregisterReceiver(receiver); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // automatically handle clicks on the Home/Up button, so long // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); if (id == R.id.action_settings) { return true; } return super.onOptionsItemSelected(item); } }
突然發現好久沒有寫博客了,一直放到筆記裡面,今天update一下。最近做的一個項目中,是盒子+電視,用戶通過遙控器來操作。這裡只是說下GridView在當前業務下的簡單使
只是簡單的實現了效果,界面沒怎麼做優化,不過那都是次要的啦!!相信大家都迫不及待的想看效果圖了吧,其中主要的彩票視圖類和橡皮擦類都是通過代碼的方式構建視圖,布
MIUI 8公測之後,MIUI官方微博隔一段時間就會將米粉集中反饋的問題以長微博的形式進行解答,同時爆料一些MIUI的新功能。繼上次透露MIUI 8將新增手
調用系統自帶的文件浏覽器這很簡單:/** 調用文件選擇軟件來選擇文件 **/ private void showFileChooser() { intent = ne