gpt4 book ai didi

java - 如何让通知在一天中的随机时间出现?

转载 作者:行者123 更新时间:2023-12-01 22:20:39 25 4
gpt4 key购买 nike

您好,我正在尝试让通知在一天中随机出现。现在它所做的只是在我按下 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);
}

}

最佳答案

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

您需要做的是发出警报,例如,它会按照您的意愿每小时激活您的应用程序代码。在此警报中,您将发出新通知。

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

关于java - 如何让通知在一天中的随机时间出现?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29878649/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com