gpt4 book ai didi

java - AlarmManager 不从 Android Wear 应用调用我的服务

转载 作者:行者123 更新时间:2023-11-30 01:12:37 26 4
gpt4 key购买 nike

我创建了一个 android wear 应用程序,我希望这个应用程序有时创建通知(在这段代码中,我想每 15 分钟调用一次我的服务以创建通知)

当我使用 AlramManager 注册我的服务时,我可以看到在操作系统中创建的任务 (adb shell dumpsys alarm > dump.txt) 但我看不到通知或日志来证明该服务运行。我用 startService 测试我的服务,通知和日志都正常工作,所以我不知道问题出在哪里。以下是我使用的代码:

MyAlarmService.java

public class MyAlarmService extends Service {
@Override
public void onCreate() {
super.onCreate();
Log.d("From serivce","Service run once");

// Create notification
Context context = this;
NotificationCompat.Builder builder = new NotificationCompat.Builder(context);
builder.setContentTitle(context.getString(R.string.NotificationTitle))
.setSmallIcon(R.mipmap.ic_launcher_hafez)
.setContentText("Some text");
Notification secondPage =
new NotificationCompat.Builder(context)
.setContentTitle(context.getString(R.string.NotificationTitle))
.setContentText("Some text")
.build();

NotificationCompat.WearableExtender extender = new NotificationCompat.WearableExtender();
extender.addPage(secondPage);
builder.extend(extender);

NotificationManagerCompat mgr = NotificationManagerCompat.from(context);
int NotificationId = new Random().nextInt(5200);
mgr.notify(NotificationId, builder.build());
}

@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}

AndroidManifest.xml

...
<service android:name=".MyAlarmService" />
...

在AlarmManager中注册服务的代码:

Context context = getActivity().getApplicationContext();
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
Intent intent = new Intent(context, MyAlarmService.class);
PendingIntent alarmIntent = PendingIntent.getBroadcast(context, 0, intent, 0);

AlarmManager alarmMgr = (AlarmManager)context.getSystemService(Context.ALARM_SERVICE);

alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
AlarmManager.INTERVAL_FIFTEEN_MINUTES, alarmIntent);

dump.txt的内容

Current Alarm Manager state:

...

Batch{91609e num=3 start=7228838 end=7233540 flgs=0x8}:

...

RTC_WAKEUP #0: Alarm{18a777f type 0 when 1467992333472 org.rashno.mypackagename}

tag=*walarm*:org.rashno.mypackagename/.MyAlarmService

type=0 whenElapsed=-6s582ms when=2016-07-08 20:08:53

window=+11m15s0ms repeatInterval=900000 count=0 flags=0x0

operation=PendingIntent{397c34c: PendingIntentRecord{de77f95 org.rashno.mypackagename broadcastIntent}}

...

Alarm Stats:
...
u0a57:org.rashno.mypackagename +9ms running, 1 wakeups:

+9ms 1 wakes 1 alarms, last -1m33s417ms:

*walarm*:org.rashno.mypackagename/.MyAlarmService
...
...

最佳答案

应使用 getService 创建服务的 PendingIntent

PendingIntent alarmIntent = PendingIntent.getService(context, 0, intent, 0);

关于java - AlarmManager 不从 Android Wear 应用调用我的服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38270766/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com