java - 服务中按下电源按钮的事件监听器

标签 java android android-intent service keyevent

我想监听服务中的电源键事件。

如何才能做到这一点?

目前我正在使用一个应用程序,我需要从后台运行的服务监听电源按钮的某些事件,即使应用程序被终止或停止也是如此。

我可以设法得到它。

但是当我终止/停止应用程序时,服务就会停止。

我该如何克服这个问题?

目前我正在使用的代码:

服务等级:

public class SampleService extends Service
{

    SettingContentObserver mSettingsContentObserver;
    AudioManager mAudioManager;
    private ComponentName mRemoteControlResponder;
    private Intent intent;

     @Override
        public int onStartCommand(Intent intent, int flags, int startId) 
        {        
            Log.v("StartServiceAtBoot", "StartAtBootService -- onStartCommand()");
            // We want this service to continue running until it is explicitly
            // stopped, so return sticky.
            return START_STICKY;            
        }

     @Override
     public void onStart(Intent intent, int startId) {
         boolean screenOn = intent.getBooleanExtra("screen_state", false);
         if (!screenOn) {
             Toast.makeText(getApplicationContext(), "On", Toast.LENGTH_SHORT).show();
         } else {
             Toast.makeText(getApplicationContext(), "Off", Toast.LENGTH_SHORT).show();
         }
     }

        public void onCreate()
        {
            mSettingsContentObserver = new SettingContentObserver(this,new Handler());
            getApplicationContext().getContentResolver().registerContentObserver
                (android.provider.Settings.System.CONTENT_URI, true, mSettingsContentObserver );
            mAudioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
            mRemoteControlResponder = new ComponentName(getPackageName(),
                    StartAtBootServiceReceiver.class.getName());

            IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
            filter.addAction(Intent.ACTION_SCREEN_OFF);
            BroadcastReceiver mReceiver = new StartAtBootServiceReceiver();
            registerReceiver(mReceiver, filter);
        }

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

    public void onDestroy()
    {       
        getApplicationContext().getContentResolver().unregisterContentObserver(mSettingsContentObserver);
    }
}

广播接收器类:

public class StartAtBootServiceReceiver extends BroadcastReceiver
{
    static boolean wasScreenOn;
    private boolean screenOff;

    public void onReceive(Context context, Intent intent) 
    {
        if(intent.getAction().equals(Intent.ACTION_SCREEN_OFF))
        {
            wasScreenOn = false;
            Toast.makeText(context, "Power Off", Toast.LENGTH_SHORT).show();
        }
        else if(intent.getAction().equals(Intent.ACTION_SCREEN_ON))
        {
            wasScreenOn = true;
        }
        Intent i = new Intent(context, SampleService.class);
        i.putExtra("screen_state", screenOff);
        i.setAction("com.example.antitheft.SampleService");
        context.startService(i);
//      
        if (intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
            Intent i1 = new Intent();
            i1.setAction("com.example.sampleonkeylistener.MainActivity");
            context.startService(i1);
        }
    }
}

上面给出的是示例代码,我也已获得用户许可创建了 AndroidManifest.xml 文件,但如果应用程序被终止或停止,我将无法获得该应用程序的继续服务。

提前致谢。

最佳答案

@Override
public void onDestroy() {

    super.onDestroy();
    startService(new Intent(this, SampleService.class));

}

这是确保服务永远不会停止的一种方法,即使用户想要销毁它。 这只是实现您想要实现的目标的一种方法。

其次,您可以尝试使用 startForeground() 在“前台”运行服务。

此外,请确保在服务的 onStartCommand() 中返回“START_STICKY”(您在共享的示例代码中执行此操作,我相信您也在应用程序的代码中执行此操作:))。

这将确保如果该服务的进程在启动时被终止(从 onStartCommand(Intent, int, int) 返回后),则将其保留在启动状态,但不保留此传递的 Intent 。稍后系统将尝试重新创建服务。

您可能会在下面的链接中找到一些额外的指示/提示,以确保您的服务不会停止。

How can we prevent a Service from being killed by OS?

只需挑选最适合需求/实现的方法即可。

关于java - 服务中按下电源按钮的事件监听器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27844381/

相关文章:

如果已经作为根目录在后台堆栈中,Android Activity 未启动?

android - 如何 Intent JSONArray?

java - 如何列出内部存储中的所有子目录?

java - 如何在kotlin中获取匿名类中的父类

java - java中的Unicode编码

java - 将整数排列的完整 ArrayLists 排序为决策树结构

php - 从 android 连接到数据库 mySQL 失败

java - 实时验证(点击按钮前)

Java try-catch 使用 do-while 循环进行输入验证

java - 无法打印俄语字符