我正在开发一个Android应用程序,其中在特定时间间隔后再次触发操作,当收到 Intent.FLAG_ACTIVITY_NEW_TASK 广播消息时再次触发。 我在 UpdateService.java :
中有以下代码package com.missnoob.screentimeout;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
public class UpdateService extends Service {
@Override
public void onCreate() {
super.onCreate();
// REGISTER RECEIVER THAT HANDLES SCREEN ON AND SCREEN OFF LOGIC
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
BroadcastReceiver mReceiver = new ScreenReceiver();
registerReceiver(mReceiver, filter);
}
@Override
public void onStart(Intent intent, int startId) {
boolean screenOn = intent.getBooleanExtra("screen_state", false);
if (!screenOn) {
Log.v("ScreenTimeOut","Broadcast Received");
Toast.makeText(getApplicationContext(), "Broadcast Received", Toast.LENGTH_LONG).show();
//This part is not working
Intent i = new Intent(this, Notification.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
//This part is not working
}
else
{
// YOUR CODE
}
}
@Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
Notification.java 中的以下代码:
package com.missnoob.screentimeout;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
import com.shadow.screentimeout.R;
public class Notification extends Activity {
/** Called when the activity is first created. */
Timer timer;
Toast toast;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
timer = new Timer();
toast = Toast.makeText(getApplicationContext(), "15 seconds after",Toast.LENGTH_SHORT);
timer.scheduleAtFixedRate(new TimerTask()
{
@Override
public void run() {
toast.show();
Log.v("ScreenTimeOut","Toast showed");
}
}, 0, 5000);
}
}
在 UpdateService.java
中Intent i = new Intent(this, Notification.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
永远不会被触发。
答案 0 :(得分:1)
您缺少startActivity(i)
Intent i = new Intent(this, Notification.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
你也不能
toast.show();
在计时器中,因为它在不同的线程上运行,你只能在ui线程上更新ui。
而是使用Handler
。你可以找到一个例子@
答案 1 :(得分:1)
您尚未拨打startActivity(i)
。
请参阅Start Another Activity(android开发者网站)。
答案 2 :(得分:1)
你没有打电话给startActivity(i)
,这就是为什么你的活动从未被召唤过,你所要做的就是这样:
Intent i = new Intent(this, Notification.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);