我想創建一個程序,在點擊按鈕30秒後調用一個活動。我有用戶pendingIntent
和BroadcastReciever
爲這個pupose,但沒有發生。我的代碼是:Android意圖廣播
package com.example.wrox;
import java.util.Calendar;
import android.app.Activity;
import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast;
public class AlarmManagerDemo extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final Calendar cal= Calendar.getInstance();
cal.add(Calendar.SECOND, 30);
Button btn= (Button) findViewById(R.id.btn);
Intent intent= new Intent(this,AlarmManagerDemo.class);
intent.putExtra("alarm_message", "Maza aa gaya");
final PendingIntent sender= PendingIntent.getBroadcast(this, 192837, intent, PendingIntent.FLAG_UPDATE_CURRENT);
btn.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
Toast message= Toast.makeText(getApplicationContext(), "This is Starting", Toast.LENGTH_LONG);
message.show();
AlarmManager am= (AlarmManager) getSystemService(ALARM_SERVICE);
am.set(AlarmManager.RTC_WAKEUP, cal.getTimeInMillis(), sender);
}
});
}
}
此活動在按鈕點擊30秒後調用Broadcase接收器。代碼是:
package com.example.wrox;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.widget.Toast;
public class AlarmDemo extends BroadcastReceiver{
@Override
public void onReceive(Context ctx, Intent intent) {
try{
Bundle bundle= intent.getExtras();
String msg= bundle.getString("alarm_message");
Intent newIntent= new Intent(ctx, NewActivity.class);
newIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
ctx.startActivity(newIntent);
}
catch(Exception e)
{
Toast message= Toast.makeText(ctx, "Error occured", Toast.LENGTH_LONG);
message.show();
}
}
}
這BroadcastReciever
呼籲在我所用Toast
顯示一些靜態內容的活動。但按鈕點擊後沒有任何事情發生。請建議我,我在哪裏犯錯? 沒有錯誤和異常生成...