保持活动在后台运行,直到用户不杀死或关闭应用程序? [英] Keep activity alive in background until user doesn't kill or close app?

查看:131
本文介绍了保持活动在后台运行,直到用户不杀死或关闭应用程序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以让Android活动在后台保持活动状态,直到用户不杀死或关闭该应用程序.

Can I keep Android activity alive in background, until user doesn't kill or close the application.

我想在某些特定的硬件按钮单击中检测到用户在后台的点击,因为onKeyDown在服务中不可用,因此我需要在后台保持活动状态,直到用户杀死该应用为止.

I want to detect user clicks in background some specific hardware button clicks, as onKeyDown is not available in service, I need to keep my activity alive in background until user kills the app.

android允许这种行为吗?

Does android allows such behavior ?

更新:

我能够使用以下方法解决此问题:

I was able to solve this using following approach :

1]使用前台服务, 参考: https://developer.android.com/guide/components/services. html#Foreground

1] Use foreground service, Ref : https://developer.android.com/guide/components/services.html#Foreground

2]要处理媒体按钮,请在Android 21 +(在前台服务的onCreate()中使用此代码)之后,使用以下方法:

2] To handle media button click use below approach after Android 21 + ( Use this code in onCreate() of your foreground service ) :

mediaSession = new MediaSessionCompat(this, TAG);
        mediaSession.setFlags(MediaSessionCompat.FLAG_HANDLES_MEDIA_BUTTONS);
        mediaSession.setCallback(new MediaSessionCompat.Callback() {
            @Override
            public boolean onMediaButtonEvent(Intent mediaButtonEvent) {
                if (mediaButtonEvent.getAction().equals(Intent.ACTION_MEDIA_BUTTON)) {
                    KeyEvent event = (KeyEvent) mediaButtonEvent.getParcelableExtra(Intent.EXTRA_KEY_EVENT);
                    if (KeyEvent.KEYCODE_HEADSETHOOK == event.getKeyCode() && event.getAction() == KeyEvent.ACTION_DOWN) {
                        Log.e(TAG, "Media Button clicked");
                        handleHeadphoneClick();
                    }
                }
                return false;
            }
        });
        mediaSession.setActive(true);

Ref: https://developer.android.com/guide/topics/media-apps/mediabuttons.html

推荐答案

简单来说,只需创建一个新的服务类即可.在这里,使用此类您可以在日志中看到硬件按钮单击事件. 在这里,我将音量键用作onKeyEvent .

Simply, just create a new service class. Here, using this class you are able to see the Hardware button click event in log. Here i am using volume key as a onKeyEvent.

public class Xtra extends Service {


@Override
public void onCreate() {
    // TODO Auto-generated method stub
    super.onCreate();

    final BroadcastReceiver vReceiver = new BroadcastReceiver() {

        @Override
        public void onReceive(Context context, Intent intent) {
            PowerManager powerManager = (PowerManager) getSystemService(POWER_SERVICE);
            boolean isScreenOn = powerManager.isScreenOn();


            if (!isScreenOn) {

                PowerManager pm = (PowerManager) getApplicationContext().getSystemService(Context.POWER_SERVICE);
                PowerManager.WakeLock mWakeLock = pm.newWakeLock((PowerManager.SCREEN_DIM_WAKE_LOCK | PowerManager.ACQUIRE_CAUSES_WAKEUP), "YourService");
                mWakeLock.acquire();
                // The screen has been locked
                // do stuff...
                Log.e("Do what you want to do from this service...", "Here screen is off..which do not show or work anything due to screen is off");
Toast.makeText(getActivity(), "Here screen is off..which do not show or work anything due to screen is off", Toast.LENGTH_SHORT).show();

} else {
                Log.e("Do what you want to do from this service...", "Here screen is on, works...");
Toast.makeText(getActivity(), "Here screen is on, works...", Toast.LENGTH_SHORT).show();

            }
        }

    };
    registerReceiver(vReceiver, new IntentFilter("android.media.VOLUME_CHANGED_ACTION"));
}

@Override
public int onStartCommand(Intent intent, int flags, int startId) {
    // TODO Auto-generated method stub
    return super.onStartCommand(intent, flags, startId);
    //43200000 schedules notification on every 12 hours
}


@Override
public void onDestroy() {
    // TODO Auto-generated method stub
    Log.e("BgService", "::>> Service Stopped...");
    super.onDestroy();
}

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

在您的活动中创建一个按钮单击事件以启动服务.它将在后台启动您的服务.

Make a button click event from your activity to start the service. It will starts your service in background.

Button btnSave;
btnSave.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
      //From here service starts when you click on a button.
           startService(new Intent(activity, Xtra.class));
        }
    });

不要忘记将此服务添加到您的清单中.

Don't forgot to add this service to your manifest.

<service android:name=".Xtra">
        <intent-filter>
            <action android:name="android.intent.action.MEDIA_BUTTON" />
        </intent-filter>
    </service>

当您单击btnSave时,它将启动您的服务.现在,只需转到主屏幕并单击音量键,您肯定会得到结果,因为它对我来说很好.

When you click on btnSave, it will starts your service. Now just move to home screen and click the volume key, you will surely get the result as it works fine for me.

这篇关于保持活动在后台运行,直到用户不杀死或关闭应用程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