android get OnTouchEvent even the app is not active, java null pointer - java

i try to make a app, witch listen also to a touch event, even when it is running in the background, here i found a solution in the forum, but i can't get i running
How can a service listen for touch gestures/events?
if i understood it right, the way to do this, is to set up a new view with the right windowmanager parameters, here is my code!
main activity:
public class MainActivity extends Activity {
View mView;
HUD mHud;
HUDView mHUDView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mHud = new HUD();
mHUDView = new HUDView(this);
}
#Override
public boolean onTouchEvent(MotionEvent e) {
mHud.onCreate(this);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
at the moment, for testing i just want to change the view, with the first touch,
public class HUD extends Service {
HUDView mView;
public void onCreate(Context mContext) {
super.onCreate();
mView = new HUDView(this);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.TYPE_SYSTEM_ALERT,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE|WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL|WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT);
params.gravity = Gravity.RIGHT | Gravity.TOP;
params.setTitle("Load Average");
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.addView(mView, params);
}
#Override
public IBinder onBind(Intent intent) {
// TODO Auto-generated method stub
return null;
}
}
class HUDView extends ViewGroup {
public HUDView(Context context) {
super(context);
}
#Override
protected void onLayout(boolean arg0, int arg1, int arg2, int arg3, int arg4) {
}
#Override
public boolean onTouchEvent(MotionEvent event) {
Log.d("ontouch", "clicked in the HUD View");
//Toast.makeText(getContext(),"onTouchEvent", Toast.LENGTH_LONG).show();
return true;
}
}
I'am not very confident in java, the error i get is a javaNullPointerException Error. I know this happend because a object became null, but how do i pass the object to the class and to the subclass.
here the log:
11-18 11:56:03.791: E/AndroidRuntime(5095): FATAL EXCEPTION: main
11-18 11:56:03.791: E/AndroidRuntime(5095): java.lang.NullPointerException
11-18 11:56:03.791: E/AndroidRuntime(5095): at android.content.ContextWrapper.getResources(ContextWrapper.java:80)
11-18 11:56:03.791: E/AndroidRuntime(5095): at android.view.View.<init>(View.java:1810)
11-18 11:56:03.791: E/AndroidRuntime(5095): at android.view.ViewGroup.<init>(ViewGroup.java:288)
11-18 11:56:03.791: E/AndroidRuntime(5095): at com.holzi.runinbackground.HUDView.<init>(HUD.java:47)
11-18 11:56:03.791: E/AndroidRuntime(5095): at com.holzi.runinbackground.HUD.onCreate(HUD.java:22)
11-18 11:56:03.791: E/AndroidRuntime(5095): at com.holzi.runinbackground.MainActivity.onTouchEvent(MainActivity.java:32)
11-18 11:56:03.791: E/AndroidRuntime(5095): at android.app.Activity.dispatchTouchEvent(Activity.java:2096)
11-18 11:56:03.791: E/AndroidRuntime(5095): at com.android.internal.policy.impl.PhoneWindow$DecorView.dispatchTouchEvent(PhoneWindow.java:1685)
11-18 11:56:03.791: E/AndroidRuntime(5095): at android.view.ViewRoot.handleMessage(ViewRoot.java:1802)
11-18 11:56:03.791: E/AndroidRuntime(5095): at android.os.Handler.dispatchMessage(Handler.java:99)
11-18 11:56:03.791: E/AndroidRuntime(5095): at android.os.Looper.loop(Looper.java:143)
11-18 11:56:03.791: E/AndroidRuntime(5095): at android.app.ActivityThread.main(ActivityThread.java:4914)
11-18 11:56:03.791: E/AndroidRuntime(5095): at java.lang.reflect.Method.invokeNative(Native Method)
11-18 11:56:03.791: E/AndroidRuntime(5095): at java.lang.reflect.Method.invoke(Method.java:521)
11-18 11:56:03.791: E/AndroidRuntime(5095): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:858)
thx!

You're passing this as the context to HUDView, this is your Service, which does not have a base context until it is attached, and thus will throw if getResources() is called.
You'll need to wait until attachBaseContext is called, or use another Context to instantiate HUDView instead of the service, perhaps the Application context.

Here the complete working code to just log any touch on the mobile, catched by the invisible system alert overlay
public class InvisibleView extends Service {
View myView;
#Override
public IBinder onBind(Intent intent) {
return null;
}
public void onCreate(Context myContext) {
super.onCreate();
LayoutInflater inflater = (LayoutInflater) myContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
myView = new View(myContext);
myView = inflater.inflate(R.layout.invisibleviewxml, null);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY,
WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH,
PixelFormat.TRANSLUCENT);
WindowManager wm = (WindowManager) myContext.getSystemService(WINDOW_SERVICE);
wm.addView(myView, params);
myView.setOnTouchListener( new OnTouchListener() {
#Override
public boolean onTouch(View inviView, MotionEvent event) {
Log.d("tag", "touch caught by invisble running service");
return true;
}
});
}
#Override
public void onDestroy() {
super.onDestroy();
if(myView != null)
{
((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(myView);
myView = null;
}
}
}
Main Activity:
public class MainActivity extends Activity {
InvisibleView myInvisibleView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myInvisibleView = new InvisibleView();
loadInvisibleView();
sendScreenHome();
}
private void loadInvisibleView(){
myInvisibleView.onCreate(this.getApplicationContext());
}
private void sendScreenHome(){
Intent homeIntent= new Intent(Intent.ACTION_MAIN);
homeIntent.addCategory(Intent.CATEGORY_HOME);
homeIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(homeIntent);
}
}
invisibleviewxml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="programm is running ..."
android:textAppearance="?android:attr/textAppearanceSmall" />
</LinearLayout>

Related

Keep media player working in background with screen off

I've an streaming audio (from a server) with Media Player. It works when I turn off the screen and the system goes to sleep mode but after some minutes the phone stop music. This doesn't happen when the cellphone is connected to power (USB cable). So, the system must crash the app due to a power management or a memory management.
Service class:
public class MyService extends Service {
PowerManager powerManager;
PowerManager.WakeLock wakeLock;
WifiManager.WifiLock wifiLock;
private MediaPlayer mediaPlayer;
#Nullable
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "My Lock");
wifiLock = ((WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE)).createWifiLock(WifiManager.WIFI_MODE_FULL, "mylock");
wakeLock.acquire();
wifiLock.acquire();
mediaPlayer = new MediaPlayer();
mediaPlayer.setWakeMode(getApplicationContext(), PowerManager.PARTIAL_WAKE_LOCK);
mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
try {
mediaPlayer.setDataSource("http://mediacontrol.jargon.com.ar:8168/;");
} catch (IOException e) {
e.printStackTrace();
}
mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mp) {
mediaPlayer.start();
}
});
mediaPlayer.prepareAsync();
return START_REDELIVER_INTENT;
}
#Override
public void onDestroy() {
super.onDestroy();
mediaPlayer.stop();
mediaPlayer.release();
wakeLock.release();
wifiLock.release();
}
}
And this is the class that implements the service:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
setRetainInstance(true); // con esto retenemos los valores pero se elimina el view
View view = inflater.inflate(R.layout.fragment_blank_fragment4, container, false);
play = (ImageButton) view.findViewById(R.id.imageButton);
imagen=(ImageView) view.findViewById((R.id.imageView));
if(comenzar) {
play.setImageResource(R.drawable.play);
}
else {
play.setImageResource(R.drawable.stop);
}
play.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (comenzar) {
if(isConnectedMobile(getActivity())||
isConnectedWifi(getActivity())) {
play.setImageResource(R.drawable.stop);
getActivity().getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
getActivity().startService(new Intent(getActivity(), MyService.class));
showNotification();
comenzar = false;
release=true;
}
else
{
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle("No hay conexión a internet");
builder.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
} else {
play.setImageResource(R.drawable.play);
getActivity().stopService(new Intent(getActivity(), MyService.class));
comenzar = true;
NotificationManager mNotificationManager = (NotificationManager) getActivity().getSystemService(Context.NOTIFICATION_SERVICE);
//getActivity().getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
release=false;
}
}
});
return view;
}
I also set this permission in the manifest
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.REQUEST_IGNORE_BATTERY_OPTIMIZATIONS" />
I can't debug it so well because the problem happens when the mobile is not connected but when the audio crash, then I connect it and it runs a one second more when I turn on the screen and after it stops.
I get this:
09-24 18:14:21.480 8539-8539/jaodev.utnfrp W/MediaPlayer: mediaplayer went away with unhandled events
09-24 18:14:24.070 8539-8551/jaodev.utnfrp I/MediaHTTPConnection: proxyName: 0.0.0.0 0
09-24 18:14:24.970 8539-8539/jaodev.utnfrp D/MediaPlayer: setSubtitleAnchor in MediaPlayer
09-24 18:17:57.413 8539-8552/jaodev.utnfrp I/MediaHTTPConnection: proxyName: 0.0.0.0 0
09-24 18:18:30.437 8539-8551/jaodev.utnfrp I/MediaHTTPConnection: proxyName: 0.0.0.0 0
09-24 18:18:34.187 8539-9040/jaodev.utnfrp W/MediaPlayer: info/warning (703, 0)
09-24 18:18:34.188 8539-9040/jaodev.utnfrp W/MediaPlayer: info/warning (701, 0)
09-24 18:19:03.462 8539-9040/jaodev.utnfrp I/MediaHTTPConnection: proxyName: 0.0.0.0 0
09-24 18:19:03.941 8539-9040/jaodev.utnfrp W/MediaHTTPConnection: readAt 1507328 / 32768 => java.net.ProtocolException
09-24 18:19:04.202 8539-8551/jaodev.utnfrp W/MediaPlayer: info/warning (703, 0)
09-24 18:21:51.201 8539-8544/jaodev.utnfrp I/art: Do partial code cache collection, code=40KB, data=62KB
09-24 18:21:51.203 8539-8544/jaodev.utnfrp I/art: After code cache collection, code=40KB, data=62KB
Increasing code cache capacity to 256KB

App crashes when Progress Dialog is open and user changes orientation [duplicate]

