我剛開始使用android開發,我試圖編寫一個在後臺運行的服務,並在特定時間啓動應用程序。創建在特定時間啓動應用程序的後臺服務。
我寫的程序是基於我遇到的教程,基本上應用程序有2個按鈕,一個開始和停止。一旦用戶按下開始按鈕,它將啓動後臺服務並檢查時間,如果時間合適,它將啓動應用程序。
但是我注意到它並不總是檢查時間,只有當用戶按下按鈕時纔會這樣做。我如何做到這一點,一旦用戶按下按鈕,它會不斷檢查時間?
這是我的代碼。 MyService.java
public class MyService extends Service{
private static final String TAG = "MyService";
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
//Toast.makeText(this, "Congrats! MyService Created", Toast.LENGTH_LONG).show();
Log.d(TAG, "onCreate");
}
@Override
public void onStart(Intent intent, int startId) {
//Toast.makeText(this, "My Service Started", Toast.LENGTH_LONG).show();
startApp("com.example.myApp");
Log.d(TAG, "onStart");
}
@Override
public void onDestroy() {
Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
public void startApp(String packageName){
Calendar c = Calendar.getInstance();
SimpleDateFormat sdf = new SimpleDateFormat("HH:mm");
String strDate = sdf.format(c.getTime());
if(strDate == "09:00" || strDate == "15:00" || strDate == "21:00"){
Toast.makeText(this,strDate,Toast.LENGTH_LONG).show();
Toast.makeText(this,"Starting the App",Toast.LENGTH_LONG).show();
Intent intent = getPackageManager().getLaunchIntentForPackage(packageName);
if(intent != null){
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
}
}
}
MainActivity.Java
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
//start the service
public void onClickStartServie(View V)
{
//start the service from here
startService(new Intent(this, MyService.class));
}
//Stop the started service
public void onClickStopService(View V)
{
//Stop the running service from here
//Service will only stop if it is already running.
stopService(new Intent(this, MyService.class));
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
}
檢查:HTTPS ://developer.android.com/training/scheduling/alarms.html – dit 2015-03-25 13:01:58
因此,如果我在上午9點發出警報,然後每隔6小時發出一次警報,並將其放入StartApp功能,它會無限期地在後臺運行? – cyberbemon 2015-03-25 13:12:40