How to unlock the phone on incoming call? - android

I am making a project in which i am using a transparent screen with a button on incoming call screen. It is working fine if the phone is unlock but if the phone is in lock condition and the call arrive on phone than firstly i have to unlock the phone
The code that i used is...
public class Recevo extends BroadcastReceiver {
#Override
public void onReceive(Context context, Intent intent) {
// TODO Auto-generated method stub
TelephonyManager tm = (TelephonyManager)context.getSystemService(Service.TELEPHONY_SERVICE);
Intent i= new Intent(context,Servo.class);
int state = tm.getCallState();
if(state==TelephonyManager.CALL_STATE_RINGING){
String number=intent.getStringExtra("incoming_number");
Log.i("State", "Call is Ringing");
context.startService(i);
}else if (state==TelephonyManager.CALL_STATE_IDLE) {
Log.i("State", "Idle State");
Toast.makeText(context, "Call is Idle", Toast.LENGTH_SHORT).show();
context.stopService(i);
} else if (state==TelephonyManager.CALL_STATE_OFFHOOK) {
//Log.i("State", "Call is Ringing");
//Toast.makeText(context, "Phone is Ringing", Toast.LENGTH_SHORT).show();
}
}
}
public class Servo extends Service{
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
//Toast.makeText(getApplicationContext(), "in servo", Toast.LENGTH_SHORT).show();
Thread t=new Thread(new Times());
t.start();
}
public class Times extends Thread{
#Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(5000);
Intent i = new Intent(Servo.this,Blank.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
public class Blank extends Activity implements OnClickListener{
Button b;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.blank);
b=(Button)findViewById(R.id.button1);
b.setOnClickListener(this);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Button Clicked", Toast.LENGTH_SHORT).show();
AudioManager audio1 = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//audio1.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
audio1.setStreamMute(AudioManager.STREAM_MUSIC, true);
finish();
}
Update 1
public class CallerService extends Service implements
TextToSpeech.OnInitListener {
String number;
boolean a;
private TextToSpeech tts;
int callState;
TelephonyManager mgr;
#Override
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public void onCreate() {
// TODO Auto-generated method stub
super.onCreate();
tts = new TextToSpeech(this, this);
mgr = (TelephonyManager) getSystemService(Context.TELEPHONY_SERVICE);
AudioManager audio1 = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
int maxVolume = audio1.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
float percent = 2.0f;
int seventyVolume = (int) (maxVolume*percent);
audio1.setStreamVolume(AudioManager.STREAM_MUSIC, seventyVolume, 0);
Thread t=new Thread(new Times());
t.start();
}
public class Times extends Thread{
#Override
public void run() {
// TODO Auto-generated method stub
try {
Thread.sleep(5000);
Intent i = new Intent(CallerService.this,Blank.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
#Override
#Deprecated
public void onStart(Intent intent, int startId) {
// TODO Auto-generated method stub
super.onStart(intent, startId);
number = intent.getStringExtra("phnumber");
//fetchContacts();
}
#Override
public void onInit(int status) {
// TODO Auto-generated method stub
if (status != TextToSpeech.ERROR)
{
tts.setLanguage(Locale.ENGLISH);
fetchContacts();
}
}
#Override
public void onDestroy() {
// TODO Auto-generated method stub
if (tts != null) {
tts.stop();
tts.shutdown();
}
super.onDestroy();
}
public void fetchContacts() {
/* tts.speak("Hello everyone", TextToSpeech.QUEUE_FLUSH,
null);*/
String phoneNumber = null;
Uri CONTENT_URI = ContactsContract.Contacts.CONTENT_URI;
String _ID = ContactsContract.Contacts._ID;
String DISPLAY_NAME = ContactsContract.Contacts.DISPLAY_NAME;
String HAS_PHONE_NUMBER = ContactsContract.Contacts.HAS_PHONE_NUMBER;
Uri PhoneCONTENT_URI = ContactsContract.CommonDataKinds.Phone.CONTENT_URI;
String Phone_CONTACT_ID = ContactsContract.CommonDataKinds.Phone.CONTACT_ID;
String NUMBER = ContactsContract.CommonDataKinds.Phone.NUMBER;
ContentResolver contentResolver = getContentResolver();
Cursor cursor = contentResolver.query(CONTENT_URI, null, null, null,
null);
if (cursor.getCount() > 0) {
while (cursor.moveToNext()) {
String contact_id = cursor
.getString(cursor.getColumnIndex(_ID));
int hasPhoneNumber = Integer.parseInt(cursor.getString(cursor
.getColumnIndex(HAS_PHONE_NUMBER)));
if (hasPhoneNumber > 0) {
Cursor phoneCursor = contentResolver.query(
PhoneCONTENT_URI, null, Phone_CONTACT_ID + " = ?",
new String[] { contact_id }, null);
while (phoneCursor.moveToNext()) {
phoneNumber = phoneCursor.getString(phoneCursor
.getColumnIndex(NUMBER));
a = PhoneNumberUtils.compare(number,
phoneNumber);
callState= mgr.getCallState();
/*if(!a){
if(callState==TelephonyManager.CALL_STATE_RINGING) {
for (int i = 0; i < 15; i++) {
callState = mgr.getCallState();
if (callState==TelephonyManager.CALL_STATE_IDLE){
tts.stop();
tts.shutdown();
break;
}else if (callState==TelephonyManager.CALL_STATE_OFFHOOK){
tts.stop();
tts.shutdown();
break;
}
tts.speak("Unknown Calling", TextToSpeech.QUEUE_FLUSH,
null);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
else */if (a) {
String contname = phoneCursor.getString(phoneCursor
.getColumnIndex(DISPLAY_NAME));
if (!contname.equals(null)) {
Toast.makeText(getApplicationContext(),
contname, Toast.LENGTH_SHORT).show();
if(callState==TelephonyManager.CALL_STATE_RINGING) {
for (int i = 0; i < 15; i++) {
callState = mgr.getCallState();
if (callState==TelephonyManager.CALL_STATE_IDLE){
tts.stop();
tts.shutdown();
break;
}else if (callState==TelephonyManager.CALL_STATE_OFFHOOK){
tts.stop();
tts.shutdown();
break;
}
tts.speak(contname + " Calling", TextToSpeech.QUEUE_FLUSH,
null);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
phoneCursor.close();
}
}
}
if(!a){
if(callState==TelephonyManager.CALL_STATE_RINGING) {
for (int i = 0; i < 15; i++) {
callState = mgr.getCallState();
if (callState==TelephonyManager.CALL_STATE_IDLE){
tts.stop();
tts.shutdown();
break;
}else if (callState==TelephonyManager.CALL_STATE_OFFHOOK){
tts.stop();
tts.shutdown();
break;
}
tts.speak("Unknown Calling", TextToSpeech.QUEUE_FLUSH,
null);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
}
in the Blank class
public class Blank extends Activity implements OnClickListener{
Button b;
Window window;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.blank);
b=(Button)findViewById(R.id.button1);
b.setOnClickListener(this);
window = this.getWindow();
// use Window.addFlags() to add the flags in WindowManager.LayoutParams
window.addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD);
window.addFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.addFlags(LayoutParams.FLAG_TURN_SCREEN_ON);
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getApplicationContext(), "Button Clicked", Toast.LENGTH_SHORT).show();
AudioManager audio1 = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
//audio1.getStreamMaxVolume(AudioManager.STREAM_MUSIC);
audio1.setStreamMute(AudioManager.STREAM_MUSIC, true);
finish();
}
}

Try following:
private Window window;
#Override
protected void onResume() {
super.onResume();
// get the window of your activity
window = this.getWindow();
// use Window.addFlags() to add the flags in WindowManager.LayoutParams
window.addFlags(LayoutParams.FLAG_DISMISS_KEYGUARD);
window.addFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED);
window.addFlags(LayoutParams.FLAG_TURN_SCREEN_ON);
}
Note: You can put this code in onCreate() as well, but I would suggest to put it in onResume().
FLAG_DISMISS_KEYGUARD - when set the window will cause the keyguard to be dismissed, only if it is not a secure lock keyguard.
FLAG_SHOW_WHEN_LOCKED - special flag to let windows be shown when the screen is locked
FLAG_TURN_SCREEN_ON - when set as a window is being added or made visible, once the window has been shown then the system will poke the power manager's user activity (as if the user had woken up the device) to turn the screen on.

Related

How to stop media player start and stop media player properly in android?

Hi am trying to stream online radio while opening my app when buffering first time it runs fine while i close the app and then start again the app it plays from where the player last closed and then stopped after it ends and i have to startup manually to stream the url for current level of radio
my coding:
public class MainActivity extends AppCompatActivity {
DrawerLayout drawer;
ImageView list_activity_check;
ImageView share,speaker,mute, control;
DrawerListAdapter drawerListAdapter;
ListView listview_nav;
private SmallBang mSmallBang;
String [] Items={"Program Lists","Rate app"} ;
int [] images={R.drawable.pro_logo,
R.drawable.rate_icon} ;
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 AM","12:30 PM","14:30 PM","16:30 PM","18:30 PM","20:30 PM","22:30 PM","00:30 AM","02:30 AM","04:30 AM","06:30 AM","08:30 AM"};
public static final String[] totime = new String[]{"12:30 PM","14:30 PM","16:30 PM","18:30 PM","20:30 PM","22:30 PM","00:30 AM","02:30 AM","04:30 AM","06:30 AM","08:30 AM","10:30 AM"};
Integer[] images0 = {
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,
};
//************* Current Show ***************//
ListView list,lvshow;
List<Program> rowItems;
int iImageId;
String sTitle,sFrom,sTo ;
SQLiteDatabase db;
ImageView music;
int media1;
int intValue1;
AdapAdapter Adapadapter;
ArrayList<String> iTitle = null;
ArrayList<String> sQuantity = null;
ArrayList<String> sQuantity1 = null;
ArrayList<String> sImageID = null;
//***************************************//
SeekBar seekbar;
AudioManager audioManager;
MediaPlayer media, mediaPlayer;
boolean playPause = false;
boolean intialStage = true;
int intvalue ;
ImageView timer;
private static final int NOTIFICATION_ID = 1;
String URL = "http://streaming.shoutcast.com/MUKILFMRADIO";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
addNotification();
mSmallBang = SmallBang.attach2Window(this);
list_activity_check = (ImageView) findViewById(R.id.list_view);
share = (ImageView) findViewById(R.id.share);
speaker = (ImageView) findViewById(R.id.speaker);
mute = (ImageView) findViewById(R.id.mute);
control = (ImageView) findViewById(R.id.play);
timer = (ImageView) findViewById(R.id.timer);
//************ Current show ************//
db = this.openOrCreateDatabase("MukilApp",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(images0[i], titles[i],fromtime[i],totime[i]);
rowItems.add(item);
}
db.execSQL("DELETE FROM proname;");
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", 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(this, sImageID, iTitle, sQuantity, sQuantity1);
lvshow.setAdapter(Adapadapter);
}
}
//*************************************//
timer.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
Intent slideactivity = new Intent(MainActivity.this, Timer_Activity.class);
Bundle bndlanimation =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animate1, R.anim.animate2).toBundle();
// startActivity(slideactivity, bndlanimation);
startActivityForResult(slideactivity, 1001,bndlanimation);
// finish();
}
});
}
});
media = MediaPlayer.create(this,R.raw.mukil_master_jingle);
media.start();
media.setLooping(true);
mediaPlayer = new MediaPlayer();
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
if (intialStage) {
new Player()
.execute(URL);
}
intvalue = mediaPlayer.getAudioSessionId();
control.setBackgroundResource(R.drawable.pause);
control.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (playPause == false) {
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 = true;
} else {
control.setBackgroundResource(R.drawable.pause);
if (intialStage) {
new Player()
.execute(URL);
} else {
if (!mediaPlayer.isPlaying())
mediaPlayer.start();
}
playPause = false;
}
}
});
speaker.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
speaker.setVisibility(View.INVISIBLE);
mute.setVisibility(View.VISIBLE);
media.setVolume(0, 0);
mediaPlayer.setVolume(0, 0);
speaker.setImageResource(R.drawable.speaker);
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
}
});
}
});
mute.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
speaker.setVisibility(View.VISIBLE);
mute.setVisibility(View.INVISIBLE);
media.setVolume(1, 1);
mediaPlayer.setVolume(1, 1);
}
});
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
if (getSupportActionBar() != null) {
getSupportActionBar().setDisplayShowTitleEnabled(false); // hide built-in Title
}
try {
seekbar = (SeekBar) findViewById(R.id.seekbar1);
audioManager = (AudioManager) getSystemService(Context.AUDIO_SERVICE);
seekbar.setMax(audioManager
.getStreamMaxVolume(AudioManager.STREAM_MUSIC));
seekbar.setProgress(audioManager
.getStreamVolume(AudioManager.STREAM_MUSIC));
seekbar.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
#Override
public void onStopTrackingTouch(SeekBar arg0) {
}
#Override
public void onStartTrackingTouch(SeekBar arg0) {
}
#Override
public void onProgressChanged(SeekBar arg0, int progress, boolean arg2) {
audioManager.setStreamVolume(AudioManager.STREAM_MUSIC,
progress, 0);
}
});
} catch (Exception e) {
e.printStackTrace();
}
listview_nav = (ListView) findViewById(R.id.listview_nav);
drawer = (DrawerLayout) findViewById(R.id.drawer_layout);
ActionBarDrawerToggle toggle = new ActionBarDrawerToggle(
this, drawer, toolbar, R.string.navigation_drawer_open, R.string.navigation_drawer_close);
drawer.setDrawerListener(toggle);
toggle.syncState();
drawerListAdapter = new DrawerListAdapter(MainActivity.this, Items, images);
listview_nav.setAdapter(drawerListAdapter);
listview_nav.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
if(position == 0){
Intent in = new Intent(MainActivity.this,ShowList_Activity.class);
startActivity(in);
}else if(position == 1){
}
}
});
list_activity_check.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
list_activity_check.setImageResource(R.drawable.playlist);
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
Intent slideactivity = new Intent(MainActivity.this, EqualizerActivity.class);
slideactivity.putExtra("sessionvalue", intvalue);
Bundle bndlanimation =
ActivityOptions.makeCustomAnimation(getApplicationContext(), R.anim.animate1, R.anim.animate2).toBundle();
startActivity(slideactivity, bndlanimation);
}
});
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
share.setImageResource(R.drawable.share_icon);
mSmallBang.bang(v);
mSmallBang.setmListener(new SmallBangListener() {
#Override
public void onAnimationStart() {
}
#Override
public void onAnimationEnd() {
}
});
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT,
"https://play.google.com/store/apps/details?id=com.digitamatix.mukilfm");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "https://play.google.com/store/apps/details?id=com.digitamatix.mukilfm" + " Mukil FM shareApp");
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
});
PhoneStateListener phoneStateListener = new PhoneStateListener() {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
if (state == TelephonyManager.CALL_STATE_RINGING) {
//INCOMING call
//do all necessary action to pause the audio
if(mediaPlayer!=null){//check mp
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
}
if(media!=null){//check mp
if(media.isPlaying()){
media.pause();
}
}
} else if(state == TelephonyManager.CALL_STATE_IDLE) {
//Not IN CALL
//do anything if the phone-state is idle
if(mediaPlayer == null){//check mp
if(!mediaPlayer.isPlaying()) {
mediaPlayer.start();
}
}
if(media==null){//check mp
if(!media.isPlaying()){
media.start();
}
}
} else if(state == TelephonyManager.CALL_STATE_OFFHOOK) {
//A call is dialing, active or on hold
//do all necessary action to pause the audio
//do something here
if(mediaPlayer!=null){//check mp
if(mediaPlayer.isPlaying()){
mediaPlayer.pause();
}
}
if(media!=null){//check mp
if(media.isPlaying()){
media.pause();
}
}
}
super.onCallStateChanged(state, incomingNumber);
}
};//end PhoneStateListener
TelephonyManager mgr = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
if(mgr != null) {
mgr.listen(phoneStateListener, PhoneStateListener.LISTEN_CALL_STATE);
}
}
private void addNotification() {
NotificationCompat.Builder builder =
(NotificationCompat.Builder) new NotificationCompat.Builder(this)
.setSmallIcon(R.drawable.mukil)
.setContentTitle("MUKIL FM")
.setContentText("Smartah Kelunga Ungal MukilFm");
// Add as notification
NotificationManager manager = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
manager.notify(0, builder.build());
}
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();
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 1001) {
String result=data.getStringExtra("result");
if(result.equalsIgnoreCase("STOP")){
onStop();
finish();
}else if(result.equalsIgnoreCase("Do Nothing")){
Toast.makeText(this, "Timer is not set", Toast.LENGTH_SHORT).show();
}
}
}
#Override
public void onStop() {
super.onStop();
if(media != null){
// media.stop(); //Stops playback after playback has been stopped or paused
media.release(); //Releases resources associated with this MediaPlayer object
media = null;
}
if(mediaPlayer!= null){
// mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer= null;
}
}
public void onBackPressed() {
if (drawer.isDrawerOpen(GravityCompat.START)) {
drawer.closeDrawer(GravityCompat.START);
} else {
AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(
MainActivity.this);
// set title
alertDialogBuilder.setTitle("Exit");
// set dialog message
alertDialogBuilder
.setMessage("Do you really want to exit?")
.setCancelable(false)
.setPositiveButton("Yes",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
MainActivity.this.finish();
mediaPlayer.release();
media.release();
}
})
.setNegativeButton("No",new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,int id) {
dialog.cancel();
}
});
// create alert dialog
AlertDialog alertDialog = alertDialogBuilder.create();
// show it
alertDialog.show();
}
// super.onBackPressed();
}
}
please help me in fixing this issues..
Thank you in advance..
In your onStop() of your activity stop and release the media player.
Place the below code in your onStop():
#Override
public void onStop() {
super.onStop();
if(media != null){
media.stop(); //Stops playback after playback has been stopped or paused
media.release(); //Releases resources associated with this MediaPlayer object
media = null;
}
if(mediaPlayer!= null){
mediaPlayer.stop();
mediaPlayer.release();
mediaPlayer= null;
}
}
This is the proper way to stop media player.
Hope it helps:)

