繁体   English   中英

BroadcastReceiver仅在打开应用程序时有效

[英]BroadcastReceiver works only when application is opened

我创建了一个名为Book Shelf的应用,因为我经常借书,因此我会使用BroadcastReceiver在屏幕打开时发送通知。 但是,仅当打开应用程序时, BroadcastReceiver才能工作(关闭时通知不会显示)。

MyReceiver.java

public class MyReceiver extends BroadcastReceiver
{
    public static final int ID_NOTFICATION_REMINDER = 0;
    SharedPreferences sp = MainActivity.sp;
    SharedPreferences.Editor edit = MainActivity.edit;
    private NotificationManager mNotificationManager;

    @SuppressWarnings("deprecation")
    public void onReceive(Context context, Intent intent)
    {
        if (intent.getAction().matches("android.intent.action.SCREEN_ON"))
        {
            for (int i = 0; i < sp.getInt("count", 0); i++)
            {
                mNotificationManager =         (NotificationManager)context.getSystemService(Context.NOTIFICATION_SERVICE);
                String name = sp.getString("name" + i, "NULL");
                String owners = sp.getString("owner" + i, "NULL");
                String holder = sp.getString("where" + i, "NULL");
                String date = sp.getString("date" + i, "NULL");
                SimpleDateFormat dfDate = new SimpleDateFormat(
                        "dd-MM-yyyy");
                Calendar c = Calendar.getInstance();
                String currentDate = dfDate.format(c.getTime());
                if ((!owners.equals(holder)) && (!name.isEmpty()) &&   (Utils.monthDiff(date, currentDate) >= 30))
                {
                    int icon = R.drawable.book_shelf_icon;
                    CharSequence tickerText = "A message from Book    Shelf";
                    long when = System.currentTimeMillis();
                    final Notification mNotification = new Notification(icon, tickerText, when);
                    String contentTitle = "The book "+name+" hasn't changed it's state for over a month!";
                    String contentText = "Tap to open Book Shelf";
                    Intent mIntent = new Intent(context, MainActivity.class);
                    PendingIntent mPendingIntent = PendingIntent.getActivity(context, 0, mIntent, 0);
                    mNotification.setLatestEventInfo(context, contentTitle, contentText, mPendingIntent);
                  mNotificationManager.notify(ID_NOTFICATION_REMINDER, mNotification);
                }
            }
        }    
    }
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.asaf.applications.bookshelf"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="8" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/book_shelf_icon"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        <activity
            android:name="com.asaf.applications.bookshelf.MainActivity"
            android:label="@string/app_name"
            android:screenOrientation="portrait" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <receiver
            android:name="com.asaf.applications.bookshelf.MyReceiver"
            android:enabled="true"
            android:exported="true">
            <intent-filter>
                <action android:name="android.intent.action.SCREEN_ON" />
            </intent-filter>
        </receiver>
    </application>

 </manifest>

您正在从MainActivity获得对SharedPreferences的引用

SharedPreferences sp = MainActivity.sp;

但是,当活动未运行时,您将获得一个NPE(为sp = null)

广播接收者已经可以访问上下文,因此可以使用它来准确引用对SharedPreferences的引用

@SuppressWarnings("deprecation")
public void onReceive(Context context, Intent intent)
    SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(context); 
    /*
    * Your code
    */
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM