Android通知应用无法正常运行

时间:2015-05-27 17:37:45

标签: java android notifications alarmmanager android-notifications

我正在开发一个Android应用程序,其中一部分涉及提醒用户做某事的通知。此通知在指定时间每12小时重复一次。我正在使用AlarmManager来安排警报,并且我还包含了在设备启动时启动警报服务的代码。这是我的java类:

MainActivity.java

public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

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

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

private void alarmMethod() {

    Intent intent = new Intent(this, AlarmService.class);
    this.startService(intent);

    Toast.makeText(MainActivity.this, "Alarm Set", Toast.LENGTH_SHORT).show();

}

}  

AlarmService.java

public class AlarmService extends Service {

//used for register alarm manager
PendingIntent pendingIntent;
//used to store running alarm manager instance
AlarmManager alarmMgr;
//Callback function for alarm manager event
BroadcastReceiver mReceiver;

private static final String TAG = "MyService";

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

@Override
public void onCreate() {
    super.onCreate();

    //Register AlarmManager Broadcast receive.
    RegisterAlarmBroadcast();
}

@Override
public void onStart(Intent intent, int startid) {

    Calendar calendar = Calendar.getInstance();
    calendar.set(Calendar.SECOND, 0);
    calendar.set(Calendar.MINUTE, 30);
    calendar.set(Calendar.HOUR_OF_DAY, 6);

    alarmMgr.cancel(pendingIntent);
    alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP,
            calendar.getTimeInMillis(), 1000 * 60 * 60 * 12, pendingIntent);

}

private void showNotification() {

    Uri soundUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
    Notification notification = new NotificationCompat.Builder(this)
            .setContentTitle("app_name")
            .setContentText("something")
            .setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, MainActivity.class), PendingIntent.FLAG_UPDATE_CURRENT))
            .setSound(soundUri)
            .setSmallIcon(R.drawable.notification_icon)
            .setAutoCancel(true)
            .setOnlyAlertOnce(true)
            .build();

    NotificationManagerCompat.from(this).notify(0, notification);

}

private void RegisterAlarmBroadcast() {
    Log.i("RegisterAlarmBroadcast", "Register Intent.RegisterAlarmBroadcast");

    //This is the call back function(BroadcastReceiver) which will be called when your alarm time is reached.
    mReceiver = new BroadcastReceiver() {
        private static final String TAG = "Alarm Example Receiver";

        @Override
        public void onReceive(Context context, Intent intent) {
            Log.i(TAG, "BroadcastReceiver::OnReceive() >>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
            showNotification();
        }
    };

    //Register the alarm broadcast here
    registerReceiver(mReceiver, new IntentFilter("com.example.application.myNotification"));
    pendingIntent = PendingIntent.getBroadcast(this, 0, new Intent("com.example.application.myNotification"), 0);
    alarmMgr = (AlarmManager) (this.getSystemService(Context.ALARM_SERVICE));
}

public void onDestroy() {
    super.onDestroy();
    Log.d(TAG, "onDestroy");
}

}

autostart.java

public class autostart extends BroadcastReceiver {

@Override
public void onReceive(Context arg0, Intent arg1)
{
    Intent intent = new Intent(arg0,AlarmService.class);
    arg0.startService(intent);
    Log.i("Autostart", "started");
}
}

AndroidManifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.application" >

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

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

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <receiver android:name=".autostart">
        <intent-filter>
            <action android:name="android.intent.action.BOOT_COMPLETED" />
        </intent-filter>
    </receiver>
    <service
        android:name=".AlarmService"
        android:enabled="true" />
</application>

但是,由于工作不正常,我一定做错了。我的问题是:
1.当我退出应用程序时,无论什么时间,通知都会因某种原因而消失 2.当我重新启动时,无论何时,通知都会消失。

我不知道这些问题是否有任何关联,也许我有一段代码搞砸了一切。但不管怎样,我都非常感谢能得到的任何帮助。提前谢谢。

1 个答案:

答案 0 :(得分:1)