Media Controllers are not visible on the top of the surface view

Media Controllers are not visible on the top of the surface view .I have tried almost all the options
Surface View should disappear every time an channel is clicked from the list.
Then the Flip animation for the background Images takes place.
Then the Surface should be visible.
The above three steps happen for every click.
Every time i have tried doing the below give things. Surface View would disappear the first time But appear while the flip animation is happening and the n Never disppears
Set Visibility(inivisible ,gone )- nothing works
Changing the size of the surface view
BringToFront paired with invalidate()
Finally i tried
mSurface .setZOrderOnTop(true);
mHolder.setPixelFormat(Transparent)
That Worked But now the Problem is My Media Controllers that were attached to FrameLayout are not getting displayedand the Reason is ofcourse
mSurface.setZOrderOnTop(true);
Can Any body please please please to power of infinity tell me what should i do to get the media controllers to show up or get the whole Scenario worked out .
I am quite new to media player and surface views.
Please Help
MainActivity:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
initImageLoader(getApplicationContext());
setContentView(R.layout.user_main_screen);
ActionBar actionBar = getActionBar();
actionBar.show();
// // get action bar
// ActionBar actionBar = getActionBar();
//
// // Enabling Up / Back navigation
// actionBar.setDisplayHomeAsUpEnabled(true);
SetUpVariables();
getDataFromSignIn();
Categories categoriesList = new Categories(UserMainScreen.this);
try {
resultFromCategoriesAsyncTask= categoriesList.execute(AccessToken).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Language LanguagesList = new Language(UserMainScreen.this);
try {
resultFromLanguagesAsyncTask= LanguagesList.execute(AccessToken).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
MainScreen mainScreen = new MainScreen(UserMainScreen.this);
try {
resultFromAsyncTask= mainScreen.execute(AccessToken).get();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
getChannelInfo(resultFromAsyncTask);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
/*
* changed the Thread variable policy variable -lalita */
StrictMode.ThreadPolicy policy1 = new StrictMode.ThreadPolicy.Builder().permitAll().build();
StrictMode.setThreadPolicy(policy1);
ParentLayout = (RelativeLayout)findViewById(R.id.relativeLayout);
PreviewFrameImage = (ImageView)findViewById(R.id.previewScreenImageView);
PreviewFrameImage.setOnTouchListener(this);
Bitmap PreviewImage = BitmapFactory.decodeResource(getResources(), R.drawable.tvscreen_white);
PreviewFrameImage.setImageBitmap(Bitmap.createScaledBitmap( PreviewImage, 350 , 180 , true));
PreviewFrame = (FrameLayout)findViewById(R.id.videoSurfaceContainer);
mSurface = (SurfaceView) findViewById(R.id.surface_main);
mSurface .setZOrderOnTop(true);
// mSurface.setVisibility(View.GONE);
//PreviewFrame.removeView(mSurface);
mHolder = mSurface.getHolder();
mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
mHolder.setFormat(PixelFormat.TRANSPARENT);
controller = new VideoControllerView(this);
// youTubeView = (YouTubePlayerView) findViewById(R.id.youtube_view);
// youTubeView.setVisibility(View.INVISIBLE);
InitImgList();
Integer[] images = (Integer[])imgList.toArray(new Integer[imgList.size()]);
for( int i = 0; i <ChannelThumbnails.size() ; i++)
{
Log.e(TAG,"ResponseData----- lalita test ---- channel Image Path "+ChannelThumbnails.get(i));
}
com.ib.coverflow.FlowImageAdapter coverImageAdapter = new com.ib.coverflow.FlowImageAdapter(this,ChannelThumbnails.toArray( new String[ChannelThumbnails.size()]),180, 150);
//coverImageAdapter.createReflectedImages();
CoverFlow coverFlow = (CoverFlow) findViewById(R.id.coverflow);
coverFlow.setAdapter(coverImageAdapter);
//coverFlow.setSpacing(-20);
coverFlow.setSelection(30);
setupListeners(coverFlow);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.user_main_screen_main_actions, menu);
return super.onCreateOptionsMenu(menu);
}
/**
* On selecting action bar icons
* */
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Take appropriate action for each action item click
switch (item.getItemId()) {
case R.id.action_refresh:
// refresh
return true;
case R.id.action_user:
// help action
return true;
case R.id.action_menu:
// check for updates action
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void InitImgList() {
imgList.add(R.drawable.img01);
imgList.add(R.drawable.img02);
imgList.add(R.drawable.img03);
imgList.add(R.drawable.img04);
}
#SuppressWarnings("unchecked")
private void getChannelInfo(String ResultDataFroMsERVER) throws JSONException {
// TODO Auto-generated method stub
channelInfo = resultFromAsyncTask;
Log.e(TAG,"channel Information " +channelInfo );
/*
* Json object for parsing the data(Channel Info)
// */
try {
json = new JSONObject(channelInfo);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
ResponseData= json.getJSONArray("Response Data");
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
for(int i=0 ; i <ResponseData.length();i++)
{
jsonobjectresponsedata = ResponseData.getJSONObject(i);
ChannelID.add(jsonobjectresponsedata.getString("channel_id")) ;
ChannelType.add(jsonobjectresponsedata.getString("channel_type")) ;
VideoType.add(jsonobjectresponsedata.getString("video_type")) ;
ChannelName.add(jsonobjectresponsedata.getString("name")) ;
channelLink.add(jsonobjectresponsedata.getString("link")) ;
ChannelThumbnails.add( jsonobjectresponsedata.getString("img_path")) ;
}
}
private void getDataFromSignIn() {
// TODO Auto-generated method stub
Intent InfoFromSignScreen = getIntent();
UserName = InfoFromSignScreen.getCharSequenceExtra("UserName").toString();
AccessToken = InfoFromSignScreen.getCharSequenceExtra("AccessToken").toString();
Log.e (TAG, "LALITA TEST ***************** USERNAME AND aCCESS TOKEN " + UserName + " "+AccessToken);
}
private void SetUpVariables() {
// TODO Auto-generated method stub
tv = (TextView)findViewById(R.id.textView1);
}
private void FlipImageViewOnClick() {
// TODO Auto-generated method stub
ObjectAnimator animation = ObjectAnimator.ofFloat(PreviewFrameImage, "rotationY", 0.0f, 180f);
animation.setDuration(1500);
animation.setRepeatCount(0);
//animation.setRepeatCount(ObjectAnimator.RESTART);
animation.setInterpolator(new AccelerateInterpolator());
animation.start();
animation.addListener(new AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
// TODO Auto-generated method stub
//PreviewFrameImage.bringToFront();
// mSurface.invalidate();
Toast.makeText(getBaseContext(), "ANimation START ", Toast.LENGTH_SHORT).show();
}
#Override
public void onAnimationRepeat(Animator animation) {
// TODO Auto-generated method stub
Toast.makeText(getBaseContext(), "ANimationREPEAT", Toast.LENGTH_SHORT).show();
}
#Override
public void onAnimationEnd(Animator animation) {
// TODO Auto-generated method stub
PreviewFrameImage.setRotationY(0);
// mSurface.bringToFront();
// mSurface.setVisibility(View.VISIBLE);
Toast.makeText(getBaseContext(), "ANimation Endded ", Toast.LENGTH_SHORT).show();
}
#Override
public void onAnimationCancel(Animator animation) {
// TODO Auto-generated method stub
}
});
}
/**
* Setup cover flow.
*
* #param mCoverFlow
* the m cover flow
* #param reflect
* the reflect
*/
/**
* Sets the up listeners.
*
* #param mCoverFlow
* the new up listeners
*/
private void setupListeners(final CoverFlow coverFlow) {
coverFlow.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
// TODO Auto-generated method stub
/*
* Hls Streams
*/
if(channelLink.get(position).endsWith("m3u8")) {
Log.e(TAG," ******* HLS*************** " +channelLink.get(position) );
if(mMediaPlayer!= null )
{
// mSurface .setZOrderOnTop(true);
mHolder.setFormat(PixelFormat.TRANSPARENT);
controller.hide();
if(mMediaPlayer.isPlaying())
{
mMediaPlayer.stop();
}
mMediaPlayer.reset();
mMediaPlayer.release();
FlipImageViewOnClick();
// mSurface .setZOrderOnTop(false);
mHolder.setFormat(PixelFormat.OPAQUE);
// mSurface.setVisibility(View.VISIBLE);
//PreviewFrame.addView(mSurface);
// mSurface .setZOrderOnTop(false);
playHlsStreams(channelLink.get(position));
}
else
{
FlipImageViewOnClick();
//mSurface .setZOrderOnTop(false);
// mSurface.setVisibility(View.VISIBLE);
// PreviewFrame.addView(mSurface);
// mSurface .setZOrderOnTop(false);
mHolder.setFormat(PixelFormat.OPAQUE);
//mHolder.setFormat(PixelFormat.OPAQUE);
playHlsStreams(channelLink.get(position));
}
}
/*
* Octoshape Streams
*/
else if (channelLink.get(position).startsWith("octoshape"))
{
Log.e(TAG," octoshape " +channelLink.get(position) );
if(mMediaPlayer != null)
{
mHolder.setFormat(PixelFormat.TRANSPARENT);
controller.hide();
if(mMediaPlayer.isPlaying())
{
mMediaPlayer.stop();
}
mMediaPlayer.reset();
mMediaPlayer.release();
FlipImageViewOnClick();
mHolder.setFormat(PixelFormat.OPAQUE);
initOctoshapeSystem(channelLink.get(position)) ;
}
else
{
FlipImageViewOnClick();
initOctoshapeSystem(channelLink.get(position)) ;
}
else
{
Toast.makeText(getBaseContext(), "Youtube Work In Progress and RTMP PLAYER NOT AVAILABLE ", Toast.LENGTH_LONG).show();
}
}
});
}
private void playHlsStreams(String OCTOLINK1) {
// TODO Auto-generated method stub
mMediaPlayer = new MediaPlayer();
controller.setMediaPlayer(this);
controller.setAnchorView(PreviewFrame);
mMediaPlayer.setDisplay(mHolder);
try {
mMediaPlayer.setDataSource(this, Uri.parse(OCTOLINK1));
mMediaPlayer.prepare();
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mMediaPlayer.start();
}
public void initOctoshapeSystem(final String OCTOLINK1)
{
os = OctoshapeSystemCreator.create(this, problemListener,
new OctoshapePortListener() {
#Override
public void onPortBound(int port) {
setupStream(OCTOLINK1).requestPlay();
}
}, Locale.ENGLISH.getLanguage());
os.setProblemMessageLanguage(Locale.ENGLISH.getLanguage());
os.setProblemListener(problemListener);
os.addPlayerNameAndVersion(MediaPlayerConstants.NATIVE_PLAYER, MediaPlayerConstants.NATIVE_PLAYER,
"" + Build.VERSION.SDK_INT);
os.open();
}
public StreamPlayer setupStream(final String stream) {
Log.d(LOGTAG, "Setting up stream: " + stream);
StreamPlayer sp = os.createStreamPlayer(stream);
sp.setProblemListener(new ProblemListener() {
#Override
public void gotProblem(Problem p) {
StreamStatus="No Stream/Internet Problem";
Log.i("Stream Status ", "Not Ok");
active="yellow";
Log.e(LOGTAG, stream+": "+p.getMessage() + " " + p.toString());
}
});
sp.setListener(new StreamPlayerListener() {
private String playerId;
#Override
public void gotUrl(String url, long seekOffset,
boolean playAfterBuffer) {
Log.i(LOGTAG, "gotUrl");
if (playAfterBuffer)
urlQueue.add(Uri.parse(url));
else
playStream(Uri.parse(url), playerId);
}
#Override
public void gotNewOnDemandStreamDuration(long duration) {
}
#Override
public void resolvedNativeSeek(boolean isLive, String playerId) {
Log.i(LOGTAG, "resolvedNativeSeek");
this.playerId = playerId;
}
#Override
public void resolvedNoSeek(boolean isLive, String playerId) {
Log.i(LOGTAG, "resolvedNoSeek");
this.playerId = playerId;
}
#Override
/**
* Called when stream support OsaSeek / DVR
*/
public void resolvedOsaSeek(boolean isLive, long duration,
String playerId) {
Log.i(LOGTAG, "resolvedOsaSeek");
this.playerId = playerId;
}
});
//sp.initialize(false);
return sp;
}
protected void playStream(Uri mediaUrl, final String playerId) {
Log.d(LOGTAG, playerId + " now plays: " + mediaUrl);
try {
mMediaPlayer = new MediaPlayer();
controller.setMediaPlayer(this);
controller.setAnchorView(PreviewFrame);
mMediaPlayer.setDisplay(mHolder);
mMediaPlayer.setDataSource(this, mediaUrl);
mMediaPlayer.setOnVideoSizeChangedListener(this);
mMediaPlayer.setOnCompletionListener(new OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mp) {
if (!urlQueue.isEmpty())
playStream(urlQueue.removeFirst(), playerId);
}
});
mMediaPlayer.setOnErrorListener(new OnErrorListener() {
#Override
public boolean onError(MediaPlayer mp, int what, int extra) {
error("MediaPlayer Error: " + what + ":" + extra);
return true;
}
});
mMediaPlayer.prepare();
mMediaPlayer.start();
} catch (Exception e) {
Log.e(LOGTAG, "Error preparing MediaPlayer", e);
error("Error preparing MediaPlayer: " + e.getMessage());
}
}
#Override
public void onVideoSizeChanged(MediaPlayer mp, int width, int height) {
FrameLayout.LayoutParams vLayout = (FrameLayout.LayoutParams) mSurface
.getLayoutParams();
mSurface.setLayoutParams(vLayout);
// dialog.dismiss();
StreamStatus="Stream Ok";
Log.i("Stream Stattus", "Stream Ok");
active="true";
long startTime = System.currentTimeMillis();
System.out.println("dddddddddddddddddddddddddddddddddddddddddddddd"+startTime);
Timer timer = new Timer();
timer.schedule(new SayHello(), 50000, 60000);
}
#Override
public void onBackPressed() {
// do nothing.
}
public void shutdown(){
if (mMediaPlayer != null)
mMediaPlayer.release();
if (os != null) {
os.close(new Runnable() {
#Override
public void run() {
UserMainScreen.this.finish();
}
});
}
}
#Override
protected void onStop()
{
super.onStop();
Log.d(LOGTAG, "MY onStop is called");
shutdown();
}
ProblemListener problemListener = new ProblemListener() {
#Override
public void gotProblem(Problem p) {
Log.e(LOGTAG, p.getMessage() + "\n" + p.toString());
error(p.getMessage());
}
};
protected void error(final String error) {
runOnUiThread(new Runnable() {
#Override
public void run() {
try {
// dialog.show();
Log.i(LOGTAG, "problem dialog block");
}
catch(Exception e)
{
e.printStackTrace();
}
}
});
}
class SayHello extends TimerTask {
public void run() {
System.out.println("Catche clear method scheduled");
clearCache();
}
}
void clearCache()
{
Log.d(LOGTAG, "clearCache() clled");
if (mClearCacheObserver == null)
{
mClearCacheObserver=new CachePackageDataObserver();
}
PackageManager mPM=getPackageManager();
#SuppressWarnings("rawtypes")
final Class[] classes= { Long.TYPE, IPackageDataObserver.class };
Long localLong=Long.valueOf(CACHE_APP);
try
{
Method localMethod=
mPM.getClass().getMethod("freeStorageAndNotify", classes);
try
{
localMethod.invoke(mPM, localLong, mClearCacheObserver);
}
catch (IllegalArgumentException e)
{
e.printStackTrace();
}
catch (IllegalAccessException e)
{
e.printStackTrace();
}
catch (InvocationTargetException e)
{
e.printStackTrace();
}
}
catch (NoSuchMethodException e1)
{
e1.printStackTrace();
}
}
private class CachePackageDataObserver extends IPackageDataObserver.Stub
{
public void onRemoveCompleted(String packageName, boolean succeeded)
{
}
}
#Override
public void surfaceCreated(SurfaceHolder mHolder) {
// TODO Auto-generated method stub
Log.e(TAG,"**************Surface created**************LOLZ ") ;
mMediaPlayer.start();
}
#Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
// TODO Auto-generated method stub
Log.e(TAG,"Surface CHANGED **************LOLZ ") ;
}
#Override
public void surfaceDestroyed(SurfaceHolder holder) {
// TODO Auto-generated method stub
Log.e(TAG,"Surface destroyed **************LOLZ " );
}
#Override
public void onPrepared(MediaPlayer mp) {
// TODO Auto-generated method stub
}
#Override
public boolean canPause() {
return true;
}
#Override
public boolean canSeekBackward() {
return true;
}
#Override
public boolean canSeekForward() {
return true;
}
#Override
public int getBufferPercentage() {
return 0;
}
#Override
public int getCurrentPosition() {
//Log.e(TAG, "GET CURRENT POSITION " +mMediaPlayer.getCurrentPosition());
return mMediaPlayer.getCurrentPosition();
}
#Override
public int getDuration() {
return mMediaPlayer.getDuration();
}
#Override
public boolean isPlaying() {
return mMediaPlayer.isPlaying();
}
#Override
public void pause() {
mMediaPlayer.pause();
}
#Override
public void seekTo(int i) {
mMediaPlayer.seekTo(i);
}
#Override
public void start() {
mMediaPlayer.start();
}
#Override
public boolean isFullScreen() {
return false;
}
public void toggleFullScreen() {
controller.hide();
mMediaPlayer.stop();
// intent = new Intent(UserMainScreen.this,
// MiniAndroidPlayer.class);
intent.putExtra("OCTO", OCTOLINK1);
startActivity(intent);
}
// End VideoMediaController.MediaPlayerControl
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(PreviewFrame == v )
{
controller.show();
//mSurface.invalidate();
Log.e(TAG, " Preview frame controller Show" +controller.isShown());
}
if( mSurface == v )
{
controller.show(); // do things
// mSurface.invalidate();
Log.e(TAG, " mSurface controller Show" +controller.isShown());
}
if (PreviewFrameImage == v)
{
controller.show(); // do things
Log.e(TAG, " PreviewFrameImage controller Show" +controller.isShown());
}
if ( youTubeView == v) {
controller.show(); // do things
//mSurface.invalidate();
Log.e(TAG, " youtubeView controller Show" +controller.isShown());
//
// controller.setVisibility(View.VISIBLE);
}
return false;
}
#Override
public void onInitializationFailure(YouTubePlayer.Provider provider,
YouTubeInitializationResult errorReason) {
// TODO Auto-generated method stub
if (errorReason.isUserRecoverableError()) {
errorReason.getErrorDialog(this, RECOVERY_DIALOG_REQUEST).show();
} else {
String errorMessage = String.format(
getString(R.string.error_player), errorReason.toString());
Toast.makeText(this, errorMessage, Toast.LENGTH_LONG).show();
}
}
#Override
public void onInitializationSuccess(YouTubePlayer.Provider provider,
YouTubePlayer player, boolean wasRestored) {
// TODO Auto-generated method stub
if (!wasRestored) {
// loadVideo() will auto play video
// Use cueVideo() method, if you don't want to play it automatically
// player.loadVideo(Config.YOUTUBE_VIDEO_CODE);
//
// Hiding player controls
player.setPlayerStyle(PlayerStyle.MINIMAL);
}
}
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
if (requestCode == RECOVERY_DIALOG_REQUEST) {
// Retry initialization if user performed a recovery action
// done now getYouTubePlayerProvider().initialize(Config.DEVELOPER_KEY, this);
}
}
/*
* Uncomment again
*/
// private YouTubePlayer.Provider getYouTubePlayerProvider()
// {
// return (YouTubePlayerView) findViewById(R.id.youtube_view);
// }
#Override
public void onAnimationStart(Animator animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationEnd(Animator animation) {
// TODO Auto-generated method stub
PreviewFrameImage.setRotationY(-90);
}
#Override
public void onAnimationCancel(Animator animation) {
// TODO Auto-generated method stub
}
#Override
public void onAnimationRepeat(Animator animation) {
// TODO Auto-generated method stub
}
public static void initImageLoader(Context context) {
// This configuration tuning is custom. You can tune every option, you may tune some of them,
// or you can create default configuration by
// ImageLoaderConfiguration.createDefault(this);
// method.
DisplayImageOptions options = new DisplayImageOptions.Builder()
.showImageOnLoading(R.drawable.ic_stub)
.showImageForEmptyUri(R.drawable.ic_empty)
.showImageOnFail(R.drawable.ic_error)
.cacheInMemory(true)
.cacheOnDisc(true)
.considerExifParams(true)
.displayer(new RoundedBitmapDisplayer(20))
.build();
File cacheDir = StorageUtils.getCacheDirectory(context);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(context)
.threadPriority(Thread.NORM_PRIORITY - 2)
.denyCacheImageMultipleSizesInMemory()
.discCache(new LimitedAgeDiscCache(cacheDir, 60))
.discCacheFileNameGenerator(new Md5FileNameGenerator())
.tasksProcessingOrder(QueueProcessingType.LIFO)
.writeDebugLogs() // Remove for release app
.defaultDisplayImageOptions(options)
.build();
// Initialize ImageLoader with configuration.
ImageLoader.getInstance().init(config);
}
#Override
public boolean onNavigationItemSelected(int itemPosition, long itemId) {
// TODO Auto-generated method stub
return false;
}
}
Main.xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relativeLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#drawable/background"
android:orientation="vertical" >
<ImageView
android:id="#+id/previewScreenImageView"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_marginBottom="190dip"
android:layout_marginTop="20dp" />
<FrameLayout
android:id="#+id/videoSurfaceContainer"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginBottom="205dp"
android:layout_marginLeft="270dp"
android:layout_marginRight="269dp"
android:layout_marginTop="30dp"
android:text="framelayout"
>
<!-- <com.google.android.youtube.player.YouTubePlayerView
android:id="#+id/youtube_view"
android:layout_width="match_parent"
android:layout_height="match_parent" /> -->
<SurfaceView
android:id="#+id/surface_main"
android:layout_width="484dp"
android:layout_height="235dp"
/>
</FrameLayout>
<com.ib.coverflow.CoverFlow
xmlns:coverflow ="http://schemas.android.com/apk/res/com.ib.qezyplay"
android:id ="#+id/coverflow"
android:layout_width ="fill_parent"
android:layout_height ="wrap_content"
android:layout_alignParentBottom="true"
android:paddingBottom="20dp">"
</com.ib.coverflow.CoverFlow>
</RelativeLayout>

