java - Android服务重启后不工作,给出ANR错误

标签 java android

浏览了有关如何 start a service automatically after the device boots 的文档并尝试了他们所说的所有方法,但在重新启动设备后无法让我的服务正常工作,尽管它在第一次实例中工作得很好。
下面是我的主要 Activity (MainActivity.java),它在单击按钮后启动服务,并使用 AlarmManager 每 10 秒触发一次服务。

public void onClickSubmitDate(View view) {
    Intent service = new Intent(this, MyService.class);
    PendingIntent pendingIntent = PendingIntent.getService(this, 0, service, 0);

    AlarmManager alarmManager = (AlarmManager) this.getSystemService(Context.ALARM_SERVICE);
    alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP, 0, 10 * 1000, pendingIntent);

    //Enable receiver when device boots
    ComponentName receiver = new ComponentName(this, BootReceiver.class);
    PackageManager pm = this.getPackageManager();

    pm.setComponentEnabledSetting(receiver,
    PackageManager.COMPONENT_ENABLED_STATE_ENABLED,
    PackageManager.DONT_KILL_APP);
}

下面是我的接收器类(BootReceiver.java)

public class BootReceiver extends BroadcastReceiver {
@Override
public void onReceive(Context context, Intent intent) {
if(intent.getAction().equals("android.intent.action.BOOT_COMPLETED")) {
Intent service = new Intent(context, MyService.class);
PendingIntent pendingIntent = PendingIntent.getService(null, 0, service, 0);

AlarmManager alarmManager = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
         alarmManager.setInexactRepeating(AlarmManager.ELAPSED_REALTIME_WAKEUP,
                10 * 1000, 10 * 1000,
                pendingIntent);
    }
}

}

我的服务包含一个线程,用于检查多个场景并为每个场景构建通知。下面是一个示例:

public int onStartCommand(Intent intent, int flags, int startId) {
        notification = new NotificationCompat.Builder(this);
        notification.setAutoCancel(true);

        Runnable r = new Runnable() {
            @Override
            public void run() {
                try {
                    boolean diff = true;
                    if (diff) {
                        // Build the notification
                        notification.setSmallIcon(R.drawable.icon);
                        notification.setTicker(getString(R.string.notification_ticker));
                        notification.setWhen(System.currentTimeMillis());
                        notification.setContentTitle(getString(R.string.notification_title));
                        notification.setContentText(getString(R.string.notification_1_text));
                        notification.setSound(alarmSound);

                        Intent i = new Intent(context, MainActivity.class);
                        PendingIntent pendingIntent = PendingIntent.getActivity(context, 0, i, PendingIntent.FLAG_UPDATE_CURRENT);
                        notification.setContentIntent(pendingIntent);

                        // Builds a notification and issues it
                        NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
                        Random r = new Random();
                        int rand = r.nextInt(1000);
                        nm.notify(rand, notification.build());
                    }
catch (Exception e) {
                    e.printStackTrace(); 
                }
            }
        };

        Thread stephThread = new Thread(r);
        stephThread.start();

        return START_STICKY;

    }

最后下面是我的 AndroidManifest.xml 代码

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.motherslove.stephnoutsa.myapplication18calendartest"
    android:installLocation="internalOnly">

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

    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait"
            android:theme="@style/AppTheme.NoActionBar">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        <activity
            android:name=".MyDate"
            android:label="@string/title_activity_my_date"
            android:theme="@style/AppTheme.NoActionBar" />

        <service
            android:name=".MyService"
            android:enabled="true"
            android:exported="true" />

        <receiver
            android:name=".BootReceiver"
            android:enabled="false">
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED"/>
            </intent-filter>
        </receiver>
    </application>

</manifest>

请有人告诉我我做错了什么吗?

最佳答案

感谢@MikeM的帮助,我可以解决这个问题。

而不是

PendingIntent pendingIntent = PendingIntent.getService(null, 0, service, 0);

我必须在接收器中将上下文作为第一个参数传递,如下所示

PendingIntent pendingIntent = PendingIntent.getService(context, 0, service, 0);

关于java - Android服务重启后不工作,给出ANR错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35190272/

相关文章:

java - 防止并发插入中的句点交叉

java - 将接口(interface)嵌套在具体类中的可行设计替代方案是什么?

android - 如何更改默认 EditText 的样式

java - 从 jsonArray java android 获取字符串

android - 在 SDK 管理器中找不到 android sdk 2.3.4

java - 我怎样才能找到父目录

java - notifyDataSetChanged() 与 invalidateData()

java - 在 Netbeans Maven 项目中添加 JDBC

android - 工具栏中的自定义布局未显示

Android Canvas - setWillNotDraw(false) 不起作用