如何停止服务中的意图活动

时间:2015-09-30 09:23:33

标签: android android-intent android-activity android-service

我已经从服务启动了Intent活动。现在,我如何能够停止服务本身的意图活动?

public class MainActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

    public void startService (View view) {
        Intent intent = new Intent(this,MainService.class);
        startService(intent);
    }

    public void stopService (View view) {
        Intent intent = new Intent(this,MainService.class);
        stopService(intent);

    }
}

startService,stopService已关联按钮。

public class MainService extends Service {

    @Override
    public void onCreate() {
        super.onCreate();

    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Toast.makeText(this, "Service started",Toast.LENGTH_LONG).show();
        Intent dialogIntent = new Intent(this, calledActivity.class);
        dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(dialogIntent);

        return START_STICKY;
        //return super.onStartCommand(intent,flags,startId);
    }

    @Override
    public void onDestroy() {
        //super.onDestroy();
        Toast.makeText(this, "Service stopped",Toast.LENGTH_LONG).show();

    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        //Intent dialogIntent = new Intent(this, MainActivity.class);
        //dialogIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        //startActivity(dialogIntent);
        return null;
    }

}


public class calledActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Toast.makeText(this, "I am here", Toast.LENGTH_LONG).show();
        displayNumber();
    }

    @Override
    protected void onStop() {
        super.onStop();
        Toast.makeText(this, "I am stopping", Toast.LENGTH_LONG).show();
        finish();
    }

    @Override
    protected void onDestroy () {
        super.onDestroy();
        Toast.makeText(this, "I am being destroyed", Toast.LENGTH_LONG).show();
        finish();
    }

    public void displayNumber () {
        TextView tv = (TextView)findViewById(R.id.textView);
        Integer counter = 10;
        while (counter > 0) {
            //tv.setText("Here you go" + String.valueOf(counter));
            tv.setText("Here you go" + counter);
            counter = counter - 1 ;
            Toast.makeText(this, "I am there "+counter, Toast.LENGTH_LONG).show();

        }
    }


}

当服务调用意图活动时,我认为意图活动是在前台。现在,每当我按停止服务按钮时,应用程序崩溃。我相信stopService与服务类相关联,但不与intent活动相关联。有没有办法阻止服务的意图活动?

1 个答案:

答案 0 :(得分:0)

Service适用于UI个帖子。尝试使用IntentService。它在后台线程上运行。