我创建了一个带有通知的广播播放器应用,但是当用户点击通知时,它会重定向到主要活动,但是它会在播放器中创建两次并播放两次
我的通知:
private void initNotification() {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.mukil)
.setContentTitle("My notification")
.setContentText("Hello World!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(0, mBuilder.build());
}
我的主要活动:
public class MainActivity extends Activity{
private ImageView control;
/**
* help to toggle between play and pause.
*/
private boolean playPause;
AudioManager audioManager;
private MediaPlayer mediaPlayer, media;
/**
* remain false till media is not completed, inside OnCompletionListener make it true.
*/
private boolean intialStage = true;
String[] titles = {
"Ippadikku Idhayam",
"Akilam 360",
"Cine Pattarai",
"Palsuvai Thoranam",
"Pesum Noolagam",
"Lollu Cafe",
"Kavi Saagaram",
"Aa muthal Akk",
"Thiraicholai",
"Kathamba Saaral",
"Paarkatha Pakkangal",
"Pagadi Panna Porom",
};
public static final String[] fromtime = new String[]{"10:30","12:30","14:30","16:30","18:30","20:30","22:30","24:30","02:30","04:30","06:30","08:30"};
public static final String[] totime = new String[]{"12:30","14:30","16:30","18:30","20:30","22:30","24:30","02:30","04:30","06:30","08:30","10:30"};
Integer[] images = {
R.drawable.ipadikku_idhayam,
R.drawable.akilam_360,
R.drawable.cine_pattarai,
R.drawable.palsuvai_thoranam,
R.drawable.pesum_noolagam,
R.drawable.lollu_cafe,
R.drawable.kavi_saagaram,
R.drawable.aa_muthal_akk,
R.drawable.thiraicholai,
R.drawable.kathamba_saaral,
R.drawable.paarkatha_pakkangal,
R.drawable.pagadi_panna_porom,
};
ListView list,lvshow;
List<Program> rowItems;
int iImageId;
String sTitle,sFrom,sTo ;
SQLiteDatabase db;
SeekBar seekbar;
ImageView speaker,mute;
AdapAdapter Adapadapter;
UpcomingAdapter upcomingAdapter;
ArrayList<String> iTitle = null;
ArrayList<String> sQuantity = null;
ArrayList<String> sQuantity1 = null;
ArrayList<String> sImageID = null;
private static final int NOTIFICATION_ID = 1;
//private static final String TOAST_TEXT = "Test ads are being shown. "
// + "To show live ads, replace the ad unit ID in res/values/strings.xml with your own ad unit ID.";
private static final String TOAST_TEXT = "Smartah Kelunga Ungal MukilFM";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
AdView adView = (AdView) findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder()
.setRequestAgent("android_studio:ad_template").build();
adView.loadAd(adRequest);
// Toasts the test ad message on the screen. Remove this after defining your own ad unit ID.
Toast.makeText(this, TOAST_TEXT, Toast.LENGTH_LONG).show();
initNotification();
speaker = (ImageView) findViewById(R.id.speaker);
mute = (ImageView) findViewById(R.id.mute);
seekbar = (SeekBar) findViewById(R.id.seekBar1);
audioManager = (AudioManager) getApplicationContext().getSystemService(Context.AUDIO_SERVICE);
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
@Override
public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0);
}
@Override
public void onStartTrackingTouch(SeekBar seekBar) {
}
@Override
public void onStopTrackingTouch(SeekBar seekBar) {
}
/* ImageView upButton = (ImageView) findViewById(R.id.control1);
upButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//To increase media player volume
audioManager.adjustVolume(AudioManager.ADJUST_RAISE, AudioManager.FLAG_PLAY_SOUND);
}
});
ImageView downButton = (ImageView) findViewById(R.id.control2);
downButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
//To decrease media player volume
audioManager.adjustVolume(AudioManager.ADJUST_LOWER, AudioManager.FLAG_PLAY_SOUND);
}
});*/
});
db =openOrCreateDatabase("MukilProgram", Context.MODE_PRIVATE,null);
db.execSQL("CREATE TABLE IF NOT EXISTS proname(ID INTEGER PRIMARY KEY AUTOINCREMENT,ImageID INTEGER,Title TEXT,FromTiming INTEGER,ToTiming INTEGER);");
rowItems = new ArrayList<Program>();
for (int i = 0; i < titles.length; i++) {
Program item = new Program(images[i], titles[i],fromtime[i],totime[i]);
rowItems.add(item);
}
db.execSQL("DELETE FROM proname;");
list = (ListView) findViewById(R.id.list);
lvshow = (ListView) findViewById(R.id.lvshow);
// listView.setVisibility(View.INVISIBLE);
final ProgramAdapter adapter = new ProgramAdapter(this,rowItems, false);
for (int i = 0; i < adapter.getCount(); i++) {
Program rowItem = (Program) adapter.getItem(i);
iImageId = rowItem.getImageId();
sTitle = rowItem.getTitle();
sFrom = rowItem.getFromtime();
sTo = rowItem.getTotime();
db.execSQL("INSERT INTO proname (ImageID,Title,FromTiming,ToTiming) VALUES(" + iImageId + ",'" + sTitle + "','" + sFrom + "','" + sTo + "');");
}
final Cursor cView = db.rawQuery("SELECT * FROM proname WHERE FromTiming <= time('now', 'localtime')\n" + "" +
"AND ToTiming >= time('now', 'localtime')\n" + "ORDER BY FromTiming LIMIT 1", null);
if (cView.getCount() > 0) {
sImageID = new ArrayList<String>();
iTitle = new ArrayList<String>();
sQuantity = new ArrayList<String>();
sQuantity1 = new ArrayList<String>();
while (cView.moveToNext()) {
sImageID.add(cView.getString(1));
iTitle.add(cView.getString(2));
sQuantity.add(cView.getString(3));
sQuantity1.add(cView.getString(4));
Adapadapter = new AdapAdapter(MainActivity.this, sImageID, iTitle, sQuantity, sQuantity1);
lvshow.setAdapter(Adapadapter);
}
}
final Cursor cView1 = db.rawQuery("SELECT * FROM proname WHERE FromTiming > time('now', 'localtime')\n" + "ORDER BY FromTiming LIMIT 3", null);
if (cView1.getCount() > 0) {
sImageID = new ArrayList<String>();
iTitle = new ArrayList<String>();
sQuantity = new ArrayList<String>();
sQuantity1 = new ArrayList<String>();
while (cView1.moveToNext()) {
sImageID.add(cView1.getString(1));
iTitle.add(cView1.getString(2));
sQuantity.add(cView1.getString(3));
sQuantity1.add(cView1.getString(4));
upcomingAdapter = new UpcomingAdapter(MainActivity.this, sImageID, iTitle, sQuantity, sQuantity1);
list.setAdapter(upcomingAdapter);
}
}
media = MediaPlayer.create(this, R.raw.mukil_master_jingle);
control = (ImageView) findViewById(R.id.control);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
control.setOnClickListener(pausePlay);
control.setBackgroundResource(R.drawable.pause);
media.setLooping(true);
if (intialStage) {
new Player()
.execute("http://streaming.shoutcast.com/MUKILFMRADIO");
}
}
@Override
public void onBackPressed() {
//Display alert message when back button has been pressed
ViewDialog alert = new ViewDialog();
alert.showDialog(this, "Are you really want to exit ?");
}
public class ViewDialog {
public void showDialog(Activity activity, String msg) {
final Dialog dialog = new Dialog(activity);
dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
dialog.setCancelable(true);
dialog.setContentView(R.layout.exitdialog);
dialog.show();
TextView text = (TextView) dialog.findViewById(R.id.text_dialog);
text.setText(msg);
Button dialogButton = (Button) dialog.findViewById(R.id.btyes);
Button dialogButton1 = (Button) dialog.findViewById(R.id.btno);
dialogButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
finish();
media.stop();
media.reset();
mediaPlayer.reset();
}
});
dialogButton1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.dismiss();
}
});
}
}
private View.OnClickListener pausePlay = new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
// TODO Auto-generated method stub
if (playPause) {
control.setBackgroundResource(R.drawable.play);
mediaPlayer.stop();
new Player().cancel(true);
media.stop();
media.reset();
mediaPlayer.reset();
if (mediaPlayer.isPlaying())
mediaPlayer.stop();
mediaPlayer.reset();
media.stop();
playPause = false;
} else {
control.setBackgroundResource(R.drawable.pause);
if (intialStage) {
new Player()
.execute("http://streaming.shoutcast.com/MUKILFMRADIO");
} else {
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
}
playPause = true;
}
}
};
/**
* preparing mediaplayer will take sometime to buffer the content so prepare it inside the background thread and starting it on UI thread.
*
* @author piyush
*/
class Player extends AsyncTask<String, Void, Boolean> {
private ProgressDialog progress;
@Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
Boolean prepared;
try {
mediaPlayer.setDataSource(params[0]);
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
@Override
public void onCompletion(MediaPlayer mp) {
// TODO Auto-generated method stub
intialStage = true;
playPause = false;
control.setBackgroundResource(R.drawable.play);
mediaPlayer.stop();
mediaPlayer.reset();
}
});
mediaPlayer.prepare();
mediaPlayer.prepareAsync();
prepared = true;
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
Log.d("IllegarArgument", e.getMessage());
prepared = false;
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
prepared = false;
e.printStackTrace();
}
return prepared;
}
@Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
if (progress.isShowing()) {
progress.cancel();
}
Log.d("Prepared", "//" + result);
mediaPlayer.start();
media.stop();
intialStage = false;
}
public Player() {
progress = new ProgressDialog(MainActivity.this);
}
@Override
protected void onPreExecute() {
// TODO Auto-generated method stub
super.onPreExecute();
this.progress.setMessage("Buffering...");
media.start();
}
}
public void mute1(View v){
speaker.setVisibility(View.VISIBLE);
mute.setVisibility(View.INVISIBLE);
mediaPlayer.setVolume(0,0);
media.setVolume(0,0);
seekbar.setClickable(false);
seekbar.setFocusable(false);
seekbar.setEnabled(false);
}
public void speaker1(View v){
speaker.setVisibility(View.INVISIBLE);
mute.setVisibility(View.VISIBLE);
mediaPlayer.setVolume(1,1);
media.setVolume(1,1);
seekbar.setClickable(true);
seekbar.setFocusable(true);
seekbar.setEnabled(true);
}
private void initNotification() {
NotificationCompat.Builder mBuilder =
new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.mukil)
.setContentTitle("My notification")
.setContentText("Hello World!");
// Creates an explicit intent for an Activity in your app
Intent resultIntent = new Intent(this, MainActivity.class);
// The stack builder object will contain an artificial back stack for the
// started Activity.
// This ensures that navigating backward from the Activity leads out of
// your application to the Home screen.
TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);
// Adds the back stack for the Intent (but not the Intent itself)
stackBuilder.addParentStack(MainActivity.class);
// Adds the Intent that starts the Activity to the top of the stack
stackBuilder.addNextIntent(resultIntent);
PendingIntent resultPendingIntent =
stackBuilder.getPendingIntent(
0,
PendingIntent.FLAG_UPDATE_CURRENT
);
mBuilder.setContentIntent(resultPendingIntent);
NotificationManager mNotificationManager =
(NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
// mId allows you to update the notification later on.
mNotificationManager.notify(0, mBuilder.build());
}
// Cancel Notification
private void cancelNotification() {
String ns = Context.NOTIFICATION_SERVICE;
NotificationManager mNotificationManager = (NotificationManager) getSystemService(ns);
mNotificationManager.cancel(NOTIFICATION_ID);
}
}