【问题标题】:Service start error while using Android notifications使用 Android 通知时服务启动错误
【发布时间】:2021-06-25 09:09:21
【问题描述】:

我试图在每天中午 12 点向应用程序用户显示通知,并遵循this 的示例。当时间到达目标时间时,什么也不会发生。为什么会这样?

这是我的NotifyService 课程:

public class NotifyService extends Service {
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate(){
        Uri sound = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        NotificationManager mNM = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        Intent intent1 = new Intent(this.getApplicationContext(), MainActivity.class);
    PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent1, 0);

    Notification mNotify = new Notification.Builder(this)
            .setContentTitle("Log Tasks!")
            .setContentText("Complete your tasks for today")
            .setSmallIcon(R.drawable.ic_launcher)
            .setContentIntent(pIntent)
            .setSound(sound)
            .build();

    mNM.notify(1, mNotify);
}
}

这就是我在MainActivity 课程中的称呼:

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView english_button;
    private TextView hindi_button;
    private PendingIntent pendingIntent;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        english_button = findViewById(R.id.english_button);
        hindi_button = findViewById(R.id.hindi_button);

        english_button.setOnClickListener(this);
        hindi_button.setOnClickListener(this);

        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
        SharedPreferences.Editor editor = preferences.edit();
        int i = preferences.getInt("numberoflaunches", 1);

        if (i < 1){
            alarmMethod();
            i++;
            editor.putInt("numberoflaunches", i);
            editor.commit();
        }
    }

    @Override
    public void onClick(View v) {
        Intent i = null;
        switch (v.getId()){

            case R.id.english_button:
                i = new Intent(MainActivity.this, Instructions.class);
                startActivity(i);
                break;

            case R.id.hindi_button:
                i = new Intent(MainActivity.this, Instructions.class);
                startActivity(i);
                break;

        }
    }

    private void alarmMethod(){
        Intent myIntent = new Intent(this , NotifyService.class);
        AlarmManager alarmManager = (AlarmManager)getSystemService(ALARM_SERVICE);
        pendingIntent = PendingIntent.getService(this, 0, myIntent, 0);

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.HOUR, 0);
        calendar.set(Calendar.AM_PM, Calendar.PM);
        calendar.add(Calendar.DAY_OF_MONTH, 1);

        alarmManager.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(), 1000 * 60 * 60 * 24, pendingIntent);



        Toast.makeText(MainActivity.this, "Start Alarm", Toast.LENGTH_LONG).show();
    }

}

我试图通过记录并检查是否正在调用 alarmMethod() 来缩小问题范围,但我看到它正在被调用,所以我无法确定是什么导致了这里的问题。

这是日志:

2021-06-25 12:00:00.010 867-867/com.android.systemui D/KeyguardClockSwitch: Updating clock: 1200
2021-06-25 12:00:02.438 237-241/? E/android.system.suspend@1.0-service: Error opening kernel wakelock stats for: wakeup34: Permission denied
2021-06-25 12:00:02.435 237-237/? W/Binder:237_2: type=1400 audit(0.0:244): avc: denied { read } for name="wakeup34" dev="sysfs" ino=19014 scontext=u:r:system_suspend:s0 tcontext=u:object_r:sysfs:s0 tclass=dir permissive=0
2021-06-25 12:00:02.443 237-241/? E/android.system.suspend@1.0-service: Error opening kernel wakelock stats for: wakeup35: Permission denied
2021-06-25 12:00:02.439 237-237/? W/Binder:237_2: type=1400 audit(0.0:245): avc: denied { read } for name="wakeup35" dev="sysfs" ino=19077 scontext=u:r:system_suspend:s0 tcontext=u:object_r:sysfs:s0 tclass=dir permissive=0
2021-06-25 12:00:54.137 505-505/? E/netmgr: qemu_pipe_open_ns:62: Could not connect to the 'pipe:qemud:network' service: Invalid argument
2021-06-25 12:00:54.138 505-505/? E/netmgr: Failed to open QEMU pipe 'qemud:network': Invalid argument
2021-06-25 12:00:54.806 516-516/? E/wifi_forwarder: qemu_pipe_open_ns:62: Could not connect to the 'pipe:qemud:wififorward' service: Invalid argument
2021-06-25 12:00:54.807 516-516/? E/wifi_forwarder: RemoteConnection failed to initialize: RemoteConnection failed to open pipe
2021-06-25 12:01:00.008 867-867/com.android.systemui D/KeyguardClockSwitch: Updating clock: 1201
2021-06-25 12:01:00.332 576-2933/system_process W/ActivityManager: Background start not allowed: service Intent { cmp=com.google.android.apps.messaging/.shared.datamodel.action.execution.ActionExecutorImpl$EmptyService } to com.google.android.apps.messaging/.shared.datamodel.action.execution.ActionExecutorImpl$EmptyService from pid=10958 uid=10115 pkg=com.google.android.apps.messaging startFg?=false
2021-06-25 12:01:00.335 10958-10958/com.google.android.apps.messaging W/BugleDataModel: ActionExecutorImpl: Action started execution, but we can't guarantee it will complete, the app may be killed. Action: class com.google.android.apps.messaging.shared.datamodel.action.CountryCodeDetectorAction-CountryCodeDetectorAction:3271432003
    java.lang.IllegalStateException: Not allowed to start service Intent { cmp=com.google.android.apps.messaging/.shared.datamodel.action.execution.ActionExecutorImpl$EmptyService }: app is in background uid UidRecord{439a600 u0a115 CEM  idle procs:1 seq(0,0,0)}
        at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1715)
        at android.app.ContextImpl.startService(ContextImpl.java:1670)
        at android.content.ContextWrapper.startService(ContextWrapper.java:720)
        at com.google.android.apps.messaging.shared.datamodel.action.execution.ActionExecutorImpl.a(PG:98)
        at com.google.android.apps.messaging.shared.datamodel.action.execution.ActionExecutorImpl.a(PG:93)
        at gjl.c(PG:119)
        at gji.run(Unknown Source:1)
        at afou.run(PG:3)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)
