我正在研究this中的服务教程..我能够完美地运行,我尝试的是在Oncreate
上启动服务并且它确实停止了按钮,但不幸的是onstop
不起作用,因为它没有显示吐司,这里的日志是我的代码......导致onstop
无法正常工作
public void onBackPressed() {
AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Confirm Close");
builder.setMessage("Are you sure you want to exit?");
builder.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
stopService(new Intent(this, MyService.class));
System.exit(0);
finish();
android.os.Process.killProcess(android.os.Process.myPid());
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertdialog=builder.create();
alertdialog.show();
}
服务代码
import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;
import android.widget.Toast;
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();
Log.d(TAG, "onStart");
//Note: You can start a new thread and use it for long background processing from here.
}
@Override
public void onDestroy() {
Toast.makeText(this, "MyService Stopped", Toast.LENGTH_LONG).show();
Log.d(TAG, "onDestroy");
}
}
答案 0 :(得分:1)
按照代码
替换您的代码 public void onBackPressed() {
AlertDialog.Builder builder=new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Confirm Close");
builder.setMessage("Are you sure you want to exit?");
builder.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
stopService(new Intent(this, MyService.class));
Intent intent = new Intent(Intent.ACTION_MAIN);
intent.addCategory(Intent.CATEGORY_HOME);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
}
});
builder.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog alertdialog=builder.create();
alertdialog.show();
}