为什么我的服务没有开始?

时间:2014-07-10 04:00:23

标签: android service timer fragment android-context

下面是我的服务代码: -

提醒服务: -

 public class ReminderService extends Service
{

    DBAdapter dbAdapter;
    //Timer timer;
    int counter;
    private NotificationManager nm;
    List<Reminder> rem_lst ;
    String str_CurrentMonth, str_storedDate, str_currentDate, str_CurrentDate,str_CurrentYear;;
    Calendar calendar;
    int month;
    int year;   
    int day;
    //final String dateTemplate = "MMMM yyyy";
    final String monthTemplate = "MM";
    String format = "yyyy/MM/dd hh:mm:ss"; 
     SimpleDateFormat sdf1 = new SimpleDateFormat(format, Locale.US);
    final String dateTemplate = "yyyy/MM/dd HH:mm:ss";
    String Category, Note;

    private static final String date = "dd";
    private static final String yearTemplate = "yyyy";

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

    @Override
    public void onCreate()
    {


    }

    private void showNotifacation()
    {
        /*// TODO Auto-generated method stub
        CharSequence text ="service_started";

        // Set the icon, scrolling text and timestamp
        Notification notification = new Notification(R.drawable.ic_launcher, text,
                System.currentTimeMillis());

        // The PendingIntent to launch our activity if the user selects this notification
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0,
                new Intent(this, MainActivity.class), 0);

        // Set the info for the views that show in the notification panel.
        notification.setLatestEventInfo(this, "ReminderService",
                       text, contentIntent);

        // Send the notification.
        // We use a layout id because it is a unique number.  We use it later to cancel.
        nm.notify(1, notification);*/
        NotificationCompat.Builder builder =
                new NotificationCompat.Builder(this)
                        .setSmallIcon(R.drawable.icon72)
                        .setContentTitle(Category)
                        .setContentText(Note);
        int NOTIFICATION_ID = 12345;

        Intent targetIntent = new Intent(this,MainActivity.class);
        PendingIntent contentIntent = PendingIntent.getActivity(this, 0, targetIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        builder.setContentIntent(contentIntent);
        Uri uri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_ALARM);
        builder.setSound(uri);
        nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
        nm.notify(NOTIFICATION_ID, builder.build());
        return;
    }

    @Override
    public void onDestroy()
    {
        // TODO Auto-generated method stub
        super.onDestroy();

    }


    @Override
    public int onStartCommand(Intent intent, int flags, int startId)
    {
        super.onCreate();

        scheduleTaskExecutor = Executors.newScheduledThreadPool(1);

        dbAdapter = new DBAdapter(this);
        dbAdapter.open();

        calendar = Calendar.getInstance(Locale.US); 
        month = calendar.get(Calendar.MONTH) + 1; 
        year = calendar.get(Calendar.YEAR); 
        day = calendar.get(Calendar.DAY_OF_MONTH);
        str_CurrentMonth = DateFormat.format(monthTemplate, calendar.getTime()).toString();
        str_currentDate = DateFormat.format(dateTemplate, calendar.getTime()).toString();

        str_CurrentDate = DateFormat.format(date, calendar.getTime()).toString();
        str_CurrentYear = DateFormat.format(yearTemplate, calendar.getTime()).toString();

        rem_lst = dbAdapter.getMonthlyReminders(str_CurrentMonth,str_CurrentDate,str_CurrentYear);

        nm = (NotificationManager)getSystemService(NOTIFICATION_SERVICE);
        // TODO Auto-generated method stub

        //Toast.makeText(this, "Reminder Service Created", Toast.LENGTH_LONG).show();



        // This schedule a runnable task every 2 minutes
        scheduleTaskExecutor.scheduleAtFixedRate(new Runnable() {
        public void run() 
          {
/*//              Log.d("bgService", ""+TimeUnit.SECONDS);
              calendar = Calendar.getInstance();
              str_CurrentMonth = DateFormat.format(monthTemplate, calendar.getTime()).toString();
              //str_currentDate = DateFormat.format(dateTemplate, calendar.getTime()).toString();
              //str_currentDate = "2014/04/2 15:30:53";
              Log.i("Current Date",""+str_currentDate);
                for(int i = 0 ; i < rem_lst.size() ; i ++ )
                  {
                    String str_storedDate = rem_lst.get(i).rem_date;
                    String Category = rem_lst.get(i).rem_catagory;

//                      if(savedDate.compareTo(currentDate)>0){
//                          System.out.println("Date1 is after Date2");
//                      }
//                      if(savedDate.compareTo(currentDate)<0){
//                          System.out.println("Date1 is before Date2");
//                      }
                    if(str_storedDate.compareTo(str_currentDate)==0){
                        System.out.println("Date1 is equal to Date2");
                        showNotifacation();
                    }*/
             String myFormat = "yyyy/MM/dd hh:mm:ss"; 
             String yearFormat = "yyyy";
             String monthFormat = "MM";
             String dateFormat = "dd";
             String timeFormat = "kk:mm:ss";

             SimpleDateFormat sdf = new SimpleDateFormat(myFormat, Locale.US);
                Date savedDate,currentDate;
                for (int i = 0; i < rem_lst.size(); i++)
                {
//                  Toast.makeText(this, ""+rem_lst.get(i).rem_date, Toast.LENGTH_LONG).show();
                    try
                    {
                        String str = rem_lst.get(i).rem_date;
                        Category = rem_lst.get(i).rem_catagory;
                        Note = rem_lst.get(i).rem_note;
                        //savedDate = sdf.parse(str);
                        savedDate = sdf.parse(str);
                        /*String CDate = String.valueOf(calendar.getTime());
                        currentDate = sdf.parse(CDate);*/
                        calendar = Calendar.getInstance(Locale.US); 
                        //currentDate = calendar.getTime();
                        //currentDate = sdf.parse("2014/4/16 21:1:40");
                        //String cDate = DateFormat.format(dateTemplate,calendar.getTime()).toString();
                        //String cDate = calendar.getTime().toString();
                        //currentDate = sdf.parse(cDate);
                        //currentDate = calendar.getTime();
                        String currentMonth = DateFormat.format(monthFormat, calendar.getTime()).toString();
                        String currentYear = DateFormat.format(yearFormat, calendar.getTime()).toString();
                        String crtDate = DateFormat.format(dateFormat, calendar.getTime()).toString();
                        String currentTime = DateFormat.format(timeFormat, calendar.getTime()).toString();
                        String current = currentYear+"/"+currentMonth+"/"+crtDate+" "+currentTime;
                        currentDate = sdf.parse(current);

                        if(savedDate.compareTo(currentDate)==0){
                            System.out.println("Date1 is equal to Date2");
                            System.out.println("Showing Notification. . . . . . . . . ");
                            showNotifacation();
                            Globals.lst_reminder.remove(i);
                            break;
                        }

                       System.out.println("Date1 is not equal to Date2");
                    }catch (ParseException e)
                    {
                        // TODO Auto-generated catch block
                        e.printStackTrace();
                    }
//                      else{
//                          System.out.println("How to get here?");
//                      }
//                      Toast.makeText(this,cDate.toString(), Toast.LENGTH_LONG).show();
                }
          }
        }, 0, 1, TimeUnit.SECONDS);


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

我想在应用程序启动时启动服务,所以我在mainactivity的onCreate()中调用了以下内容: -

getApplicationContext().startService(new Intent(getApplicationContext(), ReminderService.class));

在设置片段中,我给了两个开/关按钮,我为他们的onclick事件()编写了以下内容: -

for: -

getActivity().startService(new Intent(getActivity(), ReminderService.class));

和关闭: -

 getActivity().stopService(new Intent(getActivity(), ReminderService.class));

我的问题是当应用程序启动时,服务被调用但从未启动。当我进入设置片段并单击ON按钮和OFF按钮时,再次ON按钮它完美地工作。此外,它没有停止,我尝试timer.cancel和timer.purge()但没有任何反应。有人请告诉我这里发生了什么? 请建议我如何在设置屏幕上成功启动应用程序启动和开/关。

1 个答案:

答案 0 :(得分:0)

只需在您的Android清单文件中声明您的服务:

 <service android:name="<your service package  (ie)com.emdsys.android.pacs.services.NotificationServiceforRecorder>" >
        </service>