重复间隔应为24小时(1000 * 60 * 60 * 24),而不是12小时。

您将个人时间设置为上午6点。因此,您可以删除第calendar.setTimeInMillis(System.currentTimeMillis());

编辑:

我对您的代码进行了一些修改,最终使其正常运行。

你的问题是你在早上6点设置闹钟。但是您在上午6:00之后(比如上午9:00)设置此警报。也就是说,您正在为过去的时间设置闹钟。所以它会立即发生。

我为此做了一个工作。如果您需要设置闹钟的时间已过,请将闹钟设置为在第二天触发。

这是我修改后的代码。

MainActivity.java

public class MainActivity extends Activity {

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

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

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

    private void alarmMethod() {

        PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0,
                new Intent("com.example.application.myNotification"),
                PendingIntent.FLAG_UPDATE_CURRENT);
        AlarmManager alarmMgr = (AlarmManager) (this
                .getSystemService(Context.ALARM_SERVICE));

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 30);
        calendar.set(Calendar.HOUR_OF_DAY, 6);

        long mills = calendar.getTimeInMillis();
        if (mills <= System.currentTimeMillis()) {
            Calendar c1 = calendar;
            c1.add(Calendar.DAY_OF_MONTH, 1);
            mills = c1.getTimeInMillis();
        } else {
            mills = calendar.getTimeInMillis();
        }

        alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, mills,
                1000 * 60 * 60 * 24, pendingIntent);

        Toast.makeText(MainActivity.this, "Alarm Set", Toast.LENGTH_SHORT)
                .show();

    }

}

Autostart.java

public class Autostart extends BroadcastReceiver {

    @Override
    public void onReceive(Context arg0, Intent arg1)
    {
        PendingIntent pendingIntent = PendingIntent.getBroadcast(arg0, 0, new Intent("com.example.application.myNotification"), 0);
        AlarmManager alarmMgr = (AlarmManager) (arg0.getSystemService(Context.ALARM_SERVICE));

        Calendar calendar = Calendar.getInstance();
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MINUTE, 30);
        calendar.set(Calendar.HOUR_OF_DAY, 6);

        long mills = calendar.getTimeInMillis();
        if (mills <= System.currentTimeMillis()) {
            Calendar c1 = calendar;
            c1.add(Calendar.DAY_OF_MONTH, 1);
            mills = c1.getTimeInMillis();
        } else {
            mills = calendar.getTimeInMillis();
        }

        alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, mills, 1000 * 60 * 60 * 24, pendingIntent);

        Log.i("Autostart", "started");
    }

}

Alarmer.java

public class Alarmer extends BroadcastReceiver {

    @Override
    public void onReceive(Context context, Intent intent) {
        showNotification(context);
    }

    private void showNotification(Context context) {

        Random r = new Random();
        int r0 = r.nextInt();

        Uri soundUri = RingtoneManager
                .getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);
        Notification notification = new NotificationCompat.Builder(context)
                .setContentTitle("app_name")
                .setContentText("something" + r0)
                .setContentIntent(
                        PendingIntent.getActivity(context, 0, new Intent(context,
                                MainActivity.class),
                                PendingIntent.FLAG_UPDATE_CURRENT))
                .setSound(soundUri).setSmallIcon(R.drawable.ic_launcher)
                .setAutoCancel(true).setOnlyAlertOnce(true).build();

        // NotificationManagerCompat.from(this).notify(0, notification);
        NotificationManager nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);


        nm.notify(r0, notification);

    }

}

AndroiManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.alarmtest"
    android:versionCode="1"
    android:versionName="1.0" >

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

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

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

        <receiver android:name=".autostart" >
            <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
            </intent-filter>
        </receiver>

        <receiver android:name=".Alarmer" android:enabled="true">
            <intent-filter>
                <action android:name="com.example.application.myNotification" />
            </intent-filter>
        </receiver>

        <service
            android:name=".AlarmService"
            android:enabled="true" />
    </application>

</manifest>

将其与您的代码进行比较并进行更改。