给定时间的通知失败

时间:2015-04-14 10:43:02

标签: android notifications bind connect

我正在尝试在我的应用中实现通知功能,该功能会根据特定的用户输入日期设置通知。我试图实现这个网站的方法:http://blog.blundell-apps.com/notification-for-a-user-chosen-time/,只是它不起作用!我试图理解这个问题,但我无法弄清楚如何解决这个问题。在ScheduleClient类中似乎出现了问题,因为LogCat告诉我,当ProductsAdd类打开时,服务绑定,但是当我单击保存按钮时尝试设置警报时,在ClientService的第62行给出了Nullpointerexception。 mBoundService.setAlarm(c)中)。所以服务绑定但不会连接。有人可以告诉我这里我做错了吗?

ProductsAdd class:

public class ProductsAdd extends Activity implements OnClickListener{

Button bSave, bDelete, bCancel;
EditText etName, etAmount , etDate;
Spinner sUnit;
Time today = new Time(Time.getCurrentTimezone());

// 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);
    this.requestWindowFeature(Window.FEATURE_NO_TITLE);
    this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);
    this.setContentView(R.layout.products_add);
    Log.d("WTF", "ProductsAdd.java opened");

    initiate();

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

    // Create an ArrayAdapter using the string array and default spinner layout
    ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.units_array, android.R.layout.simple_spinner_item);
    // Specify the layout to use when the list of choices appears
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);;
    // Apply the adapter to the spinner
    sUnit.setAdapter(adapter);

    // Set product name which is passed from an activity
    Intent getProductFeatures = getIntent();
    String productName = getProductFeatures.getStringExtra("productName");
    String productUnit = getProductFeatures.getStringExtra("productUnit");
    etName.setText(productName);

    //Set spinner to right value:
    int spinnerPosition = adapter.getPosition(productUnit);
    sUnit.setSelection(spinnerPosition);

    today.setToNow();
    String timestamp = today.format("%d-%m-%Y");
    etDate.setText(timestamp);
}

@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
    switch (v.getId()){
        case R.id.bSave:
            Log.d("WTF", "ProductsAdd: Save button pressed");
            try{
                //Get info from edittexts
                String name = etName.getText().toString();
                String amount = etAmount.getText().toString();
                String unit = sUnit.getSelectedItem().toString();
                String date = etDate.getText().toString();
                Log.d("WTF", "Extracted unit from ProductsAdd is: " + unit);

                //Set date alarm

                //Get day, month and year in separate integers
                String sDay = date.substring(0, 2);             
                String sMonth = date.substring(3, 5);
                String sYear = date.substring(6, 10);

                int month = Integer.parseInt(sMonth);
                int day = Integer.parseInt(sDay);
                int year = Integer.parseInt(sYear);

                //Create new calendar to set date chosen
                Calendar c = Calendar.getInstance();
                c.set(day,month,year);

                //Set time to midnight
                c.set(Calendar.HOUR_OF_DAY, 0);
                c.set(Calendar.MINUTE,0);
                c.set(Calendar.SECOND, 0);

                //Ask service to set alarm for date
                scheduleClient.setAlarmForNotification(c);

                //Notify user of alarm
                Toast.makeText(this, "Notification set for: "+ day +"-"+ (month+1), 5);

                //Create new database entry
                DatabaseCustom entry = new DatabaseCustom(ProductsAdd.this);
                entry.open();
                entry.createEntry(name, amount, unit, date);
                entry.close();
                Log.d("WTF", "ProductsAdd: Save product in database successfull");
            } catch(Exception e){
                e.printStackTrace();
                Log.d("WTF", "ProductsAdd error: Failed to save product in database: " + e);
            }

            //Go to product list
            Intent sOpenProducts = new Intent(ProductsAdd.this,
                    Products.class);
            startActivity(sOpenProducts);
            finish();
            break;

        case R.id.bCancel:
            Log.d("WTF", "ProductsAdd: Cancel button pressed");
            Intent cOpenProducts = new Intent(ProductsAdd.this,
                    Products.class);
            startActivity(cOpenProducts);
            finish();
            break;
    }
}

private void initiate(){
    //Link java variables to the corresponding xml elements
    bSave = (Button)findViewById(R.id.bSave);
    bCancel = (Button)findViewById(R.id.bCancel);
    etName = (EditText)findViewById(R.id.etName);
    etAmount = (EditText)findViewById(R.id.etAmount);
    etDate = (EditText)findViewById(R.id.etDate);
    sUnit = (Spinner)findViewById(R.id.sUnit);      

    //Set button OnClickListeners
    bSave.setOnClickListener(this);
    bCancel.setOnClickListener(this);
}
}

ScheduleClient类:

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() {
    Log.d("WTF", "ScheduleClient: service bound");
    // Establish a connection with our service
    mContext.bindService(new Intent(mContext, ScheduleService.class), mConnection, Context.BIND_AUTO_CREATE);
    mIsBound = true;    
}

/**
 * When you attempt to connect to the service, this connection will be called with the result.
 * If we have successfully connected we instantiate our service object so that we can call methods on it.
 */
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.
        Log.d("WTF", "ScheduleClient: service connected");
        mBoundService = ((ScheduleService.ServiceBinder) service).getService();
    }

    public void onServiceDisconnected(ComponentName className) {
        mBoundService = null;
        Log.d("WTF", "ScheduleClient: service disconnected");
    }
};

/**
 * 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);
    Log.d("WTF", "ScheduleClient: alarm set");
}

/**
 * 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;
        Log.d("WTF", "ScheduleClient: service unbound");
    }
}
}

如果需要,我可以添加ScheduleClient类使用的ScheduleService,AlarmTask和NotifyService!

0 个答案:

没有答案