如何在Android上自动从电源按钮启动应用页面

问题描述 投票:0回答:1

我在VS 2017中使用Xamarin Android为我的侄女制作了一个小应用程序。我希望它在应用程序上打开一个页面,每次打开手机时都会询问她一个简单的乘法问题。我希望它作为前台服务运行,所以当应用程序最小化时它仍然会这样做。我有一个广播接收器,当应用程序有焦点时检测到按钮事件,我已将其移动到服务运行。

目前我按下切换按钮,然后5-10秒后它会抛出错误。无法在VS中看到错误,因为它是外部的。我假设Genymotion模拟器捕获了那个呢?

有任何想法吗?

更新:如果将来对其他任何人都有用,我想我会来更新一下。在Oreo更新后,NotificationCompat.Builder现在需要提供通道ID。我在代码中反映了它,现在它正确地启动了服务。

我仍然需要从服务中获得广播接收器,但我到了那里!

更新2:完成工作!

[Activity(Label = "@string/app_name", Theme = "@style/AppTheme", MainLauncher = true)]
public class MainActivity : AppCompatActivity
{
    Intent startServiceIntent;
    Intent stopServiceIntent;

    protected override void OnCreate(Bundle savedInstanceState)
    {
        base.OnCreate(savedInstanceState);
        SetContentView(Resource.Layout.activity_main);

        // Difficulty Radio Buttons
        RadioButton radioEasy = FindViewById<RadioButton>(Resource.Id.radioEasy);
        radioEasy.Click += RadioButton_Click;
        RadioButton radioMedium = FindViewById<RadioButton>(Resource.Id.radioMedium);
        radioMedium.Click += RadioButton_Click;
        RadioButton radioHard = FindViewById<RadioButton>(Resource.Id.radioHard);
        radioHard.Click += RadioButton_Click;

        // Set/Remove Lock
        Button ToggleLock = FindViewById<Button>(Resource.Id.ToggleLock);
        ToggleLock.Click += ToggleLock_Click;

        startServiceIntent = new Intent(this, typeof(LockService));
        stopServiceIntent = new Intent(this, typeof(LockService));
    }

    private void RadioButton_Click(object sender, EventArgs e)
    {
        var radiobtn = sender as RadioButton;
        Toast.MakeText(this, radiobtn.Text, ToastLength.Long).Show();
    }
    private void ToggleLock_Click(object sender, EventArgs e)
    {
        var togglebtn = sender as ToggleButton;
        if (togglebtn.Checked)
        {
            if (Build.VERSION.SdkInt >= BuildVersionCodes.O)
                StartForegroundService(startServiceIntent);
            else
                StartService(startServiceIntent);

            Toast.MakeText(this, "On", ToastLength.Long).Show();
        }
        else
        {
            Toast.MakeText(this, "Off", ToastLength.Long).Show();
        }
    }
}


/// <summary>
/// ////////////////////////////////////////////////////////////////////////////
/// </summary>

[Service]
public class LockService : Service
{
    private PowerBroadcastReceiver receiver;

    public override void OnCreate()
    {
    }

    public override StartCommandResult OnStartCommand(Intent intent, StartCommandFlags flags, int startId)
    {
        NotificationManager mngr = (NotificationManager)GetSystemService(NotificationService);
        NotificationChannel chnl = new NotificationChannel("Channel", "Name", NotificationImportance.Default);
        mngr.CreateNotificationChannel(chnl);

        NotificationCompat.Builder foregroundNotification = new NotificationCompat.Builder(this);
        foregroundNotification.SetOngoing(true);
        foregroundNotification.SetContentTitle("My Foreground Notification")
                .SetChannelId("Channel")
                .SetContentText("This is the first foreground notification Peace");

        StartForeground(101, foregroundNotification.Notification);

        // Broadcast Receiver
        receiver = new PowerBroadcastReceiver();
        RegisterReceiver(receiver, new IntentFilter(Intent.ActionScreenOn));

        return StartCommandResult.Sticky;
    }

    public override IBinder OnBind(Intent intent)
    {
        // Return null because this is a pure started service. A hybrid service would return a binder that would
        // allow access to the GetFormattedStamp() method.
        return null;
    }

}

/// <summary>
/// ////////////////////////////////////////////////////////////////////////////////
/// </summary>

[BroadcastReceiver]
[IntentFilter(new[] { Intent.ActionScreenOn, Intent.ActionScreenOff })]
public class PowerBroadcastReceiver : BroadcastReceiver
{
    public PowerBroadcastReceiver()
    {
    }

    public override void OnReceive(Context context, Intent intent)
    {
        if (intent.Action.Equals(Intent.ActionScreenOn))
        {
            // TODO: Launch Question Page

            Toast.MakeText(context, "On", ToastLength.Long).Show();
        }
        else if (intent.Action.Equals(Intent.ActionScreenOff))
            Toast.MakeText(context, "Off", ToastLength.Long).Show();
    }
}

谢谢。

c# android xamarin broadcastreceiver foreground-service
1个回答
2
投票

你可以创建一个监听器类来监听android锁屏和解锁事件,使用广播来接收屏幕状态。由于这是系统广播,我认为没有必要使用服务。

你可以参考这个:https://stackoverflow.com/a/55014763/10768653

© www.soinside.com 2019 - 2024. All rights reserved.