2014-05-01 34 views
1

我目前正試圖弄清楚,如何在android中獲取屏幕開/關事件。目前,只要MainActivity處於運行狀態,它就會工作。但是,只要我關閉活動,不知何故服務器和接收器停止工作(我沒有得到任何日誌消息了)。我想這個問題與某種接收機的動態註冊有關。只要應用程序關閉,接收器就會取消註冊(?)。我怎樣才能保持接收器活着? (在Manifest文件中聲明接收器是不可能的)。在應用程序未運行時獲取屏幕開/關事件

我得到了下面的代碼:

主要活動:

public class MainActivity extends Activity { 
@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 
    startService(new Intent(getApplicationContext(), ScreenOnOffService.class)); 
    } 
} 

ScreenReceiver:

public class ScreenReceiver extends BroadcastReceiver { 
@Override 
public void onReceive(final Context context, final Intent intent) { 
    Log.e("test","onReceive"); 
    if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)) { 
     Log.d("test","Screen Off "); 

    } else if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { 
     Log.d("test","Screen On ");} 
    } 
} 

ScreenOnOffService:

public class ScreenOnOffService extends Service { 

//Some unimportant code 
@Override 
public int onStartCommand(Intent intent, int flags, int startId) { 

    final IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON); 
    filter.addAction(Intent.ACTION_SCREEN_OFF); 
    filter.addAction(Intent.ACTION_USER_PRESENT); 
    final BroadcastReceiver mReceiver = new ScreenReceiver(); 
    registerReceiver(mReceiver, filter); 
    return super.onStartCommand(intent, flags, startId); 
    } 
} 

AndroidManifest:

<?xml version="1.0" encoding="utf-8"?> 

<application 
    android:allowBackup="true" 
    android:icon="@drawable/ic_launcher" 
    android:label="@string/app_name" 
    android:theme="@style/AppTheme" > 
    <activity 
     android:name="ch.ethz.inf.thesis.screenonoffproject.app.MainActivity" 
     android:label="@string/app_name" > 
     <intent-filter> 
      <action android:name="android.intent.action.MAIN" /> 

      <category android:name="android.intent.category.LAUNCHER" /> 
     </intent-filter> 
    </activity> 

    <service android:name=".ScreenOnOffService"> 
    </service> 

</application> 
</manifest> 

我缺少的東西讓我的服務還活着嗎?我希望有人能幫助我。

+1

看一看[這裏](http://stackoverflow.com/questions/8713361/keep-a-service-running-even-when -phone-是-睡着)。 –

+1

嘿史蒂夫,我想這不能解決我的問題(如果我沒有誤解某件事情):問題不在於我的服務在睡眠事件中停止運行,更多的是接收器不再工作。我猜想在關閉應用程序後它會被取消註冊。 – DonMushroom

+1

嘿史蒂夫再次,對不起,我錯了。它確實幫了我很多:D – DonMushroom

回答

0

嘗試在服務和完整路徑reciever如有

<service 
android:name="ch.ethz.inf.thesis.screenonoffproject.app.ScreenOnOffService"> 
</service> 
相關問題