Android服务未在后台运行

时间:2015-06-17 17:20:27

标签: android android-service

我正在开发一个生日提醒应用。我正在使用服务来获取上午12点的通知。& am;从片段的OnCreateView()方法调用该服务。但是当我的应用关闭时,服务没有在后台运行。

如何让服务始终运行?

服务类

package works.viswajith.birthdayreminder;

import android.app.NotificationManager;
import android.app.Service;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.os.IBinder;
import android.support.v4.app.NotificationCompat;
import android.widget.Toast;
import java.util.Calendar;

/**
* Created by Viswajith on 6/17/2015.
*/
public class NotificationService extends Service {

DBHelper db;
private Cursor cur;
private Calendar cal;
private int d,m,y;
private String[] temp;
private NotificationManager nm;
int i=0;


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

    db=new DBHelper(getApplicationContext());
    cur=db.getDetails();
    cal= Calendar.getInstance();
    d=cal.get(Calendar.DAY_OF_MONTH);
    m=cal.get(Calendar.MONTH)+1;
    y=cal.get(Calendar.YEAR);

}


@Override
public int onStartCommand(Intent intent, int flags, int startId) {

    Toast.makeText(getApplicationContext(),"Service",Toast.LENGTH_SHORT).show();

    i=0;
    cur.moveToFirst();

    for(i=0;i<db.getCount();i++)
    {
       temp=cur.getString(2).split("/");
        if(Integer.parseInt(temp[0])==d && Integer.parseInt(temp[1])==m)
        {

            NotificationCompat.Builder mbuilder=new NotificationCompat.Builder(this);
            mbuilder.setSmallIcon(R.drawable.happy);
            mbuilder.setContentTitle("Happy B'day "+cur.getString(0));
            mbuilder.setContentText("Today is "+cur.getString(0)+"'s B'day , Wish him ..");
            nm=(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
            nm.notify(100,mbuilder.build());


        }

        cur.moveToNext();

    }

    return Service.START_STICKY;
}

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

片段类

package works.viswajith.birthdayreminder;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.Calendar;

import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.Toast;
import android.database.Cursor;
import android.database.DatabaseUtils;


/**
* Created by Viswajith on 6/8/2015.
*/
public class BirthdayFragment extends Fragment {

private View v;
private RecyclerView mRecyclerView;
private RecyclerView.Adapter mAdapter;
private RecyclerView.LayoutManager mLayoutManager;

Cursor c;
DBHelper db;
Intent i;
int count=0;

private static String LOG_TAG = "CardViewActivity";


@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {

    i=new Intent(getActivity(),NotificationService.class);
    getActivity().startService(i);

    setHasOptionsMenu(true);
    v=inflater.inflate(R.layout.birthday_fragment,container,false);

    db=new DBHelper(getActivity());

    mRecyclerView = (RecyclerView) v.findViewById(R.id.my_recycler_view);
    mRecyclerView.setHasFixedSize(true);
    mLayoutManager = new LinearLayoutManager(getActivity());
    mRecyclerView.setLayoutManager(mLayoutManager);
    mAdapter = new MyRecyclerViewAdapter(getDataSet());
    mRecyclerView.setAdapter(mAdapter);


    return v;

}

@Override
public void onResume() {

    i=new Intent(getActivity(),NotificationService.class);
    getActivity().startService(i);

    super.onResume();
}

private ArrayList<DataObject> getDataSet() {

    ArrayList results = new ArrayList<DataObject>();

    count=0;

    c=db.getDetails();

    Calendar cal=Calendar.getInstance();
    int day=cal.get(Calendar.DAY_OF_MONTH);
    int month=cal.get(Calendar.MONTH)+1;


    if(c.getCount()!=0)
    {
    for (int index = 0; index < c.getCount(); index++) {

        String str[]=c.getString(2).split("/");

        if((month==Integer.parseInt(str[1])&&    (Integer.parseInt(str[0]))>day)) {
            DataObject obj = new DataObject(c.getString(0).toString() + "'s  B'day",
                    c.getString(1).toString(), c.getString(2).toString());
            results.add(count,obj);
            count++;
        }
        c.moveToNext();
    }
  }
    return results;
}


@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {

    super.onCreateOptionsMenu(menu,inflater);

    MenuItem refresh=menu.add(1,100,1,"Refresh");
    refresh.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
    refresh.setIcon(R.drawable.ic_autorenew_black_18dp);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    switch(item.getItemId()) {

        case 100: mAdapter = new MyRecyclerViewAdapter(getDataSet());
                  mRecyclerView.setAdapter(mAdapter);
            break;
    }

   return super.onOptionsItemSelected(item);
}

}

2 个答案:

答案 0 :(得分:2)

您应该使用AlarmManager Class。它专门用于此目的。 这是教程的链接。 http://www.learn-android-easily.com/2013/05/android-alarm-manager_31.html

答案 1 :(得分:1)

让您的服务前景。然后它不会被android杀死。