2013-08-11 4 views
1

Я новичок в программировании для Android. У меня возникла проблема с уведомлением моего приложения о том, что после перезагрузки он исчезает!Уведомление об андроиде исчезает после перезагрузки

мое приложение касается автоматического переадресации смс, а также может быть включено через sms. Я хочу, чтобы уведомление отображалось, когда приложение включено. У меня есть 2 проблемы с извещением:

1.отчета исчезновения после перезагрузки!

2. уведомление не появляется, когда приложение включено через смс!

вот мои коды:

SmsForwardConfig.java

public class SmsForwarderConfig extends Activity { 
public static final String KEY_IS_ENABLED = "SmsForwarderConfig_enabled"; 
public static final String KEY_IS_AUTO = "SmsForwarderConfig_auto"; 
public static final String KEY_SMS_NO = "SmsForwarderConfig_number"; 
public static final String APP_SET_NAME = "SmsForwarderConfig_g_cfg"; 
public static final String PASSWORD = "SmsForwarderConfig_pass"; 


@Override 
public void onCreate(Bundle savedInstanceState) { 
super.onCreate(savedInstanceState); 
setContentView(R.layout.main); 


final SharedPreferences mSettings = getSharedPreferences(APP_SET_NAME, MODE_PRIVATE); 
final Button ok = (Button) findViewById(R.id.ok); 
final TextView mTxtForwardTo = (TextView) findViewById(R.id.editText1); 
final TextView password = (TextView) findViewById(R.id.editText2); 
final TextView tx1 = (TextView) findViewById(R.id.textView1); 
final TextView tx2 = (TextView) findViewById(R.id.textView2); 
final TextView tx3 = (TextView) findViewById(R.id.textView3); 
final TextView tx4 = (TextView) findViewById(R.id.textView4); 
final CheckBox chk = (CheckBox) findViewById(R.id.checkBox1); 
final CheckBox chk2 = (CheckBox) findViewById(R.id.checkBox2); 
final ImageButton imgr = (ImageButton) findViewById(R.id.imgbtnr); 
final ImageButton support = (ImageButton) findViewById(R.id.support); 

Typeface font = Typeface.createFromAsset(getAssets(), "font.ttf"); 
ok.setTypeface(font); 
mTxtForwardTo.setTypeface(font); 
password.setTypeface(font); 
tx1.setTypeface(font); 
tx2.setTypeface(font); 
tx3.setTypeface(font); 
tx4.setTypeface(font); 

final NotificationManager nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE); 
final Notification notify = new Notification(R.drawable.ic_launcher, "sms divert is enabled!", System.currentTimeMillis()); 
Context context = SmsForwarderConfig.this; 
CharSequence title = "sms divert!"; 
CharSequence details = "sms divert is enabled!"; 
Intent intent = new Intent (context, SmsForwarderConfig.class); 
PendingIntent pending = PendingIntent.getActivity(context, 0, intent, 0); 
notify.setLatestEventInfo(context, title, details, pending); 
notify.flags = Notification.FLAG_ONGOING_EVENT; 



//set pre entered values 
if (mSettings.getBoolean(KEY_IS_ENABLED, false)) { 

    chk.setChecked(true); 


} else { 

    chk.setChecked(false); 
} 

if (mSettings.getBoolean(KEY_IS_AUTO, false)) { 
    chk2.setChecked(true); 
} else { 
    chk2.setChecked(false); 
} 
mTxtForwardTo.setText(mSettings.getString(KEY_SMS_NO, "")); 
password.setText(mSettings.getString(PASSWORD, "")); 

//prepare listener 
ok.setOnClickListener(new View.OnClickListener() { 
    public void onClick(View v) { 

     final String telNumber = mTxtForwardTo.getText().toString(); 
     final boolean isEnabled = chk.isChecked(); 
     final boolean remoteControl = chk2.isChecked(); 

     if (chk.isChecked()) { 
      nm.notify(0, notify); 
     } else { 
      nm.cancel(0); 
     } 

     SharedPreferences.Editor editor = mSettings.edit(); 
     editor.putBoolean(KEY_IS_ENABLED, isEnabled); 
     editor.putString(KEY_SMS_NO, telNumber); 
     editor.putBoolean(KEY_IS_AUTO, remoteControl); 
     editor.putString(PASSWORD, password.getText().toString()); 
     editor.commit(); 

    } 
}); 

