[英]android broadcastreceiver auto start on boot up
My AndroidManifest.xml
contains: 我的AndroidManifest.xml
包含:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
and 和
<receiver android:name=".MyBroadcastReceiver" android:enabled="true" android:exported="false"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" /> </intent-filter> </receiver>
and MyBroadcastReceiver 和MyBroadcastReceiver
class MyBroadcastreceiver extends BroadcastReceiver
{
@Override
public void onReceive(Context context, Intent intent)
{
context.startService(new Intent(context, MainService.class));
//Toast.makeText(context, " O ", Toast.LENGTH_SHORT).show();
new AlertDialog.Builder(context)
.setTitle("OK")
.setMessage("OK")
.setPositiveButton("ㅇㅇ", null)
.setCancelable(false)
.show();
}
}
BUT, 但,
I can not see the AlertDialog after reboot. 重新启动后看不到AlertDialog 。
I launched the application many times too... 我也多次启动了该应用程序...
How can I make broadcastreceiver autostart after boot up? 启动后如何使广播接收器自动启动?
Broadcast receiver cannot show dialog. 广播接收器无法显示对话框。 Start an activity instead. 而是开始一个活动。
The problem is you are trying to show an AlertDialog
from a BroadcastReceiver
, which isn't allowed. 问题是您试图从BroadcastReceiver
显示AlertDialog
,这是不允许的。 You can't show an AlertDialog
from a BroadcastReceiver
. 您无法从BroadcastReceiver
显示AlertDialog
。 Only activities can display dialogs. 只有活动可以显示对话框。
You should do something else, have the BroadcastReceiver
start on boot as you do and start an activity to show the dialog. 您应该做其他事情,使BroadcastReceiver
启动时一样在启动时启动,并启动一个活动以显示对话框。
Add the following Activity to your application 将以下活动添加到您的应用程序
public class AlertActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new AlertDialog.Builder(this)
.setTitle("OK")
.setMessage("OK")
.setPositiveButton("ㅇㅇ", null)
.setCancelable(false)
.show();
}
}
Also don't forget to add the new activity to your manifest. 另外,不要忘记将新活动添加到清单中。
Then you just need to start the activity in your receiver 然后,您只需要在接收器中开始活动
@Override
public void onReceive(Context context, Intent intent)
{
context.startService(new Intent(context, MainService.class));
context.startActivity(new Intent(context, AlertActivity.class));
}
If this answer was helpful, please click the checkmark under the like button to indicate so. 如果此答案有帮助,请单击“喜欢”按钮下的复选标记以指示这样做。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.