[转]android detect screen on and screen off

来源:互联网 发布:三中三复式计算器软件 编辑:程序博客网 时间:2024/05/19 18:41
原文出自: http://blog.kenyang.net/2010/11/android-detect-screen-on-and-screen-off.html


android detect screen on and screen off

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

和偵測sd card一樣,

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

如:

?
1
2
3
4
5
6
<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如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
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如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
public class receiverScreen extends BroadcastReceiver {
 
 @Override
 public void onReceive(Context context, Intent intent) {
   
     if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)){
          //收到螢幕開啟的通知
     }else{
          //收到螢幕關閉的通知
     }
   
 }
 
}



接著就是在widget中去startService

如下:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
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());
   
  
 }
  
 
}
原创粉丝点击