通过处理程序杀死android中的任务

时间:2015-02-22 18:14:24

标签: java android timer android-handler

我通过使用计时器处理程序来安排一些函数。这就是发生的事情。

当我按下按钮时,计时器开始发送短信并打开另一个活动。 然后在另一个活动中我已经停止按钮来终止计时器并返回主活动。 计时器终止,但它会使应用程序崩溃并返回主要活动。

这是代码

MainActivity.java

public class MainActivity extends FragmentActivity{
     protected static final int CONTACT_PICKER_RESULT = 0;


    int count=0;


     private RadioButton radioBtnten;
      private RadioButton radioBtnone;

   Button sendBtn,contact;
   EditText txtphoneNo;
   EditText txtMessage;
   GPSTracker gps;
   Timer timer;

    TimerTask timerTask;
    final Handler handler = new Handler();
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      LocationManager service = (LocationManager) getSystemService(LOCATION_SERVICE);
      boolean enabled = service.isProviderEnabled(LocationManager.GPS_PROVIDER);
      if (!enabled) 
      {
        Toast.makeText(getApplicationContext(), "Your GPS IS NOT ON SWITCH IT ON HERE",Toast.LENGTH_LONG).show();
        Intent intent = new Intent(Settings.ACTION_LOCATION_SOURCE_SETTINGS);
        startActivity(intent);
      } 
      radioBtnten=(RadioButton)findViewById(R.id.ten);
      radioBtnone=(RadioButton)findViewById(R.id.one);
      sendBtn = (Button) findViewById(R.id.btnSendSMS);
      txtphoneNo= (EditText) findViewById(R.id.editTextPhoneNo);
     contact = (Button)findViewById(R.id.contact);
      //txtMessage //= (EditText) findViewById(R.id.editTextSMS);
      gps = new GPSTracker(MainActivity.this);

      contact.setOnClickListener(new View.OnClickListener() {
          public void onClick(View view) {
              Intent intent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
              intent.setType(ContactsContract.CommonDataKinds.Phone.CONTENT_TYPE);
              startActivityForResult(intent, CONTACT_PICKER_RESULT);

          }
       });


      sendBtn.setOnClickListener(new View.OnClickListener() {
         public void onClick(View view) {
             startTimer();
            sendSMSMessage();
            Intent toAnotherActivity = new Intent(MainActivity.this, maps.class);
            startActivityForResult(toAnotherActivity, 0);

         }
      });
   }


   public void startTimer() {
        //set a new Timer
        timer = new Timer();

        //initialize the TimerTask's job
        initializeTimerTask();

        //schedule the timer, after the first 5000ms the TimerTask will run every 10000ms//
         if(radioBtnten.isChecked()==true)
        timer.schedule(timerTask, 5000, 10000);
        // if(radioBtn2.isSelected()==true)
         else if(radioBtnone.isChecked()==true)
        timer.schedule(timerTask, 5000, 1000);
    }
   public void initializeTimerTask() {

        timerTask = new TimerTask() {
            public void run() {

                //use a handler to run a toast that shows the current timestamp
                handler.post(new Runnable() {
                    public void run() {
                        //get the current timeStamp


                        Toast.makeText(getApplicationContext(), "your message has been sent, the message(s) sent are:-"+count++,Toast.LENGTH_LONG).show();
                        sendSMSMessage();

                        //show the toast


                    }
                });
            }
        };
    }

   public void stoptimertask(View v) 
   {
        //stop the timer, if it's not already null

       Toast.makeText(getApplicationContext(), "Stop button pressed",Toast.LENGTH_LONG).show();

        if (timer != null) 
        {
            timer.cancel();
            timer = null;
        }
    }
   protected void sendSMSMessage() {
      Log.i("Send SMS", "");
    double latitude = gps.getLatitude();
    double longitude = gps.getLongitude();

      String phoneNo = txtphoneNo.getText().toString();
      String message = "These are my co-ordinates:-"+ latitude + ", " + longitude; 

      try {
         SmsManager smsManager = SmsManager.getDefault();
         smsManager.sendTextMessage(phoneNo, null, message, null, null);
         Toast.makeText(getApplicationContext(), "SMS sent.",
         Toast.LENGTH_LONG).show();
      } catch (Exception e) {
         Toast.makeText(getApplicationContext(),
         "SMS faild, please try again.",
         Toast.LENGTH_LONG).show();
         e.printStackTrace();
      }
   }

下一个活动就是这个

maps.java

public class maps extends FragmentActivity implements LocationListener {
MainActivity maine= new MainActivity();
    GoogleMap googleMap;
    Button stop;
    Timer timer;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        //show error dialog if GoolglePlayServices not available
        if (!isGooglePlayServicesAvailable()) {
            finish();
        }
        setContentView(R.layout.maps);
        stop = (Button)findViewById(R.id.stop);
        stop.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View aView)
                        {
                                maine.stoptimertask(aView);
                               Intent toAnotherActivity = new Intent(aView.getContext(), MainActivity.class);
                               startActivityForResult(toAnotherActivity, 0);
                               //stop the timer, if it's not already null
                               Toast.makeText(getApplicationContext(), "Stop button pressed",Toast.LENGTH_LONG).show();

                        }
        }); 

我创建了一个mainactivity对象并调用了stoptimertask方法。应用程序崩溃了这个日志猫: -

 FATAL EXCEPTION: main
Process: com.example.textmessage, PID: 27301
 java.lang.NullPointerException: Attempt to invoke virtual method 'android.content.Context android.content.Context.getApplicationContext()' on a null object reference
    at android.content.ContextWrapper.getApplicationContext(ContextWrapper.java:105)
    at com.example.textmessage.MainActivity.stoptimertask(MainActivity.java:129)
    at com.example.textmessage.maps$1.onClick(maps.java:42)
    at android.view.View.performClick(View.java:4756)
    at android.view.View$PerformClick.run(View.java:19749)
    at android.os.Handler.handleCallback(Handler.java:739)
    at android.os.Handler.dispatchMessage(Handler.java:95)
    at android.os.Looper.loop(Looper.java:135)
    at android.app.ActivityThread.main(ActivityThread.java:5221)
    at java.lang.reflect.Method.invoke(Native Method)
    at java.lang.reflect.Method.invoke(Method.java:372)
    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:899)
    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:694)

我想要的是当在maps.java中按下按钮停止时,发送sms功能应该停止并且它应该返回到MainActivity.java

2 个答案:

答案 0 :(得分:2)

您无法使用new创建活动。这不是一个有效的活动。只有Android框架才能创建有效的Activity对象。要启动新活动,请调用startActivity。如果使用new创建一个Activity将编译,该对象将无法正确初始化并导致奇怪的崩溃。

答案 1 :(得分:0)

maine.stoptimertask(aView);不包含正确的实例。

基本上你必须在你的

stop.setOnClickListener (new View.OnClickListener ()
{
            public void onClick(View aView)
            {
                 Intent returnIntent = new Intent();
                 setResult(RESULT_OK,returnIntent);
                 this.finish();
                 //stop the timer, if it's not already null
                 Toast.makeText(getApplicationContext(), "Stop button pressed",Toast.LENGTH_LONG).show();
             }
});

向MainActivity返回您想要去那里并实现

的值
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    // Check which request we're responding to
    if (requestCode == 0) { // because you startActivityForResult(toAnotherActivity, 0);
        // Make sure the request was successful
        if (resultCode == RESULT_OK) {
            stoptimertask(); // forget view you don't need
        }
    }
}

了解您的活动地图中是否有操作。

请参阅此链接中获取活动结果的文档: http://developer.android.com/training/basics/intents/result.html