【发布时间】:2020-12-29 22:04:24
【问题描述】:
我有一台装有 Android 9 的设备,我正在开发一个根据当前日期和时间显示内容的应用程序。我希望它定期检查是否有新内容可用并通知用户。此外,当用户关闭应用程序时,我希望它也能正常工作。例如,我的电子邮件应用程序在关闭时也会显示有关新电子邮件的通知。
我的方法是接收一般广播(Intent.ACTION_USER_PRESENT 和 Intent.ACTION_SCREEN_ON),在接收时运行计时器,然后定期检查新内容。我知道用户必须为此启动我的应用程序一次 (Broadcast receiver not working in ICS if the app is not started atleast once)。如果用户使用多任务按钮并向上滑动我的活动以将其关闭,则该方法不成功。
即使用户关闭了我的应用程序/活动,我如何才能接收广播。
这里有很多个帖子,问的都是一样的,但大部分似乎都已经过时了!我已经尝试了很多,但我没有设法让它工作!因此,我为 API 28 设置了一个示例应用程序,我想再次提出这个问题,但这次是一个已定义的示例。那么应该很容易检查所提出的解决方案是否真的有效!
- 在 AndroidStudio 中使用
File->New->New Project...->Empty Activity->Language: Java, SDK: API 28创建一个空活动。 - 添加类
MyBroadcastReceiver,内容如下:
package org.test.myapplication;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.widget.Toast;
public class MyBroadcastReceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
Toast.makeText(context, "Hurray! I have received the broadcast!", Toast.LENGTH_LONG).show();
}
}
- 修改
MainActivity类,使其内容如下:
package org.test.myapplication;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.util.Log;
import androidx.appcompat.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity
{
private static BroadcastReceiver broadcastReceiver = null;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (null == broadcastReceiver)
{
// Register broadcast receiver (only a running application my do that)
IntentFilter filter = new IntentFilter(Intent.ACTION_USER_PRESENT);
filter.addAction(Intent.ACTION_SCREEN_ON);
Log.i("MainActivity", "Registered broadcast receiver.");
broadcastReceiver = new MyBroadcastReceiver();
registerReceiver(broadcastReceiver, filter);
}
}
}
在安装和运行 Activity 时,每当我注销并再次登录时,我都会看到 toast。但是,一旦我向上滑动活动以关闭它,我就再也看不到吐司了。我该如何改变呢?
【问题讨论】:
标签: java android broadcastreceiver