我正在尝试从后台运行的服务开始一项活动,但它不能正常工作......任何人都可以帮助我吗?

时间:2012-01-26 02:22:15

标签: android android-intent

我正在尝试从后台运行的服务启动一个活动,但它不起作用..这是代码。服务类使用intent来调用activity类。任何人都可以帮助我吗?

//The service class
public class ServiceTemplate extends Service
{
    // code to execute when the service is starting up 
    @Override
    public void onStart(Intent intent, int startid)
    {
        Toast.makeText(getBaseContext(), "Accelerometer initiated", Toast.LENGTH_SHORT).show();

        // to set a delay
        Runnable mMyRunnable = new Runnable()
        {
           @Override
           public void run()
           {
               Toast.makeText(getBaseContext(), "Accelerometer running", Toast.LENGTH_SHORT).show();
               // Change state here
           }
        };

        Handler myHandler = new Handler();
        myHandler.postDelayed(mMyRunnable, 5000);

        Intent i = new Intent(this, TimerAct.class);
        startActivity(i);
    }
}

//The Activity class
public class TimerAct extends Activity
{
    static TextView timeDisplay;

/** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.time);

        int length = 30000;

        timeDisplay = (TextView) findViewById(R.id.timer);
        timeDisplay.setText("Time left: " + length / 1000);
    }   
}

1 个答案:

答案 0 :(得分:0)

由于Service不是UI组件,因此您需要启动新任务。使用FLAG_ACTIVITY_NEW_TASK

Intent i = new Intent(this, TimerAct.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);