我创建了一个应用程序,我编写检测wifi网络的服务并将数据发送到服务器,为此我编写了Alarm Manager和广播接收器,然后通过报警管理器和广播接收器呼叫服务onCreate方法。我的代码如下:
BootCompletedIntentReceiver类调用广播接收器30秒。
public class BootCompletedIntentReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
AlarmManager service = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);
Intent background = new Intent(context, AlarmReceiver.class);
PendingIntent pending = PendingIntent.getBroadcast(context, 0, background,
PendingIntent.FLAG_CANCEL_CURRENT);
Calendar cal = Calendar.getInstance();
// start 30 seconds after boot completed
cal.add(Calendar.SECOND, 30);
// fetch every 30 seconds
// InexactRepeating allows Android to optimize the energy consumption
service.setInexactRepeating(AlarmManager.RTC_WAKEUP,
cal.getTimeInMillis(),2000, pending);
}
}
AlarmReceiver Class
public class AlarmReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
Intent background = new Intent(context, MyService.class);
context.startService(background);
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager)context.getSystemService(ns);
int icon = R.drawable.ic_launcher;
CharSequence tickerText = "Service Started";
long when = System.currentTimeMillis();
Notification notification = new Notification(icon,tickerText, when);
notification.flags |= Notification.FLAG_AUTO_CANCEL;
CharSequence contentTitle = "Service Start!";
CharSequence contentText = "";
Intent notificationIntent = new Intent(context,AlarmReceiver.class);
PendingIntent contentIntent = PendingIntent
.getActivity(context, 0, notificationIntent, 0);
notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent);
mNotificationManager.notify(1, notification);
// Log.d("test", "Saving Data to File from Service.");
}
}
从AlarReceiver服务获取调用和第一个onCreate方法然后OnstartCommand ..我写线程来检测wifi ..这个代码是为某些手机运行但有些电话服务永远不会启动。为什么会这样?
我的清单文件代码如下:
<service android:name="com.edbeans.attendance.MyService"
android:enabled="true"
android:process=":my_process"
android:exported="true"
android:icon="@drawable/ic_launcher"></service>
<receiver android:name="com.edbeans.attendance.AlarmReceiver">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
<receiver android:name="com.edbeans.attendance.BootCompletedIntentReceiver" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
为什么会发生这种情况,服务从某个电话拨打电话并成功运行,但某些电话服务从未启动..
答案 0 :(得分:1)
系统可能会在收到警报后立即返回低功耗状态。为了确保您的alter table `funcionarios` add constraint funcionarios_supervisor_id_foreign
foreign key (`supervisor_id`) references `funcionarios` (`id`)
运行,您需要使用唤醒锁在Service
和BroadcastReceiver
之间进行协调。请查看Service
作为选项来帮助解决此问题。