This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 5 years ago.
My application has a Progress Dialog for login process and when the orientation is changed while dialog box is open, app crashes.This all works fine, except when screen orientation changes while the dialog is up. At this point the app crashes. I am figuring out this issue from the last 3 nights but not able to get it, please help.
My fragment:
public class Example extends Fragment {
private static final String TAG = "LoginActivity";
private static final int REQUEST_SIGNUP = 0;
Unbinder unbinder;
#BindView(R.id.input_email) EditText _emailText;
#BindView(R.id.input_password) EditText _passwordText;
#BindView(R.id.btn_login) Button _loginButton;
#BindView(R.id.link_signup) TextView _signupLink;
#Override
public void onDestroyView() {
super.onDestroyView();
// unbind the view to free some memory
unbinder.unbind();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.Example, container, false);
unbinder=ButterKnife.bind(this,rootView);
_loginButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
login();
}
});
_signupLink.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
Intent create= new Intent(getActivity(),NewAccount.class);
startActivity(create);
}
});
return rootView;
}
public void login() {
Log.d(TAG, "Login");
if (!validate()) {
onLoginFailed();
return;
}
_loginButton.setEnabled(false);
final ProgressDialog progressDialog = new ProgressDialog(getActivity(),
R.style.AppTheme_Dark_Dialog);
progressDialog.setIndeterminate(true);
progressDialog.setMessage("Authenticating...");
progressDialog.show();
//new YourAsynTask(getActivity()).execute();
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
// TODO: Implement your own authentication logic here.
new android.os.Handler().postDelayed(
new Runnable() {
public void run() {
// On complete call either onLoginSuccess or onLoginFailed
onLoginSuccess();
// onLoginFailed();
progressDialog.dismiss();
}
}, 3000);
}
#Override
public void onPause() {
Log.e("DEBUG", "OnPause of loginFragment1");
super.onPause();
}
public void onLoginSuccess() {
_loginButton.setEnabled(true);
Intent i=new Intent(getActivity(),SuccessLogin.class);
startActivity(i);
}
public void onLoginFailed() {
Toast.makeText(getActivity(), "Login failed", Toast.LENGTH_LONG).show();
_loginButton.setEnabled(true);
}
public boolean validate() {
boolean valid = true;
String email = _emailText.getText().toString();
String password = _passwordText.getText().toString();
if (email.isEmpty() || !android.util.Patterns.EMAIL_ADDRESS.matcher(email).matches()) {
_emailText.setError("enter a valid email address");
valid = false;
} else {
_emailText.setError(null);
}
if (password.isEmpty() || password.length() < 4 || password.length() > 10) {
_passwordText.setError("between 4 and 10 alphanumeric characters");
valid = false;
} else {
_passwordText.setError(null);
}
return valid;
}
Logcat output:
11-16 19:20:10.955 4022-4022/com.example.a1332931.login_application E/WindowManager: android.view.WindowLeaked: Activity com.example.a1332931.login_application.TabActivity has leaked window com.android.internal.policy.PhoneWindow$DecorView{42b6135 V.E...... R......D 0,0-683,232} that was originally added here
at android.view.ViewRootImpl.<init>(ViewRootImpl.java:375)
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:299)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:85)
at android.app.Dialog.show(Dialog.java:319)
at com.example.a1332931.login_application.Example.login(Example.java:156)
at com.example.a1332931.login_application.Example$1.onClick(Example.java:67)
at android.view.View.performClick(View.java:5201)
at android.view.View$PerformClick.run(View.java:21163)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
11-16 19:20:10.957 4022-4095/com.example.a1332931.login_application E/Surface: getSlotFromBufferLocked: unknown buffer: 0xb8aa6c60
11-16 19:20:12.512 4022-4022/com.example.a1332931.login_application E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.a1332931.login_application, PID: 4022
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.Button.setEnabled(boolean)' on a null object reference
at com.example.a1332931.login_application.Example.onLoginSuccess(Example.java:200)
at com.example.a1332931.login_application.Example$3.run(Example.java:168)
at android.os.Handler.handleCallback(Handler.java:746)
at android.os.Handler.dispatchMessage(Handler.java:95)
at android.os.Looper.loop(Looper.java:148)
at android.app.ActivityThread.main(ActivityThread.java:5443)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:728)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:618)
Add this configuration change in your Android manifest activity:
<activity
android:name="YourActivity"
android:configChanges="orientation|keyboardHidden|screenSize"/>

Call method from non-Activity class in Android