2021-06-25 12:01:00.344 10958-10958/com.google.android.apps.messaging W/BugleDataModel: ActionExecutorImpl: Action started execution, but we can't guarantee it will complete, the app may be killed. Action: class com.google.android.apps.messaging.shared.datamodel.action.SelfParticipantsRefreshAction-SelfParticipantsRefreshAction:3271432004
    java.lang.IllegalStateException: Not allowed to start service Intent { cmp=com.google.android.apps.messaging/.shared.datamodel.action.execution.ActionExecutorImpl$EmptyService }: app is in background uid UidRecord{439a600 u0a115 CEM  idle procs:1 seq(0,0,0)}
        at android.app.ContextImpl.startServiceCommon(ContextImpl.java:1715)
        at android.app.ContextImpl.startService(ContextImpl.java:1670)
        at android.content.ContextWrapper.startService(ContextWrapper.java:720)
        at com.google.android.apps.messaging.shared.datamodel.action.execution.ActionExecutorImpl.a(PG:98)
        at com.google.android.apps.messaging.shared.datamodel.action.execution.ActionExecutorImpl.a(PG:93)
        at gjl.c(PG:119)
        at gji.run(Unknown Source:1)
        at afou.run(PG:3)
        at android.os.Handler.handleCallback(Handler.java:938)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:223)
        at android.app.ActivityThread.main(ActivityThread.java:7656)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:592)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:947)

另外,我在清单文件中添加了相关的用户权限行,如下所示,但我仍然没有收到任何通知:

<uses-permission android:name="android.permission.WAKE_LOCK"/>

【问题讨论】:

    标签: android notifications android-notifications


    【解决方案1】:

    可能你没有注册通知通道,因为从Android 8.0(SDK 26)开始,你应该注册一个通知通道,否则发送通知将永远无法工作。

    看这里:https://developer.android.com/training/notify-user/channels

    Caution: If you target Android 8.0 (API level 26) and post a notification without specifying a notification channel, the notification does not appear and the system logs an error.

    创建通知通道很简单,只需在调用NotificationManager.notify() 之前创建即可。您可以参考该网页下方的示例 (https://developer.android.com/training/notify-user/channels)。

    这是给 Kotlin 的

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        // Create the NotificationChannel
        val name = getString(R.string.channel_name)
        val descriptionText = getString(R.string.channel_description)
        val importance = NotificationManager.IMPORTANCE_DEFAULT
        val mChannel = NotificationChannel(CHANNEL_ID, name, importance)
        mChannel.description = descriptionText
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        val notificationManager = getSystemService(NOTIFICATION_SERVICE) as NotificationManager
        notificationManager.createNotificationChannel(mChannel)
    }
    

    这是用于 Java 的

    // Create the NotificationChannel, but only on API 26+ because
    // the NotificationChannel class is new and not in the support library
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        CharSequence name = getString(R.string.channel_name);
        String description = getString(R.string.channel_description);
        int importance = NotificationManager.IMPORTANCE_DEFAULT;
        NotificationChannel channel = new NotificationChannel(CHANNEL_ID, name, importance);
        channel.setDescription(description);
        // Register the channel with the system; you can't change the importance
        // or other notification behaviors after this
        NotificationManager notificationManager = getSystemService(NotificationManager.class);
        notificationManager.createNotificationChannel(channel);
    }
    

    【讨论】:

    • 在变量channel_namechannel_descriptionCHANNEL_ID中添加什么?
    • 您可以查看这些变量的使用说明。直接跳转看NotificationChannel的构造函数的注释即可。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-07-25
    • 1970-01-01
    • 1970-01-01
    • 2013-05-05
    • 1970-01-01
    • 1970-01-01
    • 2011-06-02
    相关资源
    最近更新 更多