如何在一天中随机出现通知?

时间:2015-04-26 14:07:41

标签: java android random notifications

您好我试图在一天中随机出现通知。现在它所做的就是当我按下a按钮时显示通知。我想按钮开始让它们每小时左右出现一次。这是我的MainActivity类。

public class MainActivity extends Activity {
Button button;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    button = (Button) findViewById(R.id.button1);
    button.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            NotificationCompat.Builder notification = new NotificationCompat.Builder(MainActivity.this);

            notification.setSmallIcon(R.mipmap.ic_launcher);
            notification.setTicker("Hey!!!");
            notification.setWhen(System.currentTimeMillis());
            notification.setContentTitle("You're Awesome");

            Uri sound = RingtoneManager.getDefaultUri(Notification.DEFAULT_SOUND);

            notification.setContentText("keep being awesome!!!:)");
            notification.setSound(sound);

            Bitmap picture = BitmapFactory.decodeResource(getResources(), R.mipmap.ic_launcher);

            notification.setLargeIcon(picture);

            PendingIntent mypendingintent;
            Intent myintent = new Intent();
            Context mycontext = getApplicationContext();
            myintent.setClass(mycontext, Activity2.class);
            myintent.putExtra("ID", 1);
            mypendingintent = PendingIntent.getActivity(mycontext, 0, myintent, 0);

            notification.setContentIntent(mypendingintent);
            Notification n = notification.build();

            NotificationManager nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            nm.notify(1,n);




        }
    });
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu_main, menu);
    return true;
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    //noinspection SimplifiableIfStatement
    if (id == R.id.action_settings) {
        return true;
    }

    return super.onOptionsItemSelected(item);
}

}

1 个答案:

答案 0 :(得分:3)

请看这里:https://developer.android.com/training/scheduling/alarms.html

您需要做的是发出警报,例如,您可以按照自己的意愿每小时激活一次应用代码。在此警报中,您将发出新通知。

如果您需要代码示例,请查看此处:Alarm Manager Example