I have a Popup window (non-Activity class) that have some buttons. one of them (btn_audio), play or pause sound and it works like a charm.
Now I want to call two method, play() and pause() in my HomeActivity and inside of onStop() method in all of my Activities. it doesn't work, call play() and pause() in other Activity's occur NullPointException.
public class Popup_Menu extends Activity implements OnClickListener {
Button btn_audio;
public static MediaPlayer player; String play_or_pause;
int num_ply, tim_pos; int [] resID;// Audio
SharedPreferences sp;
void showPopup(final Activity context) {
this.context=context;
LinearLayout viewGroup = (LinearLayout) context.findViewById(R.id.popup);
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
layout = layoutInflater.inflate(R.layout.popup_layout_menu, viewGroup);
sp = context.getSharedPreferences("text", MODE_PRIVATE);
btn_audio = (Button) layout.findViewById(R.id.btn_audio); // audio
layout.findViewById(R.id.btn_audio).setOnClickListener(this);
#Override
public void onClick(View whichButtonIsClicked) {
switch (whichButtonIsClicked.getId()) {
case R.id.btn_audio:
if (play_or_pause.equals("play")) {
pause();
} else {
play(context);
}
sp.edit().putString("play_or_pause", play_or_pause).commit(); // save current stat
} ////// close of showPopup()
//define play and pause methods
public void pause() {
player.pause();
btn_audio.setBackgroundResource(R.drawable.icon_audio_pause);
play_or_pause="pause"; // current state is 'pause'
}
public void play(final Context context) {
if(num_ply==9){num_ply=0; }
resID = new int []{ R.raw.tarane,R.raw.toofan,R.raw.shane,R.raw.kharazmi,R.raw.golhaye_khofte,R.raw.rang,R.raw.naghmeh,R.raw.dar_rahe_to,R.raw.emperor};
player=MediaPlayer.create(context,resID[num_ply]);
player.seekTo(tim_pos);
player.start();
btn_audio.setBackgroundResource(R.drawable.icon_audio_play);
play_or_pause="play"; // current state is 'play'
player.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer player) {
tim_pos=0; num_ply++; play(context);
}
});
}
}
and my HomeActivity :
public class HomeActivity extends Activity implements OnClickListener {
Popup_Menu ppp;
#Override
protected void onCreate..............
ppp = new Popup_Menu();
SharedPreferences sp = getSharedPreferences("text", MODE_PRIVATE);
if(sp.getString("play_or_pause", "play").equals("pause")){
ppp.play(getApplicationContext()); // ERROR
} // audio
} /// close of onCreate
#Override
public void onStop() {
super.onStop();
if(play_or_pause.equals("play")){
ppp.tim_pos= ppp.player.getCurrentP
Ok, I decided to use service to resolve this problem and it works well for play(). but when playing, still i can't call pause() method from SoundService because player object is null. I think by creating an object, from SoundService class, (ss in Popup_Menu class) , default constructor put player value to null (when playing and player object wasn't null). and calling player.pause occur error.
How PLEASE can i pause this one_week_friend!!!
public class SoundService extends Service {
MediaPlayer player; int num_ply, tim_pos; int [] resID;
public int onStartCommand(Intent intent, int flags, int startId) {
resID = new int []{ R.raw.tarane,R.raw.toofan,R.raw.shane,R.raw.kharazmi,
R.raw.golhaye_khofte,R.raw.rang,R.raw.naghmeh,R.raw.dar_rahe_to,R.raw.emperor };
player=MediaPlayer.create(this,resID[num_ply]);
play();
return Service.START_FLAG_REDELIVERY;
}
public void play() {
if(num_ply==9){num_ply=0; }
player.seekTo(tim_pos);
player.start();
player.setOnCompletionListener(new OnCompletionListener() {
public void onCompletion(MediaPlayer player) {
tim_pos=0; num_ply++; play();
}
});
}
public void resume(){
player.seekTo(tim_pos);
player.start();
}
public void pause() {
tim_pos= player.getCurrentPosition(); ////// ERROR
player.pause(); ////// ERROR
num_ply++;
}
public IBinder onBind(Intent arg0) {
// TODO Auto-generated method stub
return null;
}
}
And my Popup_Menu class:
#Override
public void onClick(View whichButtonIsClicked) {
switch (whichButtonIsClicked.getId()) {
case R.id.btn_audio:
if (play_or_pause.equals("play")) {
btn_audio.setBackgroundResource(R.drawable.icon_audio_pause);
play_or_pause="pause"; // current state is 'pause'
SoundService ss = new SoundService();
ss.pause(); ////// ERROR
} else {
btn_audio.setBackgroundResource(R.drawable.icon_audio_play);
play_or_pause="play"; // current state is 'play'
Intent sound_Intent = new Intent(context , SoundService.class); // start service
context.startService(sound_Intent);
}
sp.edit().putString("play_or_pause", play_or_pause).commit(); // save current state
break;
LogCat:
08-05 01:03:31.440: E/AndroidRuntime(25356): FATAL EXCEPTION: main
08-05 01:03:31.440: E/AndroidRuntime(25356): java.lang.NullPointerException
08-05 01:03:31.440: E/AndroidRuntime(25356): at com.codegostarNiloo.negar.SoundService.pause(SoundService.java:47)
08-05 01:03:31.440: E/AndroidRuntime(25356): at com.codegostarNiloo.negar.Popup_Menu.onClick(Popup_Menu.java:234)
08-05 01:03:31.440: E/AndroidRuntime(25356): at android.view.View.performClick(View.java:4209)
08-05 01:03:31.440: E/AndroidRuntime(25356): at android.view.View$PerformClick.run(View.java:17457)
08-05 01:03:31.440: E/AndroidRuntime(25356): at android.os.Handler.handleCallback(Handler.java:725)
08-05 01:03:31.440: E/AndroidRuntime(25356): at android.os.Handler.dispatchMessage(Handler.java:92)
08-05 01:03:31.440: E/AndroidRuntime(25356): at android.os.Looper.loop(Looper.java:153)
08-05 01:03:31.440: E/AndroidRuntime(25356): at android.app.ActivityThread.main(ActivityThread.java:5341)
08-05 01:03:31.440: E/AndroidRuntime(25356): at java.lang.reflect.Method.invokeNative(Native Method)
08-05 01:03:31.440: E/AndroidRuntime(25356): at java.lang.reflect.Method.invoke(Method.java:511)
08-05 01:03:31.440: E/AndroidRuntime(25356): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:929)
08-05 01:03:31.440: E/AndroidRuntime(25356): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:696)
08-05 01:03:31.440: E/AndroidRuntime(25356): at dalvik.system.NativeStart.main(Native Method)
08-05 01:03:32.066: D/dalvikvm(25356): threadid=11: interp stack at 0x5f1c9000
First, off, don't extend an Activity if it's a non Activity, as you claim, then passing a Context is preferred over an Activity
Secondly, there is a class called DialogFragment that is intended to be used as a popup dialog
I think you are looking for something like the following, though
public class Popup_Menu implements OnClickListener {
Button btn_audio;
public MediaPlayer player;
String play_or_pause;
int num_ply, tim_pos;
int [] resID;// Audio
SharedPreferences sp;
Context context ;
public Popup_Menu(final Context context) {
this.context= context;
sp = this.context.getSharedPreferences("text", Context.MODE_PRIVATE);
// LinearLayout viewGroup = (LinearLayout) view.findViewById(R.id.popup);
LayoutInflater layoutInflater = LayoutInflater.from(this.context);
layout = layoutInflater.inflate(R.layout.popup_layout_menu, viewGroup);
btn_audio = (Button) layout.findViewById(R.id.btn_audio); // audio
btn_audio.setOnClickListener(this);
}
You can now create a new Popup_Menu(HomeActivity.this)
Yeah...!!! Done. It now working.it doesn't need to create new object. I must change modifire of (object)player and pause() methode and everything in it, to STATIC. So righte now i can access all objects and variables.
Thanks cricket_007...

NoClassDefFoundError Exception when launching app in GenyMotion emulator

I wanted to test my code on another device than my physical one, so I launched the app in GenyMotion emulator with a Samsung Galaxy S3 (API 18), but it keeps throwing a NoClassDefFoundError Exception in my class "SlidingMenuUtil" (a customized drawer menu) which is called on startup by my MainActivity.
Here is code from my onCreate in MainActivity:
#Bind(R.id.viewContentFullScreen) RelativeLayout viewContentFullScreen;
#Bind(R.id.viewContentTopBar) RelativeLayout viewContentTopBar;
#Bind(R.id.topBarWrapper) RelativeLayout topbarView;
private ViewContainer viewContainer;
private SlidingMenuUtil leftMenu;
private Bundle bundle;
private MessageHandler messageHandler;
private GoBackFunction currentGoBackFunction;
private CallbackManager callbackManager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bundle = savedInstanceState;
setContentView(R.layout.activity_main);
leftMenu = new SlidingMenuUtil(this, SlidingMenuUtil.MenuType.LEFT, R.layout.drawer_menu, (int)(LayoutUtil.getScreenWidth(this) * 0.75), false);
populateMenu();
ButterKnife.bind(this);
messageHandler = new MessageHandler(this, findViewById(R.id.spinner));
FacebookSdk.sdkInitialize(getApplicationContext());
callbackManager = CallbackManager.Factory.create();
}
The problem occurs in the SlidingMenuUtil class on line: 67. Here is the constructor for the class:
public SlidingMenuUtil(Activity activity, MenuType menuType, int menuLayout, int shownMenuWidth, boolean fadeEffectOn) {
this.activity = activity;
this.menuType = menuType;
this.shownMenuWidth = shownMenuWidth;
this.fadeEffectOn = fadeEffectOn;
this.screenWidth = LayoutUtil.getScreenWidth(activity);
this.rootView = (ViewGroup)((ViewGroup)activity.findViewById(android.R.id.content)).getChildAt(0);
this.activityWrapper = new RelativeLayout(activity);
this.activityWrapper.setLayoutParams(this.rootView.getLayoutParams());
this.overlay = new RelativeLayout(activity);
this.overlay.setLayoutParams(new ViewGroup.LayoutParams(-1, -1));
this.overlay.setBackgroundColor(Color.parseColor("#000000"));
this.overlay.setAlpha(0.0F);
this.overlay.setVisibility(View.GONE);
this.overlay.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (menuOpen) {
toggle(new ToggleMenu() {
#Override
public void animationDone() {
}
});
}
}
});
this.rootView.addView(this.overlay);
this.menu = (LinearLayout)activity.getLayoutInflater().inflate(menuLayout, (ViewGroup) null, false);
this.menu.setLayoutParams(new ViewGroup.LayoutParams(shownMenuWidth, -1));
if (menuType == MenuType.LEFT) {
this.menu.setTranslationX((float)(-shownMenuWidth));
} else {
this.menu.setTranslationX((float)(screenWidth));
}
this.rootView.addView(this.menu);
this.menuOpen = false;
}
lin 67 is:
this.overlay.setOnClickListener(new View.OnClickListener() {
As mentioned before the problem only occurs in the emulator.
Here is the log:
812-812/? E/AndroidRuntime﹕ FATAL EXCEPTION: main
java.lang.NoClassDefFoundError: nightout.dk.nightoutandroid.utils.SlidingMenuUtil$1
at nightout.dk.nightoutandroid.utils.SlidingMenuUtil.<init>(SlidingMenuUtil.java:67)
at nightout.dk.nightoutandroid.MainActivity.onCreate(MainActivity.java:40)
at android.app.Activity.performCreate(Activity.java:5133)
at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1087)
at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2175)
at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2261)
at android.app.ActivityThread.access$600(ActivityThread.java:141)
at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1256)
at android.os.Handler.dispatchMessage(Handler.java:99)
at android.os.Looper.loop(Looper.java:137)
at android.app.ActivityThread.main(ActivityThread.java:5103)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:525)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
at dalvik.system.NativeStart.main(Native Method)
I hope somone can help me out.
Any help will be gratly appreciated

