Android的通知应用程序无法正常工作 [英] Android notification app not working properly

查看:243
本文介绍了Android的通知应用程序无法正常工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我开发一个Android应用程序,它的一部分涉及到一个通知,提醒用户做一些事情。此通知在指定的时间,并且重复每12小时。我使用 AlarmManager 调度报警,我还包含了code开始我报警服务设备启动时。这里是我的Java类:

I'm developing an android app, and part of it involves a notification that reminds the user to do something. This notification at a specified time and repeats every 12 hours. I'm using AlarmManager to schedule the alarm and I've also included the code to start my Alarm Service when the device boots. Here are my java classes:

MainActivity.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

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

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中

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.当我重新启动,通知熄灭,无论时间。

However I must have done something wrong as it is not working properly. My problems are:
1. When I exit the app, the notification for some reason goes off, whatever the time is.
2. When I reboot, the notification goes off, whatever the time is.

我不知道这些问题是任何关系,也许我有一张code多数民众赞成搞乱一切。但无论哪种方式,我真的很AP preciate任何形式的帮助,我可以得到的。先谢谢了。

I don't know if these problems are in any way related, maybe I have a piece of code that's messing everything up. But either way I would really appreciate any sort of help I can get. Thanks in advance.

推荐答案

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

The repeating interval should be 24 hours (1000 * 60 * 60 * 24), not 12 hours.

您的时间分别设定为6点。所以,你可以删除行 calendar.setTimeInMillis(System.currentTimeMillis的());

You are individually setting the time to 6 AM. So you can remove the line calendar.setTimeInMillis(System.currentTimeMillis());

编辑:

我已经做了一些修改,您的code和终于得到了它的工作。

I have made some of modifications to your code and finally got it working.

您的问题是,您的上午6:00设置闹铃。但你以后上午6:00(比如9:00 AM)设置报警的时间。也就是说,你要设置的过去时间报警。因此,它会立即熄灭。

You problem was that you set an alarm for 6:00 AM. But you are setting this alarm at a time after 6:00 AM (say 9:00 AM). That is, you are setting an alarm for a past time. So it will go off immediately.

我围绕这个做了工作。如果您需要设置闹铃的时间已经过去,将闹钟设置为第二天触发。

I made a work around for this. If the time you need to set alarm is past, set the alarm to trigger on the next day.

这是我修改code。

MainActivity.java

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

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

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

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>

您code比较,并做出改变。

Compare it with your code and make changes.

这篇关于Android的通知应用程序无法正常工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