android - 解锁屏幕时启动服务

标签 android service

解锁屏幕后如何启动服务?可能是 AlarmAanger 之类的东西!

context.startService(new Intent(context, Widget.class));

最佳答案

为了检测屏幕打开和屏幕关闭,注册一个广播接收器,如:

AndroidManifest.xml:

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

在 Activity 或服务中:

 try {
              IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);

              filter.addAction(Intent.ACTION_SCREEN_OFF);
filter.addAction(Intent.ACTION_USER_PRESENT);

              BroadcastReceiver mReceiver = new receiverScreen();

              registerReceiver(mReceiver, filter);
         } catch (Exception e) {

         }

如果屏幕打开/关闭,系统会通知您的接收代码:

public class receiverScreen extends BroadcastReceiver {

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

         if (intent.getAction().equals(Intent.ACTION_SCREEN_ON)){

         }
        if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)){

         }
if (intent.getAction().equals(Intent.ACTION_USER_PRESENT)){

         }
     }

    }

关于android - 解锁屏幕时启动服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18037397/

相关文章:

java - 致命异常 : android. app.RemoteServiceException Context.startForegroundService() 然后没有调用 Service.startForeground()

javascript - Controller 中未定义的服务

Android:如何从 Activity 到 Service 到第二个 Activity

android - 无法实现 notifyDataSetChanged()

android - 如何编写来自 Android Market 的 Android 应用程序更新

android - 可以在触摸时显示我的通知栏和标题栏吗?

android - 警报管理器或服务

wcf - 通过 WCF 服务返回数据集时出现问题

android - 我必须在 Android Studio 的子项目中添加 .aar 文件作为库。它给了我一个错误。

java - 将 JSON 转换为 Android Bundle