我尝试每两秒钟在服务中运行一种方法,但是当我启动服务时,仅运行一次 这是相关代码:
启动服务:
shoppinglist_file.write("%s\n" % (thing_to_add))
这是从我的Service类中获得的:
mViewHolder.mLinearLayoutContainer.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Intent launchIntent = view.getContext().getPackageManager().getLaunchIntentForPackage(mListStorage.get(position).getAdrress());
mApkPackage = mListStorage.get(position).getAdrress();
Intent intent = new Intent(view.getContext(), KillerService.class);
if(mApkPackage != null){
intent.putExtra("NAMEAPK", mApkPackage);
view.getContext().startService(new Intent(view.getContext().getApplicationContext(), KillerService.class));
view.getContext().bindService(intent,mServiceConnection, Context.BIND_AUTO_CREATE);
}
if (launchIntent != null) {
view.getContext().startActivity(launchIntent);//null pointer check in case package name was not found
}
}
});
@Override
protected void onHandleIntent(@Nullable Intent intent) {
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//mAppsNames();
Log.d("SYSTEMRUNNIGKILLI", "matandoapps");
}
}, 2000);
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
mApkName = intent.getStringExtra("NAMEAPK");
Log.d("HOLAXD", mApkName);
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
的一部分仅运行一次,而不是每2秒运行一次。
答案 0 :(得分:3)
每2秒使用一次错误的方法来调用代码。尝试使用此方法
new Timer().scheduleAtFixedRate(new TimerTask() {
@Override
public void run() {}
}, 0, 1000); //1000 miliseconds equal to 1 second
答案 1 :(得分:1)
另一种方法是添加handler.postDelayed(this,2000);
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
@Override
public void run() {
//mAppsNames();
Log.d("SYSTEMRUNNIGKILLI", "matandoapps");
handler.postDelayed(this,2000);
}
}, 2000);