我想編寫一個程序,當手機開機時它將自動運行。我想在特定時間每天顯示此計劃的通知。用戶將設置這些通知的時間。我正在用sqlite在數據庫中註冊這個。我在我爲它編寫的程序中定義了一個廣播接收器和服務。我正在使用掛起的意圖創建通知。所以當手機關機時,用戶正在生成的通知正在消失。我的課是這樣的:如何在xamarin中編寫啓動程序的權限
類BootCompleted:廣播接收器
類AlarmReceiver:廣播接收器
類的自動啓動:服務
在我AndroidManifest,我做了如下定義:
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<application android:label="myprogram">
<receiver
android:name=".ReminderService.BootCompleted"
android:enabled="true"
android:exported="false">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
</intent-filter>
</receiver>
<service android:name=".ReminderService.AutoStartUp">
</service>
</application>
因此,當我在手機上安裝此程序並嘗試使用時,發生了問題。 因此,當我以用戶身份創建通知,然後關閉和打開手機時,出現「程序停止工作」等錯誤。 這是爲什麼發生?
我BootCompleted類是擴展了BroadcastReceiver
[BroadcastReceiver]
[IntentFilter(new[] { Android.Content.Intent.ActionBootCompleted })]
public class BootCompleted : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
Log.Debug("BroadcastReceiverBoot", "BootCompleted");
if (intent.Action.Equals("android.intent.action.BOOT_COMPLETED"))
{
Intent serviceIntent = new Intent(context, typeof(AutoStartUp));
context.StartService(serviceIntent);
}
}
}
我AlarmReceiver類是擴展了BroadcastReceiver
[BroadcastReceiver]
[IntentFilter(new[] { Android.Content.Intent.ActionBootCompleted })]
public class AlarmReceiver : BroadcastReceiver
{
public override void OnReceive(Context context, Intent intent)
{
var message = intent.GetStringExtra("message");
var title = intent.GetStringExtra("title");
var notIntent = new Intent(context, typeof(MainActivity));
notIntent.SetFlags(ActivityFlags.NewTask | ActivityFlags.ClearTask);
var contentIntent = PendingIntent.GetActivity(context, 0, notIntent,
PendingIntentFlags.CancelCurrent);
var manager = NotificationManagerCompat.From(context);
var style = new NotificationCompat.BigTextStyle();
style.BigText(message);
var builder = new NotificationCompat.Builder(context)
.SetContentIntent(contentIntent)
.SetSmallIcon(Resource.Drawable.icon)
.SetContentTitle(title)
.SetContentText(message)
.SetStyle(style)
.SetAutoCancel(true);
var notification = builder.Build();
manager.Notify(DateTime.Now.Millisecond, notification);
}
}
我的自動啓動類是延長服務
class AutoStartUp : Service
{
public override IBinder OnBind(Intent intent)
{
return null;
}
public override void OnCreate()
{
try
{
Toast.MakeText(this, "boot1", ToastLength.Long).Show();
AndroidReminderService.BootRemind(DateTime.Now, "Boot Control", "Phone Opened!", DateTime.Now.Hour, DateTime.Now.Minute + 2, DateTime.Now.Second);
Toast.MakeText(this, "boot2", ToastLength.Long).Show();
}
catch (Exception e)
{
Toast.MakeText(this, e.Message, ToastLength.Long).Show();
throw;
}
}
}
很難說沒有完整的代碼。它可以在任何地方崩潰... –
作爲評論我分享類的內容 – oflu1071
這就是我所有的代碼。我也在編寫這個跨平臺的程序。這是我在複雜的android部分編寫的代碼。 – oflu1071