01 November 2010
android detect screen on and screen off

android偵測螢幕的關閉與開啟,

和偵測sd card一樣,

Intent.ACTION_SCREEN_OFF和Intent.ACTION_SCREEN_ON是不能在AndroidManifest.xml裡面宣告的

如:

<receiver android:name="receiverScreen"> 
<intent-filter>
<action android:name="android.intent.action.SCREEN_ON" />
<action android:name="android.intent.action.SCREEN_OFF" />
</intent-filter>
</receiver>


這樣子的宣告沒有用,你永遠都receive不到任何action

詳細原因我也不知道,但是可以透過registerReceiver去實作,

這裡舉個例子,先啟動一個service,由這個service去registerReceiver

由service啟動的好處是,service可以常駐,

如果你用acitivity去registerReceiver

這個acitivity關閉以後,你一樣receive不到任何action

且如果你只是想偵測acitivity的關閉與否的話,可以直接利用onResume和onPause去偵測即可

不用特地去registerReceiver


但是如果今天你有一個widget在桌面,

且我們是無法透過widget去registerReceiver,

會出現exception(ReceiverCallNotAllowedException)

所以一定得透過service去啟動。

service的code如下:

public class serviceScreen extends Service {

@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}

@Override
public void onStart(Intent intent, int startId) {
super.onStart(intent, startId);
try {
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);

filter.addAction(Intent.ACTION_SCREEN_OFF);

BroadcastReceiver mReceiver = new receiverScreen();

registerReceiver(mReceiver, filter);
} catch (Exception e) {
Log.d("main",e.toString());
}
}

}




receiver的code如下:

public class receiverScreen extends BroadcastReceiver {

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

if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
//收到螢幕開啟的通知
}else{
//收到螢幕關閉的通知
}

}

}





接著就是在widget中去startService

如下:

public class widgetSmall extends AppWidgetProvider {


@SuppressWarnings("static-access")
@Override
public void onUpdate(Context context, AppWidgetManager appWidgetManager,int[] appWidgetIds) {
super.onUpdate(context, appWidgetManager, appWidgetIds);

//啟動一個service
context.startService(new Intent(context, serviceScreen.class));


}


@SuppressWarnings("static-access")
@Override
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);


//當這個widget被刪除時,就stopService
context.stopService(new Intent(context, serviceScreen.class) );

android.os.Process.killProcess(android.os.Process.myPid());


}


}











blog comments powered by Disqus