如何在应用关闭时让服务在后台运行?

时间:2016-02-17 04:17:34

标签: android service alarmmanager

所以我有这个代码设置在每天上午9点30分运行服务

Calendar cal = Calendar.getInstance();
        cal.setTimeInMillis(System.currentTimeMillis());
        cal.set(Calendar.HOUR_OF_DAY, 9);
        cal.set(Calendar.MINUTE,30);


        Intent start = new Intent(getActivity(), Services.class);
        PendingIntent PI = PendingIntent.getService(getActivity(), 0, start, 0);
        AlarmManager am = (AlarmManager)getActivity().getSystemService(getActivity().ALARM_SERVICE);
        //am.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 1000*60*60*24, PI);
        am.setInexactRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(),AlarmManager.INTERVAL_DAY, PI);
        getActivity().startService(new Intent(getActivity(), Services.class));

当我打开应用程序时它起作用,但当我关闭应用程序时,该服务根本没有运行。该服务应该根据此代码显示通知

package apps.skripsi.petvac.Services;

import android.app.IntentService;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Handler;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.app.AlertDialog;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import org.apache.http.client.ClientProtocolException;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.Locale;

import apps.skripsi.petvac.MainMenu.MainMenuAdapter;
import apps.skripsi.petvac.R;
import apps.skripsi.petvac.navigationmenu.MainMenu;
import apps.skripsi.petvac.notification.NotificationButtonReceiver;
import apps.skripsi.petvac.parser.JSONParser;
import apps.skripsi.petvac.petinformation.MainPetInformation;
import apps.skripsi.petvac.preference.PreferencesHelper;


public class Services extends IntentService {
    Handler handler = new Handler();
    PreferencesHelper ph;
    MainMenu mm;
    JSONObject json;
    JSONObject jsonObject;
    NotificationManager mNotificationManager;
    int days;
    String result, result2;
    String sisaWaktu, sisa_hari;
    String ID_USER, ID_BINATANG, NAMA_BINATANG, JENIS_BINATANG, FOTO_BINATANG, RAS_BINATANG, TANGGAL_VAKSIN, NAMA_VAKSIN, STATUS_VAKSIN, ID_DATA_WAKTU_VAKSINASI;

    ArrayList<HashMap<String, String>> listBinatang = new ArrayList<HashMap<String, String>>();

    public static String id_user = "id_user";
    public static String id_binatang = "id_binatang";
    public static String nama_binatang = "nama_binatang";
    public static String jenis_binatang = "jenis_binatang";
    public static String foto_binatang = "foto_binatang";
    public static String ras_binatang = "ras_binatang";
    public static String tanggal_vaksin = "tanggal_vaksin";
    public static String nama_vaksin = "nama_vaksin";
    public static String jumlah_hari;
    public static String status_vaksin = "status_vaksin";
    public static String id_data_waktu_vaksinasi = "id_data_waktu_vaksinasi";

    private Context context;

    private static String url = "http://petvaccination.hol.es/api/data_menu_utama_vaksinasi.php";

    public Services() {
        super("Services");
    }

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    protected void onHandleIntent(Intent intent) {

    }

    @Override
    public void onCreate() {
        // TODO Auto-generated method stub
        super.onCreate();
        System.out.println("create");

    }

    @SuppressWarnings("static-access")
    @Override
    public void onStart(Intent intent, int startId) {

        ph = new PreferencesHelper(getApplicationContext());
        mm = new MainMenu();

/*            // TODO Auto-generated method stub
            new Handler().postDelayed(new Thread() {
                public void run() {
                    super.run();
                        handler.postDelayed(this, 30000);*/
                        new DataBinatangOperation().execute(url);
                        Toast.makeText(Services.this,"Muncul",Toast.LENGTH_SHORT).show();
/*
                }
            }, 5000);*/
        }


    @Override
    public void onDestroy() {
        // TODO Auto-generated method stub
        handler.removeCallbacks(null);
        System.out.println("destroy");
        super.onDestroy();
    }