    imgr.setOnClickListener(new OnClickListener() { 

    @Override 
    public void onClick(View arg0) { 
     Intent link = new Intent(Intent.ACTION_VIEW); 
     link.setData(Uri.parse("bazaar://search?q=Ratin&c=apps")); 
     startActivity(link); 
    } 
}); 

    support.setOnClickListener(new OnClickListener() { 

     @Override 
     public void onClick(View arg0) { 
      startActivity(new Intent(SmsForwarderConfig.this, SupportActivity.class)); 

     } 
    }); 

} 

и SmsReceiver.java

public class SmsReceiver extends BroadcastReceiver { 


@Override 
public void onReceive(Context context, Intent intent) { 

final SharedPreferences settings = context.getSharedPreferences(SmsForwarderConfig.APP_SET_NAME, Context.MODE_PRIVATE); 
boolean isActive = settings.getBoolean(SmsForwarderConfig.KEY_IS_ENABLED, false); 
final boolean isRemoteEnabled = settings.getBoolean(SmsForwarderConfig.KEY_IS_AUTO, false); 
final String telNumber = settings.getString(SmsForwarderConfig.KEY_SMS_NO, ""); 

searchRemoteReq: 
if (isRemoteEnabled && !isActive) { 
    String password = settings.getString(SmsForwarderConfig.PASSWORD, ""); 
    if (password.trim().length() > 0) { 
     Bundle bundle = intent.getExtras(); 
     SmsMessage[] msgs = null; 
     if (bundle != null) { 
      //---retrieve the SMS message received--- 
      Object[] pdus = (Object[]) bundle.get("pdus"); 
      msgs = new SmsMessage[pdus.length]; 
      for (int i = 0; i < msgs.length; i++) { 
       msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); 
       String message = msgs[i].getMessageBody().toString(); 
       if (message.contains(password)) { 
        isActive = true; 
        SharedPreferences.Editor editor = settings.edit(); 
        editor.putBoolean(SmsForwarderConfig.KEY_IS_ENABLED, true); 
        editor.commit(); 
        break searchRemoteReq; 
       } 
      } 
     } 

    } 
} 

if (isActive && telNumber != null && telNumber.length() > 0) { 
    Log.v("SmsReceiver", "Is active: " + isActive); 
    Log.v("SmsReceiver", "Tel Number: " + telNumber); 
    sendSMS(context, intent, telNumber); 
} 
} 

private void sendSMS(Context context, Intent intent, String phoneNumber) { 
//---get the SMS message passed in--- 
Bundle bundle = intent.getExtras(); 
SmsMessage[] msgs = null; 
if (bundle != null) { 
    //---retrieve the SMS message received--- 
    Object[] pdus = (Object[]) bundle.get("pdus"); 
    msgs = new SmsMessage[pdus.length]; 
    for (int i = 0; i < msgs.length; i++) { 
     msgs[i] = SmsMessage.createFromPdu((byte[]) pdus[i]); 
     SmsManager sms = SmsManager.getDefault(); 
     String from = msgs[i].getDisplayOriginatingAddress(); 
     String message = msgs[i].getMessageBody().toString(); 
     String all = from + ":" + message; 
     Log.v("SmsReceiver", "SMS Message: " + all); 
     sms.sendTextMessage(phoneNumber, null, all, null, null); 
    } 

} 
} 
} 
+1

Сначала напишите «Сервис», переместите туда свою логику уведомлений. А затем напишите «BroadcastReceiver», который будет прослушивать действие «android.intent.action.BOOT_COMPLETED». Начните свое обслуживание, когда получите это действие. – Milan

ответ

2

Вам нужно создать фоновое задание (андроидом обслуживание) который будет запускаться после перезагрузки и будет искать сохраненные уведомления и показывать их. ваше приложение будет убито после перезагрузки и, следовательно, Android не сможет связаться с ним и покажет оповещения.

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