我正在开发 1 个使用警报管理器的应用程序,我的代码显示在下面。实际上,问题是我成功为存储在 sqlite 数据库中的 1 个任务创建了警报(任务、日期和时间由用户设置)。但我没有设置这里有多个警报。我的下一个问题是我想在服务触发警报时显示警报对话框。我已经在警报触发时应用音乐和振动并且也生成通知,但问题是那个锄头停止为我服务的音乐。
一般来说,我的问题是
我想停止音乐通知已被用户取消,直到那时我想播放音乐。我想在触发警报时设置警报对话框
提前谢谢...任何建议都值得赞赏..!! 我的代码显示在下面..
Myservice.java
public class MyService extends Service {
/*---String result;
String oid1,operatorid1;*/
DatabaseHandler db = new DatabaseHandler(this);
public String tableName = db.TABLE_CONTACTS;
public String task_name = db.KEY_TASK;
public String dt = db.KEY_DATETIME;
String tname, dt1;
NotificationManager nm;
static final int uniqueID = 1394885;
ResponseHandler<String> responseHandler;
SQLiteDatabase dbobject;
Cursor c;
Context context, ctx1;
public int flag1 = 0 ,flag2=0;
public MediaPlayer music;
public Vibrator vibrator;
@Override
public IBinder onBind(Intent arg0) {
return null;
}
@Override
public void onCreate() {
super.onCreate();
}
@Override
public void onDestroy() {
super.onDestroy();
}
@Override
public void onStart(Intent intent, int startId) {
final Calendar c1 = Calendar.getInstance();
int hour = c1.get(Calendar.HOUR_OF_DAY);
int minutes = c1.get(Calendar.MINUTE);
int day = c1.get(Calendar.DAY_OF_MONTH);
int month = c1.get(Calendar.MONTH);
int year1 = c1.get(Calendar.YEAR);
String combine = String.valueOf(day).trim() + ":"
+ String.valueOf(month + 1).trim() + ":"
+ String.valueOf(year1).trim() + String.valueOf(hour) + ":"
+ String.valueOf(minutes);
String combine2 = String.valueOf(day).trim() + ":"
+ String.valueOf(month + 1).trim() + ":"
+ String.valueOf(year1).trim() + String.valueOf(hour) + ":"
+ String.valueOf(minutes - 1);
Log.w("trace", "date " + combine);
Log.w("trace", "date " + combine2);
// dbobject=this.openOrCreateDatabase("engdb.db",SQLiteDatabase.CREATE_IF_NECESSARY,null);
MainActivity act = new MainActivity();
dbobject = act.getInstance().openOrCreateDatabase("contactsManager",
SQLiteDatabase.CREATE_IF_NECESSARY, null);
String q = "SELECT task_name,date_time FROM contacts WHERE date_time='"
+ combine + "'";
c = dbobject.rawQuery(q, null);
System.out.print("totle records are :" + c.getCount());
// method1
if (c.getCount() >= 1) {
c.moveToFirst();
try {
for (int i = 0; i < c.getCount(); i++) {
tname = c.getString(c.getColumnIndex("task_name"));
dt1 = c.getString(c.getColumnIndex("date_time"));
c.moveToNext();
}
flag1 = 1;
} catch (Exception e) {
e.printStackTrace();
}
}
Log.w("trace", "alarm has been fired " + c.getCount() + " " +tname
+ " " +dt1);
/*if (flag1 == 1)
{*/
if(c.getCount()>=1)
{
music = MediaPlayer.create(MyService.this, R.raw.mymusic);
music.start();
Log.w("trace", "~~~~~~~~music has been start~~~~~~~ ");
Vibrator vib = (Vibrator) getSystemService(Context.VIBRATOR_SERVICE);
vib.vibrate(500);
// vib.cancel();
Log.w("trace", "******vibrator is going to on ******");
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
nm.cancel(uniqueID);
Intent myintent= new Intent(this,MainActivity.class);
myintent.addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP| Intent.FLAG_ACTIVITY_CLEAR_TOP);
/*
myintent.putExtra("notift", "ticketnotif");
myintent.putExtra("ticketid", str1);*/
PendingIntent pi=PendingIntent.getActivity(this.getApplicationContext( ),0, myintent,PendingIntent.FLAG_UPDATE_CURRENT );
String body=tname;
String title ="Wake up !!";
Notification n= new Notification(R.drawable.img,body,System.currentTimeMillis());
n.flags |= Notification.FLAG_AUTO_CANCEL;
n.setLatestEventInfo(this.getApplicationContext(),title, body,pi);
n.defaults = Notification.DEFAULT_ALL;
nm.notify(uniqueID,n);
}
}
public void setDatabase(SQLiteDatabase db) {
this.dbobject = db;
}
}// end of IF condition
// end of start method
DatabasedHandler.java
public class DatabaseHandler extends SQLiteOpenHelper {
// All Static variables
// Database Version
public static final int DATABASE_VERSION = 1;
// Database Name
public static final String DATABASE_NAME = "contactsManager";
// Contacts table name
public static final String TABLE_CONTACTS = "contacts";
// Contacts Table Columns names
public static final String KEY_ID = "id";
public static final String KEY_TASK = "task_name";
public static final String KEY_DATETIME = "date_time";
Context ctx;
public List<Contact> contactList = new ArrayList<Contact>();
public DatabaseHandler(Context context) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
ctx = context;
}
// Creating Tables
@Override
public void onCreate(SQLiteDatabase db) {
String CREATE_CONTACTS_TABLE = "CREATE TABLE " + TABLE_CONTACTS + "("
+ KEY_ID + " INTEGER PRIMARY KEY," + KEY_TASK + " TEXT,"
+ KEY_DATETIME + " TEXT" + ")";
db.execSQL(CREATE_CONTACTS_TABLE);
}
// Upgrading database
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// Drop older table if existed
db.execSQL("DROP TABLE IF EXISTS " + TABLE_CONTACTS);
// Create tables again
onCreate(db);
}
/**
* All CRUD(Create, Read, Update, Delete) Operations
*/
// Adding new contact
public void addContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TASK, contact.getName()); // Contact Name
values.put(KEY_DATETIME, contact.getPhoneNumber()); // Contact Phone
// Inserting Row
db.insert(TABLE_CONTACTS, null, values);
db.close(); // Closing database connection
}
// Getting single contact
Contact getContact(int id) {
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.query(TABLE_CONTACTS, new String[] { KEY_ID,
KEY_TASK, KEY_DATETIME }, KEY_ID + "=?",
new String[] { String.valueOf(id) }, null, null, null, null);
if (cursor != null)
cursor.moveToFirst();
Contact contact = new Contact(Integer.parseInt(cursor.getString(0)),
cursor.getString(1), cursor.getString(2));
// return contact
return contact;
}
// Getting All Contacts
public List<Contact> getAllContacts() {
try {
List<Contact> contactList = new ArrayList<Contact>();
contactList.clear();
System.out.print("clear array list :");
// Select All Query
String selectQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getWritableDatabase();
Cursor cursor = db.rawQuery(selectQuery, null);
// looping through all rows and adding to list
if (cursor.moveToFirst()) {
do {
Contact contact = new Contact();
contact.setID(Integer.parseInt(cursor.getString(0)));
contact.setName(cursor.getString(1));
contact.setPhoneNumber(cursor.getString(2));
// Adding contact to list
contactList.add(contact);
} while (cursor.moveToNext());
}
cursor.close();
// return contact list
return contactList;
} catch (Exception e) {
// TODO: handle exception
Log.e("all_contact", "" + e);
}
List<Contact> contactList = new ArrayList<Contact>();
return contactList;
}
// Updating single contact
public int updateContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
ContentValues values = new ContentValues();
values.put(KEY_TASK, contact.getName());
values.put(KEY_DATETIME, contact.getPhoneNumber());
// updating row
return db.update(TABLE_CONTACTS, values, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
}
// Deleting single contact
public void deleteContact(Contact contact) {
SQLiteDatabase db = this.getWritableDatabase();
db.delete(TABLE_CONTACTS, KEY_ID + " = ?",
new String[] { String.valueOf(contact.getID()) });
db.close();
}
// Getting numbers of contacts Count
public int getContactsCount() {
String countQuery = "SELECT * FROM " + TABLE_CONTACTS;
SQLiteDatabase db = this.getReadableDatabase();
Cursor cursor = db.rawQuery(countQuery, null);
cursor.close();
// return count
return cursor.getCount();
}
}
Mainactivity.java
public class MainActivity extends Activity implements OnClickListener{
// This is a handle so that we can call methods on our service
// This is the date picker used to select the date for our notification
private DatePicker picker;
private TimePicker timePicker1;
DatePickerDialog mDatePickerDialog;
Calendar c;
Button b1,b2,b3,b4,b5;
TextView t1,t2;
EditText task;
NotificationManager nm;
static final int uniqueID=1394885;
PendingIntent operation;
Context ctx;
private int hour;
private int minutes;
private int day;
private int month;
private int year1;
static final int TIME_DIALOG_ID = 999;
static final int DATE_DIALOG_ID = 1000;
static MainActivity INSTANCE;
DatabaseHandler db;
// DBAdapter2 db2;
SQLiteDatabase dbobject;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
setCurrentTimeOnView();
addListenerOnButton();
INSTANCE=this;
//dbobject=this.openOrCreateDatabase("engdb",SQLiteDatabase.CREATE_IF_NECESSARY,null);//for ddmmyyyy
// dbobject=this.openOrCreateDatabase("engdb2",SQLiteDatabase.CREATE_IF_NECESSARY,null);// for hhmm
task=(EditText)this.findViewById(R.id.txt_task);
b1=(Button)this.findViewById(R.id.btndate);
b2=(Button)this.findViewById(R.id.btntime);
t1=(TextView)this.findViewById(R.id.lbldate);
t2=(TextView)this.findViewById(R.id.lbltime);
b3=(Button)this.findViewById(R.id.selectButton);
// b4=(Button)this.findViewById(R.id.updateButton);
b5=(Button)this.findViewById(R.id.refreshButton);
db= new DatabaseHandler(this);
//for the notification
nm =(NotificationManager)getSystemService(NOTIFICATION_SERVICE);
nm.cancel(uniqueID);
//remove this comments ..................................................................
db.addContact(new Contact("Ravi", "9100000000"));
// for the service
Intent myIntent = new Intent (this,MyService.class);
operation = PendingIntent.getService(this, 0, myIntent, 0);
this.ctx=this;
myIntent.putExtra("operation", operation);
// Service to check every 1 minute
AlarmManager manager =
(AlarmManager)ctx.getSystemService(ALARM_SERVICE);
Calendar futuretime = Calendar.getInstance();
futuretime.setTimeInMillis(System.currentTimeMillis());
futuretime.add(Calendar.MINUTE,1);
manager.setRepeating(AlarmManager.RTC_WAKEUP, futuretime.getTimeInMillis(), 60*1000, operation);
// End Service...
/*// context variable contains your `Context`
AlarmManager mgrAlarm = (AlarmManager) ctx.getSystemService(ALARM_SERVICE);
ArrayList<PendingIntent> intentArray = new ArrayList<PendingIntent>();
for(int i = 0; i < 10; ++i)
{
Intent intent = new Intent(ctx, OnAlarmReceiver.class);
// Loop counter `i` is used as a `requestCode`
PendingIntent pendingIntent = PendingIntent.getBroadcast(ctx, i, intent, 0);
// Single alarms in 1, 2, ..., 10 minutes (in `i` minutes)
mgrAlarm.set(AlarmManager.ELAPSED_REALTIME_WAKEUP,
SystemClock.elapsedRealtime() + 60000 * i,
pendingIntent);
intentArray.add(pendingIntent);
}*/
/*
b4.setOnClickListener(new View.OnClickListener()
{ @Override
public void onClick(View v)
{
Intent myintent = new Intent(MainActivity.this,displaytask_2.class);
MainActivity.this.startActivity(myintent);
}
});
*/
b5.setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minutes = c.get(Calendar.MINUTE);
day = c.get (Calendar.DAY_OF_MONTH);
month = c.get(Calendar.MONTH);
year1 = c.get(Calendar.YEAR);
// set current time into textview
t2.setText(
new StringBuilder().append(pad(hour))
.append(":").append(pad(minutes)));
t1.setText(
new StringBuilder().append(pad(day))
.append(":").append(pad(month + 1)).append(":").append(pad(year1)));
task.setText("");
}
});
//for notification
// mDatePickUp = (Button)findViewById(R.id.btndate);
// db2 = new DBAdapter2(this,"engdb2",null,1);
// db.getWritableDatabase();
// db2.getWritableDatabase();
c = Calendar.getInstance();
// Create a new service client and bind our activity to this service
// Get a reference to our date picker
// picker = (DatePicker) findViewById(R.id.scheduleDatePicker);
}//onCreate() closed
// display current date and time
public void setCurrentTimeOnView() {
t1=(TextView)this.findViewById(R.id.lbldate);
t2=(TextView)this.findViewById(R.id.lbltime);
final Calendar c = Calendar.getInstance();
hour = c.get(Calendar.HOUR_OF_DAY);
minutes = c.get(Calendar.MINUTE);
day = c.get (Calendar.DAY_OF_MONTH);
month = c.get(Calendar.MONTH);
year1 = c.get(Calendar.YEAR);
// set current time into textview
t2.setText(
new StringBuilder().append(pad(hour))
.append(":").append(pad(minutes)));
t1.setText(
new StringBuilder().append(pad(day))
.append(":").append(pad(month + 1)).append(":").append(pad(year1)));
}
public void addListenerOnButton() {
b1 = (Button) findViewById(R.id.btndate);
b1.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showDialog(DATE_DIALOG_ID);
}
});
b2 = (Button) findViewById(R.id.btntime);
b2.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
showDialog(TIME_DIALOG_ID);
}
});
}
@Override
protected Dialog onCreateDialog(int id) {
switch (id) {
case TIME_DIALOG_ID:
// set time picker as current time
return new TimePickerDialog(this,
timePickerListener, hour, minutes,false);
case DATE_DIALOG_ID:
// set time picker as current time
return new DatePickerDialog(this,
datePickerListener, day, month , year1);
}
return null;
}
//++++++++++++++++
//date and time from dialog boxes and save in to sqlite db.......
private DatePickerDialog.OnDateSetListener datePickerListener =
new DatePickerDialog.OnDateSetListener()
{
@Override
public void onDateSet(DatePicker view, int year, int monthOfYear,
int dayOfMonth) {
// TODO Auto-generated method stub
year1 = year;
month = monthOfYear;
day = dayOfMonth;
/*String insertQuery="insert into contact (Day,Month,Year) values('" +
day + "','" + month + "','" +year + "')";
db.insertRecord(insertQuery);
int count = db.countRecord();*/
Toast.makeText(getApplicationContext(), "Date Saved successflly" , 1000).show();
t1.setText(new StringBuilder().append(pad(day))
.append(":").append(pad(month + 1)).append(":").append(pad(year1)));
}
};
private TimePickerDialog.OnTimeSetListener timePickerListener =
new TimePickerDialog.OnTimeSetListener() {
public void onTimeSet(TimePicker view, int selectedHour,
int selectedMinute) {
hour = selectedHour;
minutes = selectedMinute;
/*String insertQuery="insert into contact (Hour,Minutes) values('" +
hour + "','" + minutes + "')";
db.insertRecord(insertQuery);
int count = db.countRecord();*/
Toast.makeText(getApplicationContext(), "Time Saved successflly" , 1000).show();
// set current time into textview
t2.setText(new StringBuilder().append(pad(hour))
.append(":").append(pad(minutes)));
}
};
private static String pad(int c)
{
if (c >= 10)
return String.valueOf(c);
else
return "0" + String.valueOf(c);
}
public void onDateSelectedButtonClick(View v)
{
if(task.getText().toString().length()==0)
{
task.setError("Please Enter your Task ..");
Toast.makeText(getApplicationContext(), " fill up the detail correctly ", 2000).show();
}
else
{
final ProgressDialog myPd_ring=ProgressDialog.show(MainActivity.this, "Please wait", "Alarm has been set...!!", true);
myPd_ring.setCancelable(true);
myPd_ring.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
new Thread() {
public void run() {
try{
sleep(1000);
} catch (Exception e) {
Log.e("tag", e.getMessage());
}
// dismiss the progress dialog
myPd_ring.dismiss();
}
}.start();
String set_date = t1.getText().toString();
String set_time = t2.getText().toString();
String set_task=task.getText().toString();
// substring(startIndex, endIndex);
String d1=set_date.substring(0,2);
String m1=set_date.substring(3,5);
String y1=set_date.substring(6,10);
String h1=set_time.substring(0,2);
String min1=set_time.substring(3,5);
//inser data in to sqlite data base
String dt= String.valueOf(day).trim()+":"+String.valueOf(month+1).trim()+":"+String.valueOf(year1).trim()+String.valueOf(hour)+":"+String.valueOf(minutes);
Toast.makeText(getInstance(), "Combine String "+dt,Toast.LENGTH_LONG).show();
db.addContact(new Contact("Ravi", "9100000000"));
db.addContact(new Contact(set_task, dt));
Toast.makeText(this, " query fired ", 2000).show();
System.out.println(" message" + d1);
int day = Integer.parseInt(d1);
int month = Integer.parseInt(m1);
int year = Integer.parseInt(y1);
int hourOfDay = Integer.parseInt(h1);
int minute = Integer.parseInt(min1);
Calendar c = Calendar.getInstance();
//c.set(year, month, day);
c.set(year, month, day, hourOfDay, minute);
Toast.makeText(this, "Notification set for the date: "+set_date , 1000).show();
Toast.makeText(this, "Notification set for the time: "+set_time , 2000).show();
}
}
MainActivity getInstance()
{
return INSTANCE;
}
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}