Thread in my code does not work

Here is the code, Results Activity should start if button is clicked:
public class Tab19 extends Activity {
ImageButton button1;
SoundPool mSoundPool;
AssetManager assets;
int catSound;
int countLoadedSound;
Context mContext;
ProgressDialog dialog;
int count = 0;
TextView t;
boolean has_been_clicked = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab19);
count = getIntent().getIntExtra("CountNum", 0);
mContext = this;
mSoundPool = new SoundPool(2, AudioManager.STREAM_MUSIC, 0);
assets = getAssets();
catSound = loadSound("catSound.mp3");
button1 = (ImageButton)findViewById(R.id.button2);
button1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
playSound(catSound);
Intent firstIntent = new Intent(Tab19.this, Results.class);
TextView t = (TextView)findViewById(R.id.t);
t.setText("score: " + ++count +"/18");
firstIntent.putExtra("CountNum", count);
has_been_clicked = true;
startActivity(firstIntent);
finish();
}
});
new Thread(
new Runnable() {
public void run() {
while (!has_been_clicked) {
try {
// Thread will sleep for 10 seconds
sleep(10*1000);
} catch (Exception e) {
}
}
Intent i=new Intent(getBaseContext(),Results.class);
i.putExtra("CountNum", count);
startActivity(i);
finish();
return;
}
private void sleep(int i) {
// TODO Auto-generated method stub
}
}
).start(); }
#Override
protected void onDestroy() {
super.onDestroy(); }
protected void playSound(int sound) {
if (sound > 0)
mSoundPool.play(sound, 1, 1, 1, 0, 1);
}
private int loadSound(String fileName) {
AssetFileDescriptor afd = null;
try {
afd = assets.openFd(fileName);
} catch (IOException e) {
e.printStackTrace();
Toast.makeText(this, "Не могу загрузить файл " + fileName,
Toast.LENGTH_SHORT).show();
return -1;
}
return mSoundPool.load(afd, 1);
} }
If button is not clicked Thread should start next Activity within 10 seconds, but it does not happen, please help me find a mistake. Thanks in advance
Into your thread change the while loop into an if statement:
if (!has_been_clicked) {
try {
// Thread will sleep for 10 seconds
sleep(10*1000);
} catch (Exception e) {
}
}
I think you should change your code to
boolean has_been_clicked = true;
...
while (has_been_clicked) {
has_been_clicked = false;
try {
// Thread will sleep for 10 seconds
sleep(10*1000);
} catch (Exception e) {
}
}
Intent i=new Intent(getBaseContext(),Results.class);
i.putExtra("CountNum", count);
startActivity(i);
finish();
return;

