嗨我想在5分钟后在后台应用时将通知发送给用户执行应用程序。 所以,我使用onWindowFocusChanged检查我的应用程序是否为背景。请帮帮我,我该怎么办。这是我的代码。请用完整的代码回答我。 我想通过弹出菜单通知他们。
MainActivity.java
package com.myapp;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
.............//import is too long
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;
import com.myapp.R;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button btnA = (Button)findViewById(R.id.btngetA);
btnA.setOnClickListener(new Button.OnClickListener(){
@Override
public void onClick(View v){
//TODO Auto-generated method stub
Intent intentA = new Intent(getApplicationContext(), gotoAActivity.class);
startActivity(intentA);
}
});
@Override
public void onWindowFocusChanged(boolean hasFocus) {
if (!hasFocus) {
new CountDownTimer(1000, 1) {
public void onTick(long millisUntilFinished) {
}
public void onFinish() {
//timer finished
}
}.start();
}
super.onWindowFocusChanged(hasFocus);
}
这是通知。但我不知道这些代码应该添加到哪里..
public static void createService(Context context, CharSequence tickerMessage, CharSequence title,
CharSequence message, int icon, int id, Intent intent, long[] pattern, Boolean autoCancel) {
PendingIntent p = PendingIntent.getService(context, 0, intent, 0);
Notification n;
title="notice";
message="execute your app!!";
int apiLevel = Build.VERSION.SDK_INT;
if (apiLevel >= 11) {
NotificationCompat.Builder builder = new NotificationCompat.Builder(context)
.setContentTitle(title)
.setTicker(tickerMessage)
.setContentText(message)
.setSmallIcon(icon)
.setContentIntent(p)
.setPriority(NotificationCompat.PRIORITY_DEFAULT);
if (pattern.length > 0) {
builder.setVibrate(pattern);
}
if (autoCancel != null) {
builder.setAutoCancel(autoCancel);
}
if (apiLevel >= 17) {
// Android 4.2+
n = builder.build();
}
else {
// Android 3.x
n = builder.getNotification();
}
}
else {
// Android 2.2+
n = new Notification(icon, tickerMessage, System.currentTimeMillis());
// Data
n.setLatestEventInfo(context, title, message, p);
}
NotificationManager nm = (NotificationManager)
context.getSystemService(Activity.NOTIFICATION_SERVICE);
nm.notify(id, n);
}
答案 0 :(得分:0)
您应该使用onFinish()
方法发送通知,但说实话,此代码根本不起作用。如果你的活动在后台,可以随时被操作系统杀死。您可以做的是在活动的onStop()
回调中设置5分钟的闹钟,并在onStart()
回调中将其删除。这样,如果5分钟后没有启动活动,您可以根据计时器到期时的操作进行一些工作。