Start activity from service isn't working (Android)

I created an overlay "always on top button", which is a service HUD, and I can't start an activity screen from there, it gives the error: "Unfortunately App has stopped". In the beginning, all I used to know if there was any TouchEventwas a toast, and that toast was created, but it was created several times, so I don't know if it gives that error because this code, which is on TouchEvent body , is repeated several times too.
here is my code:
public class HUD extends Service implements OnClickListener, OnTouchListener, OnLongClickListener {
Button mButton;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
//mView = new HUDView(this);
mButton = new Button(this);
mButton.setId(1);
mButton.setText("Button");
mButton.setClickable(true);
mButton.setOnTouchListener(this);
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.OPAQUE);
params.gravity = Gravity.LEFT | Gravity.TOP;
params.setTitle("Load Average");
WindowManager wm = (WindowManager) getSystemService(WINDOW_SERVICE);
wm.addView(mButton, params);
}
#Override
public void onDestroy() {
super.onDestroy();
if(mButton != null)
{
((WindowManager) getSystemService(WINDOW_SERVICE)).removeView(mButton);
mButton = null;
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getX()<mButton.getWidth() & event.getY()>0)
{
Toast.makeText(this,"Overlay button event", Toast.LENGTH_SHORT).show(); //this my toast
Intent i = new Intent(); //this is my new acivity (intent)
i.setClass(HUD.this, screen.class);
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(i);
HUD.this.stopSelf();
}
return false;
}
#Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
Toast.makeText(this,"Click", Toast.LENGTH_SHORT).show();
}
#Override
public boolean onLongClick(View v) {
// TODO Auto-generated method stub
System.exit(1);
return false;
}
}
So my question is, is this code on TouchEvent body being repeated several times? If it is, is that the cause of the error?
log cat:
07-20 22:11:06.962: I/Choreographer(1620): Skipped 52 frames! The application may be doing too much work on its main thread.
07-20 22:11:08.062: D/AndroidRuntime(1620): Shutting down VM
07-20 22:11:08.062: W/dalvikvm(1620): threadid=1: thread exiting with uncaught exception (group=0x40a71930)
07-20 22:11:08.132: E/AndroidRuntime(1620): FATAL EXCEPTION: main
07-20 22:11:08.132: E/AndroidRuntime(1620): android.app.SuperNotCalledException: Activity {com.example.screenshot/com.example.screenshot.screen} did not call through to super.onCreate()
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2146)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread.access$600(ActivityThread.java:141)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.os.Handler.dispatchMessage(Handler.java:99)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.os.Looper.loop(Looper.java:137)
07-20 22:11:08.132: E/AndroidRuntime(1620): at android.app.ActivityThread.main(ActivityThread.java:5041)
07-20 22:11:08.132: E/AndroidRuntime(1620): at java.lang.reflect.Method.invokeNative(Native Method)
07-20 22:11:08.132: E/AndroidRuntime(1620): at java.lang.reflect.Method.invoke(Method.java:511)
07-20 22:11:08.132: E/AndroidRuntime(1620): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)
07-20 22:11:08.132: E/AndroidRuntime(1620): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)
07-20 22:11:08.132: E/AndroidRuntime(1620): at dalvik.system.NativeStart.main(Native Method)
screen.java:
public class screen extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
Toast.makeText(getApplicationContext(), "Made it", 0).show();
finish();
}
}
See android start activity from service
Intent i= new Intent(getBaseContext(), screen.class);
i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
getApplication().startActivity(i);
You error seems to be inside screen activity. There are many thread which might help to figure out the error that you are getting for the activity:
Error in Android "SuperNotCalledException:Activity did not call through to super.OnCreate()"
android.app.SuperNotCalledException: Activity did not call through to super.onStop()
Update
The error is because you haven't called: super.onCreate(savedInstanceState); in your screen activity's onCreate(). That should be the first thing to be called in onCreate(). Do something like this:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//.... other stuff
}
Hope this helps.

Categories

Resources