【问题标题】:How to keep running an IntentService even when Home button is pressed即使按下主页按钮,如何继续运行 IntentService
【发布时间】:2016-08-15 13:19:39
【问题描述】:

我遇到了一个奇怪的问题,当我最小化我的应用程序(按主页按钮)时,我的IntentService 停止了。 IntentService 中有一个 while 循环,它在 IntentService 中运行良好,直到应用程序在前台运行。

IntentService类如下:

public class MainService extends IntentService {

    public MainService() {
        super("MainService");
    }

    @Override
    protected void onHandleIntent(Intent intent) {
        try {
            Instrumentation inst = new Instrumentation();

            while (true) {
                inst.sendKeyDownUpSync(KeyEvent.KEYCODE_VOLUME_DOWN);
            }
        } catch(Exception e){
            e.printStackTrace();
        }
    }
}

并从我的Activity 类中将其称为:

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void mainButtonClick(View view) {
        Intent intentX = new Intent(this, MainService.class);
        this.startService(intentX);
    }
}

【问题讨论】:

    标签: android intentservice android-intentservice


    【解决方案1】:

    你检查过你的日志吗?这不是IntentService 的问题,而是您在离开应用程序后无权更改音量的问题。它应该崩溃:

    W/System.err: java.lang.SecurityException: 注入另一个 应用程序需要 INJECT_EVENTS 权限

    您需要成为系统应用程序才能使用此权限,因此这在普通 Android 设备上是不可能的。

    【讨论】:

    • 是的,那里有完全相同的东西。
    • 那么唯一的办法就是root设备?
    • @KhurshidAbbas 不幸的是它不是那么简单,可能唯一的方法是从源代码为您的设备构建 Android,您可以阅读更多here
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2019-06-13
    • 2012-08-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-09
    相关资源
    最近更新 更多