簡體   English   中英

我正在嘗試從后台運行的服務開始一項活動,但是該服務無法正常工作..有人可以幫幫我嗎?

[英]I'm trying to start an activity from a service running in background but its not working..can anyone help me out?

我正在嘗試從在后台運行的服務開始一項活動,但是它無法正常工作..這是代碼。 服務類使用意圖來調用活動類。 誰能幫我嗎??

//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);
    }   
}

由於Service不是UI組件,因此您需要啟動新任務。 使用FLAG_ACTIVITY_NEW_TASK

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM