Android服务一次又一次地创建

时间:2014-11-11 11:19:19

标签: android android-service

我有一个按钮,上面写着以下代码

  Calendar cal = Calendar.getInstance();

                        cal.add(Calendar.SECOND, 10);

                        Intent intent = new Intent(Formact.this, MyService.class);


                        MyService.pintent = PendingIntent.getService(Formact.this, 0, intent, 0);


                        MyService.alarm = (AlarmManager) getSystemService(Context.ALARM_SERVICE);
                                    MyService.alarm.setRepeating(AlarmManager.RTC_WAKEUP,cal.getTimeInMillis(), 5000, MyService.pintent);

现在一旦创建了服务,就必须销毁一个特定的动作,但每次破坏之后它都会再次启动。 这是我的服务类

public class MyService extends Service {
public static int counter = 0;
public static PendingIntent pintent;
public static AlarmManager alarm;
 Boolean save=false;
public MyService() {

}

@Override
public IBinder onBind(Intent intent) {
    return new  Binder() ;
}
@Override
public void onCreate() {
    Toast.makeText(this, "Service was Created", Toast.LENGTH_SHORT).show();
   }

@Override
public void onStart(Intent intent, int startId) {

    counter++;
    Toast.makeText(this, " Service Started" + "  " + counter, Toast.LENGTH_SHORT).show();


    SaveForm handler = new SaveForm(getApplicationContext());



    handler.setobj(getApplicationContext());

    handler.setText(Formact.sendform, Formact.listString);

    handler.stratConnection();

    String m = "";
    int val = 0;
    try{
        Log.e("val",SaveForm.msg);
        if(SaveForm.msg!=null)
        {
        m=SaveForm.msg.substring(SaveForm.msg.length() - 1);
        }
        val=Integer.parseInt(m);

        Log.e("val",m);



    if(val>0)
    {
        Toast toast = Toast.makeText(getApplicationContext(), "Data saved", 100);
        toast.show();
    save=true;
        MyService.this.stopSelf();

    //      alarm.cancel(pintent);



        if(alarm!=null)
        {
            try{
            alarm.cancel(pintent);
            }
            catch(Exception e)
            {
                Toast toasdst = Toast.makeText(getApplicationContext(), "Massi", 100);
                toasdst.show();
            }
            alarm=null;
        }       
    }
    }

    catch(Exception e)
    {
        Toast toast = Toast.makeText(getApplicationContext(), "Data Not saved", 100);
        toast.show();
        ///responseStr = responseStrr;
    }

}

@Override
public void onDestroy() {
    Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
    super.onDestroy();



    if(save)

    {
        try{


             stopSelf();


        }
        catch(Exception e)
        {
            Toast.makeText(this, "Head Bang", Toast.LENGTH_SHORT).show();
            super.onDestroy();
        }
    }

    }
    }

我设置了 alarm.cancle ,但是它会引发异常,因为警告已经 null

我也试过这个

    @Override
public int onStartCommand(Intent intent, int flags, int startId) {
    try{
      //  String parameter = intent.getStringExtra("param_name");
        if(save){
            stopSelf();
        }
    }catch(Exception ex){
    }
    return startId;
}

但是没有任何作品可以一次又一次地开始服务。 还有一件事,如果我没有关闭应用程序,而不是每件事情完美的警报被取消但是当我关闭应用程序并期望运行它同样的背景时它会一次又一次地开始创建。

请帮助。

2 个答案:

答案 0 :(得分:2)

1.请勿在文档中使用onStart()

onStart(Intent intent, int startId)
This method was deprecated in API level 5. Implement onStartCommand(Intent, int, int) instead.

改为使用onStartCommandreturn START_NOT_STICKYSTART_STICKY而不是startId
2.如果您使用handler.stratConnection();绑定任何内容,似乎您正在开始连接bindService(),那么您需要使用unbindService(mConnection)将其与服务解除绑定。如文档中所述:

Disconnect from an application service. You will no longer receive calls as the service is restarted, and the service is now allowed to stop at any time.

如果您没有绑定任何内容,请在null中返回onBind()

@Override
public IBinder onBind(Intent intent) {
    return null;
}

3。像这样使用super.onDestroy()

@Override
public void onDestroy() {
Toast.makeText(this, "Service Destroyed", Toast.LENGTH_SHORT).show();
super.onDestroy();
/***** No need to put this as it is already going to be destroyed
if(save)

{
    try{


         stopSelf();


    }
    catch(Exception e)
    {
        Toast.makeText(this, "Head Bang", Toast.LENGTH_SHORT).show();
        super.onDestroy();
    }
}

}
*****/
}

4。在致电alarm.cancel(pintent)之前,请stopSelf()取消闹钟。

if(alarm!=null)
    {
        try{
        alarm.cancel(pintent);
        }
        catch(Exception e)
        {
            Toast toasdst = Toast.makeText(getApplicationContext(), "Massi", 100);
            toasdst.show();
        }
        alarm=null;
    }
MyService.this.stopSelf();

5。您正在使用alarmpintent而未初始化它。它未在您的代码中初始化。 6.使用与context.stopService(intent)相同的意图,使用Intent intent = new Intent(Formact.this, MyService.class);停止活动中的服务。

答案 1 :(得分:-1)

使用

将数据存储到服务器时
 handler.setText(Formact.sendform, Formact.listString);

只需保存数据即可生成

Formact.sendform=null
 Formact.listString=null

当这些值为null时,应用程序将在catch块中抛出异常并使用此行关闭

    MyService.alarm.cancel(MyService.pintent);
    MyService.this.stopService();

服务不会重新开始。