2017-05-09 85 views
-2

當應用程序正在運行時,我能夠接收屏幕狀態,但是當應用程序停止時,我無法接收它。Android如何在屏幕開啓時接收廣播

這裏我的代碼的LockService

public class LockService extends Service { 
@Override 
public IBinder onBind(Intent intent) { 
    return null; 
} 

@Override 
public void onCreate() { 
    super.onCreate(); 
} 
@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); 
    Log.e("Action","Screen"); 
    final BroadcastReceiver mReceiver = new ScreenReceiver(); 
    registerReceiver(mReceiver, filter); 
    Log.e("Sample","Screen"); 
    return super.onStartCommand(intent, flags, startId); 

} 
public class LocalBinder extends Binder { 
    LockService getService() { 
     return LockService.this; 
    } 
} 
} 

廣播接收器

public class ScreenReceiver extends BroadcastReceiver { 
Intent intent; 
@Override 
public void onReceive(final Context context, Intent intent) { 
    if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)) { 
     Log.e("Screen state"," ON"); 
     Intent i = new Intent(context, MainActivity.class); 
     i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); 
     context.startActivity(i); 
    } 
} 
} 

MainActivity在OnCreate活動

startService(new Intent(getApplicationContext(), LockService.class)); 

的Manifest.xml

<service android:name=".LockService"> 
    <intent-filter> 
     <action android:name="android.intent.action.ACTION_SCREEN_ON"/> 
     <action android:name="android.intent.action.ACTION_SCREEN_OFF"/> 
     <action android:name="android.intent.action.ACTION_USER_PRESENT"/> 

    </intent-filter> 
</service> 

我想,當用戶喚醒電話

+2

嗨,看看這個問題和答案。 http://stackoverflow.com/q/13307565/5241603 –

+0

即使應用程序停止工作嗎? – KidPPAP

+0

該鏈接僅在應用程序運行時纔有效 – KidPPAP

回答

0

我的代碼工作,開始一個活動。只是我的手機不穩定,我重新格式化手機,然後我的應用程序完美地工作。感謝您的投入。

電話:小米彌5 操作系統:Android的6.0