1

我的应用程序只有MainActivity一个ImageView.

BroadcastReceiver作品。当我连接 USB 时显示 Toast 消息。

现在,我需要启动我的应用程序最小化并只显示应用程序连接了 USB 电缆。

BroadcastReceiver broadcast_reciever = new BroadcastReceiver() {

    @Override
    public void onReceive(Context arg0, Intent intent) {
        String action = intent.getAction();
        if (action.equals("usb_detect")) {
            Toast.makeText(arg0,"Atenção!",Toast.LENGTH_SHORT).show();
            finish();
            startActivity(getIntent());
            //startActivity(new Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER));
        }
    }
};

清单在这里:https ://i.stack.imgur.com/sa3Pe.jpg

4

1 回答 1

0

要将您的应用程序置于前台,请将以下内容添加到onReceive()

Intent launchIntent = getPackageManager().
    getLaunchIntentForPackage("your.package.name");
startActivity(launchIntent);

这不会启动一个新的Activity,它只会将包含您的应用程序的现有任务以它移动到后台时所处的任何状态带到前台。

此外,finish()从您的BroadcastReceiver. finish()仅用于Activity.

于 2018-10-24T11:23:57.057 回答