簡體   English   中英

使用 Android 通知時服務啟動錯誤

[英]Service start error while using Android notifications

我試圖在每天中午 12 點向應用程序用戶顯示通知,並按照示例進行操作。 當時間到達目標時間時什么也沒有發生。 為什么會這樣?

這是我的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 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);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM