2

帮我解决这个问题。

我在本地数据库中有一些日期,每天我想在特定时间检查数据库日期和当前日期,如果数据库日期与当前日期匹配在状态栏中显示通知

我已经添加了我的代码,

登录-->MyNotificationService-->Scheduleclient-->ScheduleServcie-->AlarmTask-->NotifyService 流程,这里一旦服务启动,正在检索数据库数据但条件不是每天都检查。我想检查本地数据库保存日期和当前日期,如果两者相同则开始通知。

此链接我已用于参考

登录.Java

import android.widget.Button;
import android.widget.EditText;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;

public class sign_in extends Activity implements OnClickListener {

    TextView Signin, ForgotPasword;
    private EditText EMAIL, PASSWORD;
    private Button login;

    // for Shared preferences
    public static String email = "";
    public static String password = "";
    public static String storedPassword = "";


    // This is a handle so that we can call methods on our service
    private ScheduleClient scheduleClient;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        requestWindowFeature(Window.FEATURE_NO_TITLE);

        setContentView(R.layout.sign_in);

        // Session Manager
        session = new SessionManagerFor_Signin(getApplicationContext());


        DB = new DataBaseConnector_forsignUp(this);
        DB = DB.open();

        Signin = (TextView) findViewById(R.id.textView1);
        login = (Button) findViewById(R.id.button1);
        ForgotPasword = (TextView) findViewById(R.id.textView4);
        EMAIL = (EditText) findViewById(R.id.editText1);
        PASSWORD = (EditText) findViewById(R.id.editText2);

        login.setOnClickListener(this);


        //new Service bind for Notification
                // Create a new service client and bind our activity to this service
                scheduleClient = new ScheduleClient(this);
                scheduleClient.doBindService();

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {

        case R.id.button1:


            email = EMAIL.getText().toString();
            password = PASSWORD.getText().toString();

            session.createLoginSession(email, password);

            if (email.equals("") || password.equals("")) {
                // user didn't entered user name or password
                // Show alert asking him to enter the details
                alert.showAlertDialog(sign_in.this, "Login failed...","Please Enter Email and Password", false);

            } else {

                // fetch the Password form database for respective Email
                storedPassword = DB.getSinlgeEntry(email);
                if (password.equals(storedPassword)) {

                    Toast.makeText(sign_in.this, "Login Successfull",Toast.LENGTH_LONG).show();
                    Intent intent = new Intent(sign_in.this, Page1.class);

                    startActivity(intent);
                    finish();


                    //Calling the Notication for Notification Process
                    Intent myIntent1 = new Intent(sign_in.this,MyNotificationService.class);
                    pendingintent2 = PendingIntent.getService(sign_in.this, 0,myIntent1, 0);
                    AlarmManager alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE);
                    Calendar calendar1 = Calendar.getInstance();
                    calendar1.setTimeInMillis(System.currentTimeMillis());
                    calendar1.add(Calendar.SECOND, 40);
                    alarmManager1.set(AlarmManager.RTC_WAKEUP,calendar1.getTimeInMillis(), pendingintent2);

                    long time24h = 24*60*60*1000;

                    alarmManager1.setRepeating(AlarmManager.RTC_WAKEUP,calendar1.getTimeInMillis(), time24h,pendingintent2);

                    // get Internet status
                    isInternetPresent = cd1.isConnectingToInternet();

                }


        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        // Close The Database
        DB.close();
    }



    //Stop the Notification
     @Override
        protected void onStop() {
            // When our activity is stopped ensure we also stop the connection to the service
            // this stops us leaking our activity into the system *bad*
            if(scheduleClient != null)
                scheduleClient.doUnbindService();
            super.onStop();
        }
}

我的通知服务 .Java

package com.example;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import com.example.database.DatabaseConnector_forProduct;
import com.example.service.ScheduleClient;
import com.example.web.ProductPojo;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.util.Log;


public class MyNotificationService extends Service

{

    // This is a handle so that we can call methods on our service
    private ScheduleClient scheduleClient;
    DatabaseConnector_forProduct helper=new DatabaseConnector_forProduct(this);
    public String ExpiryDate;
    private String TAG1 = "Notify..!!";
    @Override
    public void onCreate() 
    {
        Log.i(TAG1, "Notification Created");
        //new Service bind for Notification
                // Create a new service client and bind our activity to this service
                scheduleClient = new ScheduleClient(this);
                scheduleClient.doBindService();

    }
    @Override
    public IBinder onBind(Intent intent) 
    {
    //Toast.makeText(this, "MyAlarmService.onBind()", Toast.LENGTH_LONG).show();
    return null;
    }
    @Override
    public void onDestroy() 
    {
    super.onDestroy();



    }

    @SuppressWarnings("deprecation")
    @Override
    public void onStart(Intent intent, int startId) 
    {
    super.onStart(intent, startId);

     try 
     {

         List<ProductPojo> val1 = helper.getAllvalues();
           //    "Reading all data..from Db ", Toast.LENGTH_LONG).show();

              for (int i=0;i<val1.size();i++) 
              {

                  ExpiryDate = val1.get(i).getExpiry_Date();

                //for Showing List view  Data
                String dt = ExpiryDate;
                SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
                Calendar cd = Calendar.getInstance();
                try
                {
                    cd.setTime(sdf.parse(dt));

                } 
                catch (ParseException e) 
                {
                    e.printStackTrace();
                }


                SimpleDateFormat sdfr = new SimpleDateFormat("yyyy-MM-dd");
                Calendar cal = Calendar.getInstance();
                Date Warranty_Expired_Date = sdfr.parse(sdfr.format(cd.getTime()));
                String dateExpiry=Warranty_Expired_Date.toString();
                Date Current_Date = sdfr.parse(sdfr.format(cal.getTime()));
                Log.i(TAG1,dateExpiry+"=="+Current_Date);

         if(Warranty_Expired_Date.equals(Current_Date))
         {
            Calendar cd1 = Calendar.getInstance();
            /*int DaySpecific = cd1.get(Calendar.DAY_OF_MONTH);
            int month_Specfic = cd1.get(Calendar.MONTH);
            int year_Specific = cd1.get(Calendar.YEAR);
            cd1.set(year_Specific, month_Specfic, DaySpecific);
            cd1.set(Calendar.HOUR_OF_DAY, 5);//24 Hour Format
            cd1.set(Calendar.MINUTE, 30);
            cd1.set(Calendar.SECOND, 0);*/
        // Ask our service to set an alarm for that date, this activity talks to the client that talks to the service
            scheduleClient.setAlarmForNotification(cd1);
         }
         else
         {

         }

 }

     } 
     catch (Exception e) 
     {
         e.printStackTrace();
         Log.i(TAG1,"Exception Caught");

     }



    }

    @Override
    public boolean onUnbind(Intent intent)
    {

    return super.onUnbind(intent);

    }



}

报警任务.Java

package com.example.service.task;

import java.util.Calendar;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;

import com.example.service.NotifyService;


public class AlarmTask implements Runnable{
    // The date selected for the alarm
    private final Calendar date;
    // The android system alarm manager
    private final AlarmManager am;
    // Your context to retrieve the alarm manager from
    private final Context context;

    public AlarmTask(Context context, Calendar date) {
        this.context = context;
        this.am = (AlarmManager) context.getSystemService(Context.ALARM_SERVICE);
        this.date = date;
    }

    @Override
    public void run() {
        // Request to start are service when the alarm date is upon us
        // We don't start an activity as we just want to pop up a notification into the system bar not a full activity
        Intent intent = new Intent(context, NotifyService.class);
        intent.putExtra(NotifyService.INTENT_NOTIFY, true);
        PendingIntent pendingIntent = PendingIntent.getService(context, 0, intent, 0);

        // Sets an alarm - note this alarm will be lost if the phone is turned off and on again
        am.set(AlarmManager.RTC_WAKEUP, date.getTimeInMillis(), pendingIntent);



        /*// setRepeating() lets you specify a precise custom interval--in this case,
        // 20 minutes.
        alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
                1000 * 60 * 20, alarmIntent);*/


    }
}

通知服务.Java

package com.example.service;

import com.example.Page1;

import android.R;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

public class NotifyService extends Service {

    /**
     * Class for clients to access
     */
    public class ServiceBinder extends Binder {
        NotifyService getService() {
            return NotifyService.this;
        }
    }

    // Unique id to identify the notification.
    private static final int NOTIFICATION = 123;
    // Name of an intent extra we can use to identify if this service was started to create a notification  
    public static final String INTENT_NOTIFY = "com.blundell.tut.service.INTENT_NOTIFY";
    // The system notification manager
    private NotificationManager mNM;

    @Override
    public void onCreate() {
        Log.i("NotifyService", "onCreate()");
        mNM = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("LocalService", "Received start id " + startId + ": " + intent);

        // If this service was started by out AlarmTask intent then we want to show our notification
        if(intent.getBooleanExtra(INTENT_NOTIFY, false))
            showNotification();

        // We don't care if this service is stopped as we have already delivered our notification
        return START_NOT_STICKY;
    }

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

    // This is the object that receives interactions from clients
    private final IBinder mBinder = new ServiceBinder();

