任何人都可以帮助我,我在android中。
我想在 10 分钟的空闲时间后关闭应用程序,我在网上搜索并找到了这个链接:
但我对这部分代码有一点问题:
// soft stopping of thread
public synchronized void stop() {
stop = true;
}
出现此错误:
此行有多个标记 - 无法覆盖 Thread 的最终方法 - 覆盖 java.lang.Thread.stop
请帮助我理解它。
谢谢!
似乎stop()
不需要解决问题。我建议这样做:
public class Waiter extends Thread {
private static final String TAG=Waiter.class.getName();
private long lastUsed;
private long period;
private boolean stop;
private final WeakReference<Context> mContextRef;
public Waiter(final long period, final Context context) {
this.period = period;
stop = false;
mContextRef = new WeakReference<Context>(context);
}
public void run() {
long idle = 0;
this.touch();
do {
idle = System.currentTimeMillis()-lastUsed;
Log.d(TAG, "Application is idle for " + idle + " ms");
try {
Thread.sleep(5000); //check every 5 seconds
if(idle > period) {
final Context context = mContextRef.get();
if (context != null) {
// start activity
startActivity(context);
}
stop = true;
}
}
catch (InterruptedException e) {
Log.d(TAG, "Waiter interrupted!");
// set stop, because smb has called interrupt() on the thread
stop = true;
}
}
while(!stop);
Log.d(TAG, "Finishing Waiter thread");
}
private void startActivity(final Context context) {
final Intent intent = new Intent(context, MyActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
try {
context.startActivity(intent);
} catch (ActivityNotFoundException e) {
// If there is nothing that can send a text/html MIME type
e.printStackTrace();
}
}
public synchronized void touch() {
lastUsed=System.currentTimeMillis();
}
public synchronized void setPeriod(long period) {
this.period=period;
}
}
因此,它将是一次性线程(一旦空闲超时,您将需要创建新线程),您只需使用标准 API Thread.interrupt()即可随时停止。
public class test extends Activity {
ImageView _playButton;
Handler h;
Runnable r;
LinearLayout mainLayout;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mainLayout=(LinearLayout)findViewById(R.id.mainLayout);
h=new Handler();
r=new Runnable() {
@Override
public void run() {
// TODO Auto-generated method stub
finish();
}
};
mainLayout.setOnTouchListener(new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
shutIdleApp();
return false;
}
});
}
@Override
protected void onDestroy() {
// TODO Auto-generated method stub
super.onDestroy();
h.removeCallbacks(r);
}
public void shutIdleApp()
{
h.removeCallbacks(r);
h.postDelayed(r,10*1000);
}
}
这是我对问题的实现,以防人们在使用复杂代码时感到不舒服。