    public class DataBinatangOperation extends AsyncTask<String, Void, String> {


        @Override
        protected String doInBackground(String... params) {

            JSONArray json;
            try {
                result = JSONParser.getPage(url);
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            return result;

        }


        @Override
        protected void onPostExecute(String result) {

            try {
                System.out.print("result = " + result);
                json = new JSONObject(result);
                //progress.dismiss();

                JSONArray objek = json.getJSONArray("data_vaksinasi_menu");

                for (int i = 0; i < objek.length(); i++) {

                    JSONObject jo = objek.getJSONObject(i);

                    ID_USER = jo.getString(id_user);
                    ID_BINATANG = jo.getString(id_binatang);
                    NAMA_BINATANG = jo.getString(nama_binatang);
                    JENIS_BINATANG = jo.getString(jenis_binatang);
                    FOTO_BINATANG = jo.getString(foto_binatang);
                    RAS_BINATANG = jo.getString(ras_binatang);
                    ID_DATA_WAKTU_VAKSINASI = jo.getString(id_data_waktu_vaksinasi);
                    TANGGAL_VAKSIN = jo.getString(tanggal_vaksin);
                    NAMA_VAKSIN = jo.getString(nama_vaksin);
                    STATUS_VAKSIN = jo.getString(status_vaksin);

                    if (ph.getPreferences("ID").equals(ID_USER)) {


                            DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd", Locale.getDefault());

                            Calendar waktuSekarang = Calendar.getInstance();

                            Date date1 = waktuSekarang.getTime();
                            Date date2 = new Date();

                            date2 = formatter.parse(TANGGAL_VAKSIN);

                            if (date2.after(date1)) {
                                days = Days.daysBetween(new DateTime(date1), new DateTime(date2)).getDays();
                                if (days > 7 && days <= 30) {
                                    int weeks = days / 7;
                                    sisa_hari = String.valueOf(days);
                                    sisaWaktu = String.valueOf(weeks) + " minggu";
                                } else if (days > 30 && days <= 365) {
                                    int months = days / 30;
                                    sisa_hari = String.valueOf(days);
                                    sisaWaktu = String.valueOf(months) + " bulan";
                                } else if (days > 365) {
                                    int years = days / 365;
                                    sisa_hari = String.valueOf(days);
                                    sisaWaktu = String.valueOf(years) + " tahun";
                                } else {
                                    sisaWaktu = String.valueOf(days) + " hari";
                                    if (days <= 5) {
                                        sisa_hari = String.valueOf(days);
                                        /*if(!result.equals(result2)) {*/
                                        createSimpleNotification(context, NAMA_BINATANG, sisa_hari, ID_BINATANG);
                                       /* }*/
                                    }
                                }
                            } else if (date2.before(date1)) {
                                days = Days.daysBetween(new DateTime(date2), new DateTime(date1)).getDays();
                                if (days == 0) {
                                    sisaWaktu = "sekarang";
                                    sisa_hari = String.valueOf(days);
                                    if (STATUS_VAKSIN.equals("belum")) {
                                        /*if(!result.equals(result2)) {*/
                                        createButtonNotification(context, NAMA_BINATANG, sisaWaktu, sisa_hari, ID_BINATANG, ID_DATA_WAKTU_VAKSINASI);
                                        /*}else {
                                            return;
                                        }*/
                                    }/*else{
                                        return;
                                    }*/
                                } else {
                                    sisaWaktu = "lewat " + String.valueOf(days) + " hari";
                                    sisa_hari = String.valueOf(days);
                                    if (STATUS_VAKSIN.equals("belum")) {
                                        /*if(!result.equals(result2)){*/
                                        createButtonNotification(context, NAMA_BINATANG, sisaWaktu, sisa_hari, ID_BINATANG, ID_DATA_WAKTU_VAKSINASI);
                                        /*}else{
                                            return;
                                        }*/
                                    }
                                }
                            }

                        }

                    }







            } catch (JSONException e1) {
                // TODO Auto-generated catch block
                e1.printStackTrace();
            } catch (ParseException e) {
                e.printStackTrace();
            }

        }

        @Override
        protected void onPreExecute() {

        }

        @Override
        protected void onProgressUpdate(Void... values) {
        }
    }