java.lang.NullPointerException on my Service Media player

i have tried to find the answer...and have no idea what i was doing wrong
public class RadioService extends Service {NotificationManager nm;Intent i;
String artist, title, streamUrl, title_play;
int id = 0;
public MediaPlayer mp ;
#Override
public void onCreate() {
super.onCreate();
mp = new MediaPlayer();
nm = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
mp.setOnPreparedListener(new OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mp.start(); // TODO Auto-generated method stub
}
});
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
public int onStartCommand(Intent intent, int flags, int startId) {
try {
artist = intent.getStringExtra("artist");
title = intent.getStringExtra("title");
streamUrl = intent.getStringExtra("streamUrl");
title_play = intent.getStringExtra("title_play");
id = intent.getIntExtra("id", 0);
Log.d("MyLog in radioservise", "" + artist + title + streamUrl
+ title_play + id);
} catch (Exception e1) {
Log.d("MyLog", "" + artist + title + streamUrl + title_play + id);
Log.d("Exeption here", e1 + "");
e1.printStackTrace();
}
Play();
sendNotif();
return super.onStartCommand(intent, flags, startId);
}
void sendNotif() {
Intent intent = new Intent(this, PlayActivity.class);
// intent.putExtra(MainActivity.FILE_NAME, "somefile");
PendingIntent pIntent = PendingIntent.getActivity(this, 0, intent, 0);
notif.setLatestEventInfo(this, title_play, streamUrl, pIntent);
notif.flags |= Notification.FLAG_AUTO_CANCEL;
nm.notify(1, notif);
}
public void onExit() {
if (mp != null)
{
mp.stop();
mp.release();
mp = null;
}
nm.cancelAll();
}
public void Play(/* String play */) {
try {
if (mp.isPlaying()) {
stop();
} else {
mp.reset();
mp.setAudioStreamType(AudioManager.STREAM_MUSIC);
mp.setDataSource(streamUrl);
mp.prepareAsync();
}
} catch (Exception e) {
}}
public void Pause() {
try {
if (mp.isPlaying()) {
if (mp!=null){
mp.pause();
}
}
} catch ( Exception e) {
e.printStackTrace();
}
}
public void Mute() {
try {
mp.setVolume(0, 0);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void Volume() {
try {
mp.setVolume(1, 1);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void stop() {
if (mp.isPlaying()) {
try {
mp.stop();
mp.prepare();
} catch (IOException e) {
e.printStackTrace();
}
}
}
when i launch the activity i run service ,where i am play the music. The music plays fine, but when I click on pause or mute button the application crashes with NullPointer exception on mp.pause() or pm.volume(0,0) or mp.stop
The code of activity here:
public void onClick(View v) {
switch (v.getId()) {
case R.id.im_play:
rServ.Play(/*streamUrl*/);
ResetInfo(streamUrl);
break;
case R.id.im_pause:
rServ.Pause();
// rServ.mp.pause();
break;
case R.id.im_mute:
if (z == true) {
rServ.Mute();
mut.setImageResource(R.drawable.no_mute_bt_ic);
z = false;
} else {
rServ.Volume();
mut.setImageResource(R.drawable.mute_bt_ic);
z = true;
}
break;
}
}
public void onBackPressed() {
tm.listen(phoneStateListener, PhoneStateListener.LISTEN_NONE);
try {
//if (rServ.mp != null && rServ.mp.isPlaying()) {
rServ.onExit();
//rServ.stop();
t.cancel();
//}
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Logcat error:
> 02-05 10:01:04.238: E/AndroidRuntime(429): FATAL EXCEPTION: main
02-05 10:01:04.238: E/AndroidRuntime(429): java.lang.NullPointerException
02-05 10:01:04.238: E/AndroidRuntime(429): at com.example.smpleradio.RadioService.onExit(RadioService.java:106)
02-05 10:01:04.238: E/AndroidRuntime(429): at com.example.smpleradio.PlayActivity.onBackPressed(PlayActivity.java:190)
02-05 10:01:04.238: E/AndroidRuntime(429): at com.example.smpleradio.PlayActivity.onOptionsItemSelected(PlayActivity.java:249)
I think your varible " nm " is becoming null. So please verify it where it happening.

I Want to detect Screen Resolution

I have an android application with a country map divided into Districts...
and in the database.xml file i put the XY coordinates positions for each District in the map...
But, when I run the application on a device with a different screen size,
the positions change and Didn't fit the positions that I need!
So, Please I Want to know how to detect the screen size, and create a separate XY database for each screen resolution!
Thank you in Advance,
here is the MainActivity.java Code, if you want anything else I will post it,
please I need your help! :(
private final Context appContext = MainActivity.this;
RelativeLayout relativeLayoutMap;
ProgressDialog xyProgressDialog;
Dialog dialog;
Spinner spinner;
MediaPlayer mediaPlayer;
static String extStorageDirectory = Environment
.getExternalStorageDirectory().toString();
final static String TARGET_BASE_PATH = extStorageDirectory + "/";
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
relativeLayoutMap = (RelativeLayout) findViewById(R.id.mapContainer);
checklanguage();
clickRadioButton();
playMusicOnCoordinatesClick();
new saveFoldertoSDCard().execute("MyApp");
**//Display myDisplay = getWindowManager().getDefaultDisplay();
//Point point = new Point();
//myDisplay.getSize(point);
//int width = point.x;
//int height = point.y;**
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public void clickRadioButton() {
RadioButton rdbtnEnglish = (RadioButton) findViewById(R.id.rdBtnEnglish);
if(rdbtnEnglish.isChecked()){
saveLanguageSelection(true);
}else{
saveLanguageSelection(false);
}
rdbtnEnglish.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
// TODO Auto-generated method stub
saveLanguageSelection(isChecked);
}
});
}
public void elabirate() {
int coordinates = Coordinates.sCoordinatesList.size();
int i;
for (i = 0; i < coordinates; i++) {
final Button btnclick = new Button(appContext);
btnclick.setId(i);
RadioButton rdbtnEnglish = (RadioButton) findViewById(R.id.rdBtnEnglish);
if(rdbtnEnglish.isChecked()){
btnclick.setText("" + Coordinates.sCoordinatesList.get(i).getName());
}else{
btnclick.setText("" + Coordinates.sCoordinatesList.get(i).getArabicCityName());
}
btnclick.setBackgroundResource(R.drawable.round_button_selector);
btnclick.setTextColor(Color.CYAN);
LayoutParams lp = new LayoutParams(
android.app.ActionBar.LayoutParams.WRAP_CONTENT,
android.app.ActionBar.LayoutParams.WRAP_CONTENT);
lp.topMargin = Coordinates.sCoordinatesList.get(i).getX();
lp.leftMargin = Coordinates.sCoordinatesList.get(i).getY();
relativeLayoutMap.addView(btnclick, lp);
btnclick.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Integer id = btnclick.getId();
Intent intent = new Intent();
intent.setClass(appContext, CityActivity.class);
intent.putExtra("btnid", id.toString());
startActivity(intent);
}
});
}
}
public void changeCoordinatesLanguage(View view){
RadioButton rdbtnEnglish = (RadioButton) findViewById(R.id.rdBtnEnglish);
int coordinates = Coordinates.sCoordinatesList.size();
int i;
for (i = 0; i < coordinates; i++) {
final Button btnCoordinates = (Button) findViewById(i);
if(rdbtnEnglish.isChecked()){
btnCoordinates.setText("" + Coordinates.sCoordinatesList.get(i).getName());
loadCityList();
}else{
btnCoordinates.setText("" + Coordinates.sCoordinatesList.get(i).getArabicCityName());
loadCityList();
}
}
}
public class GetCoordinates extends AsyncTask<String, Integer, Boolean> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
xyProgressDialog = new ProgressDialog(appContext);
xyProgressDialog.setMessage("Loading...");
xyProgressDialog.setCancelable(false);
xyProgressDialog.show();
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
return Coordinates.getCity();
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
try {
xyProgressDialog.dismiss();
if (result) {
elabirate();
loadCityList();
} else {
Toast.makeText(appContext, "Unable to load City list",
Toast.LENGTH_SHORT).show();
}
} catch (Exception e) {
// TODO: handle exception
}
super.onPostExecute(result);
}
}
public void loadImage(){
dialog = new Dialog(appContext);
dialog.setContentView(R.layout.progress_dialog);
dialog.setTitle("Load Progress");
dialog.show();
}
public class saveFoldertoSDCard extends AsyncTask<String, Integer, Boolean> {
#Override
protected void onPreExecute() {
// TODO Auto-generated method stub
dialog = new Dialog(appContext);
dialog.setContentView(R.layout.progress_dialog);
dialog.setTitle("My App");
dialog.setCancelable(false);
dialog.show();
super.onPreExecute();
}
#Override
protected Boolean doInBackground(String... params) {
// TODO Auto-generated method stub
return copyFileOrDir(params[0]);
}
#Override
protected void onPostExecute(Boolean result) {
// TODO Auto-generated method stub
try {
//xyProgressDialog.dismiss();
dialog.dismiss();
if (result) {
String path = Environment.getExternalStorageDirectory()
.toString()
+ "/MyApp/MyAppdata.xml";
new GetCoordinates().execute(path);
}
} catch (Exception e) {
// TODO: handle exception
}
super.onPostExecute(result);
}
}
private Boolean copyFileOrDir(String path) {
AssetManager assetManager = this.getAssets();
String assets[] = null;
try {
assets = assetManager.list(path);
if (assets.length == 0) {
copyFile(path);
} else {
String fullPath = TARGET_BASE_PATH + path;
Log.i("tag", "path=" + fullPath);
File dir = new File(fullPath);
if (!dir.exists())
if (!dir.mkdirs())
;
Log.i("tag", "could not create dir " + fullPath);
for (int i = 0; i < assets.length; ++i) {
String p;
if (path.equals(""))
p = "";
else
p = path + "/";
copyFileOrDir(p + assets[i]);
}
}
return true;
} catch (IOException ex) {
return false;
}
}
private void copyFile(String filename) {
AssetManager assetManager = this.getAssets();
InputStream in = null;
OutputStream out = null;
String newFileName = null;
try {
in = assetManager.open(filename);
if (filename.endsWith(".png")) // extension was added to avoid
// compression on APK file
newFileName = TARGET_BASE_PATH
+ filename.substring(0, filename.length() - 4);
else
newFileName = TARGET_BASE_PATH + filename;
out = new FileOutputStream(newFileName);
byte[] buffer = new byte[1024];
int read;
while ((read = in.read(buffer)) != -1) {
out.write(buffer, 0, read);
}
in.close();
in = null;
out.flush();
out.close();
out = null;
} catch (Exception e) {
}
}
public void saveLanguageSelection(boolean value) {
SharedPreferences Shared_preferences = PreferenceManager
.getDefaultSharedPreferences(appContext);
SharedPreferences.Editor editor = Shared_preferences.edit();
if (value) {
editor.putString("lang", "english");
} else {
editor.putString("lang", "arabic");
}
editor.commit();
}
public void checklanguage() {
RadioButton rdbtnEnglish = (RadioButton) findViewById(R.id.rdBtnEnglish);
RadioButton rdbtnArabic = (RadioButton) findViewById(R.id.rdBtnArabic);
SharedPreferences Shared_preferences = PreferenceManager
.getDefaultSharedPreferences(appContext);
String txtlanguage = Shared_preferences.getString("lang", "null");
if (txtlanguage != "null") {
if (txtlanguage.equals("english")) {
rdbtnEnglish.setChecked(true);
rdbtnArabic.setChecked(false);
} else {
rdbtnEnglish.setChecked(false);
rdbtnArabic.setChecked(true);
}
} else {
rdbtnEnglish.setChecked(true);
rdbtnArabic.setChecked(false);
saveLanguageSelection(true);
}
}
public void showWeather(View view) {
String url = "http://m.accuweather.com/";
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
//parse: to check the availability of the url, ex: 123?
startActivity(browserIntent);
}
public void aboutApp(View view) {
openAboutDialog();
}
#SuppressWarnings("deprecation")
private void openAboutDialog() {
final AlertDialog alertDialog = new AlertDialog.Builder(
MainActivity.this).create();
alertDialog.setTitle("About");
alertDialog.setMessage("MyApp");
alertDialog.setIcon(R.drawable.ic_launcher);
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
alertDialog.dismiss();
}
});
alertDialog.show();
}
public void loadCityList(){
Integer type=0;
RadioButton rdbtnEnglish = (RadioButton) findViewById(R.id.rdBtnEnglish);
if(rdbtnEnglish.isChecked()){
type=0;
}else{
type=1;
}
CityList.getAllCityList(type);
CityListAdapter cityAdapter = new CityListAdapter(appContext, CityList.sCityList);
spinner = (Spinner) findViewById(R.id.spinner1);
spinner.setAdapter(cityAdapter);
spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> arg0, View view,
int arg2, long arg3) {
// TODO Auto-generated method stub
if(arg2 > 0){
TextView txtcityId = (TextView) view.findViewById(R.id.txtCityId);
TextView txtXyId = (TextView) view.findViewById(R.id.txtxyId);
Intent intent = new Intent();
intent.setClass(appContext, CityImagesActivity.class);
intent.putExtra("xyid", txtXyId.getText().toString());
intent.putExtra("cityid", txtcityId.getText().toString());
startActivity(intent);
}
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
// TODO Auto-generated method stub
}
});
}
public void playMusicOnCoordinatesClick() {
mediaPlayer = new MediaPlayer();
mediaPlayer.reset();
try {
AssetFileDescriptor afd = getAssets().openFd("Intro.mp3");
mediaPlayer.setDataSource(afd.getFileDescriptor(),afd.getStartOffset(),afd.getLength());
} catch (IllegalArgumentException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (SecurityException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IllegalStateException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
try {
mediaPlayer.prepare();
} catch (IllegalStateException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (mediaPlayer.isPlaying()) {
mediaPlayer.stop();
}
mediaPlayer.setVolume(100, 100);
mediaPlayer.start();
}
public void calledSearch(View view){
Intent intent = new Intent();
intent.setClass(appContext, SearchActivity.class);
startActivity(intent);
}
You can use something like:
Display myDisplay = getWindowManager().getDefaultDisplay();
Point point = new Point();
myDisplay.getSize(point);
int width = point.x;
int height = point.y;
as per this awesome answer.
If your map view is not full screen then I suggest using percentages to set the size of the map. This way you can use a percentage offset with your coordinates to alleviate the varying screen size issue. You definitely don't want to store different sets of XML co-ordinates for different screen resolutions.

Categories

Resources