    /**
     * Creates a notification and shows it in the OS drag-down status bar
     */
    @SuppressWarnings("deprecation")
    private void showNotification() {
        // This is the 'title' of the notification
        CharSequence title = " Alert...!";
        // This is the icon to use on the notification
        int icon = R.drawable.ic_dialog_alert;
        // This is the scrolling text of the notification
        CharSequence text = "Alert Today..!";       
        // What time to show on the notification
        long time = System.currentTimeMillis();

        Notification notification = new Notification(icon, text, time);

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

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

        // Clear the notification when it is pressed
        notification.flags |= Notification.FLAG_AUTO_CANCEL;

        // Send the notification to the system.
        mNM.notify(NOTIFICATION, notification);

        // Stop the service when we are finished
        stopSelf();
    }
}

调度客户端.java

package com.example.service;

import java.util.Calendar;

import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.os.IBinder;


public class ScheduleClient {

    // The hook into our service
    private  ScheduleService mBoundService;
    // The context to start the service in
    private Context mContext;
    // A flag if we are connected to the service or not
    private boolean mIsBound;

    public ScheduleClient(Context context) {
        mContext = context;
    }

    /**
     * Call this to connect your activity to your service
     */
    public void doBindService() {
        // Establish a connection with our service
        mContext.bindService(new Intent(mContext, ScheduleService.class), mConnection, Context.BIND_AUTO_CREATE);
        mIsBound = true;
    }


    private ServiceConnection mConnection = new ServiceConnection() {
        public void onServiceConnected(ComponentName className, IBinder service) {
            // This is called when the connection with our service has been established, 
            // giving us the service object we can use to interact with our service.
            mBoundService = ((ScheduleService.ServiceBinder) service).getService();
        }

        public void onServiceDisconnected(ComponentName className) {
            mBoundService = null;
        }
    };

    /**
     * Tell our service to set an alarm for the given date
     * @param c a date to set the notification for
     */
    public void setAlarmForNotification(Calendar c){
        mBoundService.setAlarm(c);
    }

    /**
     * When you have finished with the service call this method to stop it 
     * releasing your connection and resources
     */
    public void doUnbindService() {
        if (mIsBound) {
            // Detach our existing connection.
            mContext.unbindService(mConnection);
            mIsBound = false;
        }
    }
}

调度服务.java

package com.example.service;

import java.util.Calendar;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;
import android.util.Log;

import com.example.service.task.AlarmTask;

public class ScheduleService extends Service {

    /**
     * Class for clients to access
     */
    public class ServiceBinder extends Binder {
        ScheduleService getService() {
            return ScheduleService.this;
        }
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        Log.i("ScheduleService", "Received start id " + startId + ": " + intent);

        // We want this service to continue running until it is explicitly stopped, so return sticky.
        return START_STICKY;
    }

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

    // This is the object that receives interactions from clients. See
    private final IBinder mBinder = new ServiceBinder();

    /**
     * Show an alarm for a certain date when the alarm is called it will pop up a notification
     */
    public void setAlarm(Calendar c) {
        // This starts a new thread to set the alarm
        // You want to push off your tasks onto a new thread to free up the UI to carry on responding
        new AlarmTask(this, c).run();
    }
}
4

2 回答 2

1

您可以使用alarm执行此操作。它可以设置为每天运行一次,您可以在其中检查数据库中的数据并根据需要显示通知。

// Set the alarm to start at approximately 2:00 p.m.
Calendar calendar = Calendar.getInstance();
calendar.setTimeInMillis(System.currentTimeMillis());
calendar.set(Calendar.HOUR_OF_DAY, 14);

alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar.getTimeInMillis(),
        AlarmManager.INTERVAL_DAY, alarmIntent);
于 2015-04-08T08:38:10.910 回答
1

我在我的代码中找到了答案。现在它工作正常每天早上 8 点将发送通知

// 用于通知过程

   Intent myIntent1 = new Intent(sign_in.this,MyNotificationService.class);
                        pendingintent2 = PendingIntent.getService(sign_in.this, 1,myIntent1, 1);
                        AlarmManager alarmManager1 = (AlarmManager) getSystemService(ALARM_SERVICE);
                        Calendar calendar1Notify = Calendar.getInstance();
                        calendar1Notify.setTimeInMillis(System.currentTimeMillis());
                        calendar1Notify.set(Calendar.HOUR_OF_DAY, 8);
                        calendar1Notify.set(Calendar.MINUTE, 00);

                        alarmManager1.set(AlarmManager.RTC_WAKEUP,calendar1Notify.getTimeInMillis(), pendingintent2);

                        long time24h = 24*60*60*1000;

 alarmManager1.setInexactRepeating(AlarmManager.RTC_WAKEUP, calendar1Notify.getTimeInMillis(),time24h,pendingintent2);

在清单中添加权限

 <service android:name="com.example.service.ScheduleService" />
            <service android:name="com.example.service.NotifyService" />
            <service android:name="com.example.MyNotificationService" >

                <intent-filter>
                    <action android:name="android.intent.action.BOOT_COMPLETED" />
                </intent-filter>
            </service>
于 2015-06-22T12:16:00.187 回答