要求:设置一个android应用程序开机启动一个服务,此服务用来监听情景模式的切换。
首先要知道在android中开机启动程序是通过广播机制实现的,在android手机启动完成之后,系统会发送一个名叫android.intent.action.BOOT_COMPLETED的广播,所以我们只要在程序中接收这个广播,然后启动一个后台服务,就会实现程序一开机即启动。
对于监听情景模式的切换,android手机跟其他手机不太一样,没有那些诸如会议模式、户外模式、自定义模式等那么多的模式。系统内置的只有正常模式跟静音模式两种可选,而且是长按关机按钮才出现的。如下图:
一开始我以为系统也应该会发送一个广播,但是找了很多资料没找着。后来我从王涛那学到了一个不错的技巧。假设你现在不知道系统到底会不会发情景模式切换的广播,而且找了很多资料也没有涉及诸如此类的问题,那么现在你可以从LogCat中查看日志文件。在我点击上图中静音模式切换的按钮时,会得到如下日志:
很明显,系统是发了广播的。所以我们同样只要在程序中接收这个广播就OK了。
Demo代码如下:
MainActivity:
package org.sunchao; import android.app.Activity; import android.os.Bundle; public class MainActivity extends Activity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); } }
BroadcastReceiver:
package org.sunchao; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.widget.Toast; public class BootReceiver extends BroadcastReceiver { @Override public void onReceive(Context context, Intent intent) { // 监听情景切换 if (intent.getAction().equals("android.media.RINGER_MODE_CHANGED")) { Toast.makeText(context, "情景模式已切换", Toast.LENGTH_LONG).show(); } // 设置开机启动 Intent intent2 = new Intent(context, BackgroundService.class); intent2.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); context.startService(intent2); } }
BackgroundService:
package org.sunchao; import android.app.Service; import android.content.Intent; import android.os.IBinder; import android.util.Log; public class BackgroundService extends Service { private static String TAG = "BackgroundService"; @Override public void onCreate() { Log.i(TAG, "onCreate()"); super.onCreate(); } @Override public void onStart(Intent intent, int startId) { Log.i(TAG, "onStart()"); super.onStart(intent, startId); } @Override public void onDestroy() { Log.i(TAG, "onDestroy()"); super.onDestroy(); } @Override public IBinder onBind(Intent intent) { Log.i(TAG, "onBind()"); return null; } }
AndroidManifest.xml:
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android" package="org.sunchao" android:versionCode="1" android:versionName="1.0"> <uses-sdk android:minSdkVersion="8" /> <application android:icon="@drawable/icon" android:label="@string/app_name"> <activity android:name=".MainActivity"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> </activity> <service android:name=".BackgroundService" /> <receiver android:name=".BootReceiver"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> <action android:name="android.media.RINGER_MODE_CHANGED" /> </intent-filter> </receiver> </application> <uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" /> </manifest>
以上代码开机启动测试成功,查看后台运行的服务(Boot_Complete):
进行模式切换监听也是OK的: