2013-12-05 3 views
0

В моей программе уведомление должно быть активировано всякий раз, когда приложение запущено или нет. Должен ли я использовать метод уведомления в onCreate()? мое уведомление - это как тревога. Пожалуйста, проверьте alittle.Отображать уведомление, когда приложение запущено или нет

public String getCurrentTime(){ 
    Calendar c= Calendar.getInstance(); 
    SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss "); 
    String strDate = sdf.format(c.getTime()); 
    return strDate; 
} 

Это системное время.

public void jsonen() 
{ 
    int status=2; 
    JSONObject json=null; 

    String teamID=null; 
    ArrayList<NameValuePair> postParameters = new ArrayList<NameValuePair>(); 
    //postParameters.add(new BasicNameValuePair("email",edit_txt_EmailAddress.getText().toString()));//// define the parameter 
    postParameters.add(new BasicNameValuePair("userID","396797666")); 

    StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder() 
     .detectDiskReads().detectDiskWrites().detectNetwork() // StrictMode is most commonly used to catch accidental disk or network access on the application's main thread 
     .penaltyLog().build()); 

    ArrayList<NameValuePair> pp = new ArrayList<NameValuePair>(); 

    String response = null; 
    try { 
      response=CustomHttpClient.executeHttpPost("http://10.0.2.2/football365/notification.php", postParameters); 
     // json=new JSONObject(response); 
     // teamID=json.getString("teamID"); 
     // Log.i("Team ID",teamID+""); 
     } 
    catch (Exception e) { 

     e.printStackTrace(); 
    } 


    JSONObject jsonobj = null; 
    String alerttime=null; 
    String beforematch=null; 
    JSONArray jArray = null; 
    String starttime=null; 
try{ 

    jsonobj = new JSONObject (response); 
    jArray=jsonobj.getJSONArray("notifications"); 

    Log.i("Current Time",jArray+""); 
    Log.i("Current Time",getCurrentTime()); 

    for(int i=0;i<jArray.length();i++){ 

     jsonobj=jArray.getJSONObject(i); 

     alerttime=jsonobj.getString("alert"); 
     starttime=jsonobj.getString("startTime"); 
     beforematch=jsonobj.getString("beforeMatchTime"); 

     if(alerttime==getCurrentTime()){ 

       Notification(starttime); 
       Log.i("Wintal", "wint"); 
     } 
    } 
    //teamStatus=jsonobj.getString("teamStatus"); 

} 
catch(JSONException e){ 
     Log.e("log_tag", "Error parsing data "+e.toString()); 
} 



Log.i("RESULT", jsonobj+""); 
Log.i("time", alerttime+""); 
Log.i("before Match",beforematch+""); 
} 

Это проверка.

public void Notification(String s) 
{ 

     String ns = Context.NOTIFICATION_SERVICE; 

     NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns); 

     int icon = R.drawable.notification_icon; 
     CharSequence tickerText = "Ready for Play time."; // ticker-text 
     long when = System.currentTimeMillis(); 
     Context context = getApplicationContext(); 
     CharSequence contentTitle = "Play Time"; 
     CharSequence contentText = "Your match is at "+s; 
     Intent notificationIntent = new Intent(this,ScheldueNotification .class); 
     PendingIntent contentIntent = PendingIntent.getActivity(this, 0, notificationIntent, 0); 
     Notification notification = new Notification(icon, tickerText, when); 
     notification.setLatestEventInfo(context, contentTitle, contentText, contentIntent); 

     // and this 
     final int HELLO_ID = 1; 
     mNotificationManager.notify(HELLO_ID, notification); 

     notification.flags=Notification.FLAG_AUTO_CANCEL; 
} 

Это часть с уведомлением. Пожалуйста, помогите.

+0

Используйте диспетчер будильника и установите локальное уведомление с некоторым временем его запуска, независимо от того, работает приложение или нет. http://justcallmebrian.com/2010/04/27/using-alarmmanager-to-schedule-activities-on-android/ –

ответ

0

Используйте AlarmManger для уведомления через определенные промежутки времени.

Проверь это:

Alaram Manager Description и Alarm Manager Example

Надеется, что это помогает.

+0

Это не так, например. Давайте будем игроком команды. Я должен тренироваться в 2:00, и уведомление должно быть показано в 1:00, поэтому системное время прибывает в 1:00, и уведомление должно быть активировано. Наверное, у тебя это получилось. – vcav

+0

Alarm Manger точно делает это. Проверьте ссылку, которую я вам предоставил. –

0

Используйте AlarmManager с BroadcastReceiver. С помощью запуска диспетчера аварийных сигналов приемник и внутри вашего класса приемника имеют свой метод уведомления. BroadcastReceiver позволяет запускать процессы в фоновом режиме, работает ли приложение или нет.

Смежные вопросы