    public void createSimpleNotification(Context context, String nama_binatang, String sisa_hari, String id) {

        Intent resultIntent = new Intent(getApplicationContext(), MainPetInformation.class);
        resultIntent.putExtra("IDB", id);
        resultIntent.putExtra("SW", sisa_hari);
        resultIntent.putExtra("IDVAK", "");

        mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(this.NOTIFICATION_SERVICE);

        int IntID = Integer.valueOf(id);

        Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);

        PendingIntent resultPending = PendingIntent.getActivity(getApplicationContext(), IntID, resultIntent, PendingIntent.FLAG_UPDATE_CURRENT);

        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.logo)
                .setContentTitle(nama_binatang)
                .setContentText(sisa_hari + " hari lagi")
                .setSound(uri)
                .setContentIntent(resultPending);

        mNotificationManager.notify(IntID, mBuilder.build());
    }

    public void createButtonNotification(Context context, String nama_binatang, String sisa_waktu, String sisa_hari, String idb, String idv) {

        Log.d("idb", idb);

        int IntID = Integer.valueOf(idb);
        int sisaHari = Integer.valueOf(sisa_hari);
        String sisa_hari2;

        Intent intent = new Intent(getApplicationContext(), MainPetInformation.class);

        intent.putExtra("IDB", idb);
        intent.putExtra("IDVAK", idv);
        if (sisaHari > 0) {
            sisa_hari2 = "-" + sisa_hari;
            intent.putExtra("SW", sisa_hari2);
        } else if (sisaHari == 0) {
            intent.putExtra("SW", sisa_hari);
        }

        Intent cancelIntent = new Intent(getApplicationContext(), NotificationButtonReceiver.class);
        cancelIntent.putExtra("notifID", IntID);

        mNotificationManager = (NotificationManager) getApplicationContext().getSystemService(this.NOTIFICATION_SERVICE);

        Uri uri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);


        PendingIntent IntentAccept = PendingIntent.getActivity(getApplicationContext(), IntID, intent, PendingIntent.FLAG_UPDATE_CURRENT);

        PendingIntent IntentCancel = PendingIntent.getActivity(getApplicationContext(), IntID, cancelIntent, 0);

        // Building the notifcation
        NotificationCompat.Builder nBuilder = new NotificationCompat.Builder(this)
                .setSmallIcon(R.drawable.logo)
                .setContentTitle(nama_binatang)
                .setContentText(sisa_waktu)
                .setSound(uri)
                .addAction(R.drawable.accept, "Accept", IntentAccept)
                .addAction(R.drawable.cancel, "Cancel", IntentCancel);

        nBuilder.setAutoCancel(true);
        mNotificationManager.notify(IntID, nBuilder.build());


    }
}

即使应用已关闭,任何使其在后台运行的解决方案?

1 个答案:

答案 0 :(得分:0)

您可以使用闹钟管理器来执行此操作

 Calendar cur_cal = Calendar.getInstance();
        cur_cal.setTimeInMillis(System.currentTimeMillis());
        cur_cal.add(Calendar.SECOND, 50);

    Intent intent = new Intent(YourActivity.this, ServiceClass.class);
    PendingIntent pintent = PendingIntent.getService(YourActivity.this, 0, intent, 0);
    AlarmManager alarm = (AlarmManager)getSystemService(Context.ALARM_SERVICE);
    alarm.setRepeating(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), 30*1000, pintent);

另外,您确保在manifestet文件中声明了服务类,如此

 <service android:enabled="true" android:name=".ServiceClass" />

希望这会对你有所帮助