here is the code of the class which i created which extends MainActivity and how can i call this from MainActivity?
I'm trying to figure out where I went wrong on referencing my surface view class, not my view. I only did the view as an example. Here is my main class:
import android.app.Activity;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
public class SurfaceViewExample extends Activity implements OnTouchListener{
OurView v;
Bitmap ball;
float x,y;
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
v=new OurView(this);
v.setOnTouchListener(this);
ball=BitmapFactory.decodeResource(getResources(),R.drawable.tennis_ball);
x = y = 0;
setContentView(v);
}
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
v.resume();
}
public class OurView extends SurfaceView implements Runnable{
Thread t;
SurfaceHolder holder;
boolean isItOk=false;
public OurView(Context context) {
super(context);
// TODO Auto-generated constructor stub
holder=getHolder();
}
public void run() {
// TODO Auto-generated method stub
while( isItOk ==true)
{
//drawing
if(holder.getSurface().isValid()) {
continue;
}
Canvas c=holder.lockCanvas();
c.drawARGB(255,150,150,10);
c.drawBitmap(ball, x+(ball.getWidth()/4), y+(ball.getHeight()), null);
holder.unlockCanvasAndPost(c);
}
}
public void pause()
{
isItOk=false;
while(true) {
try {
t.join();
}catch(InterruptedException e) {
e.printStackTrace();
}
break;
}
}
public void resume()
{
isItOk=true;
t=new Thread(this);
t.start();
}
}
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
}
The much i got is that you want to go SurfaceViewExample from your main activity for that you need to use intent on button click like
Intent i = new Intent(this, SurfaceViewExample.class);
startActivity(i) ;
and you have to add a permission in menifest to got to that activity like
<activity android:enabled="true" android:name="SurfaceViewExample" />
and you can see these links also
Calling one Activity from another in Android
http://developer.android.com/reference/android/content/Intent.html
Related
I have searched a lot and tried nearly everything and nothing worked for me .
I just want to disable the home and the menu buttons.
here is the LockScreenActivity.java
import android.app.ActionBar;
import android.app.Activity;
import android.app.KeyguardManager;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.widget.DrawerLayout;
import android.telephony.PhoneStateListener;
import android.telephony.TelephonyManager;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MenuItem;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
import com.mehuljoisar.lockscreen.utils.LockscreenService;
import com.mehuljoisar.lockscreen.utils.LockscreenUtils;
public class LockScreenActivity extends Activity implements
LockscreenUtils.OnLockStatusChangedListener {
// User-interface
private Button btnUnlock;
private Button button1;
private Button button2;
private Button button3;
private Button button4;
private Button button5;
private Button button6;
private Button button7;
private Button button8;
private Button button9;
private ImageButton button10;
private TextView textView;
private RelativeLayout myView;
// Member variables
private LockscreenUtils mLockscreenUtils;
// Set appropriate flags to make the screen appear over the keyguard
#Override
public void onAttachedToWindow() {
this.getWindow().setType(
WindowManager.LayoutParams.TYPE_KEYGUARD_DIALOG);
this.getWindow().addFlags(
WindowManager.LayoutParams.FLAG_FULLSCREEN
| WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED
| WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON
| WindowManager.LayoutParams.FLAG_DISMISS_KEYGUARD
);
super.onAttachedToWindow();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
setContentView(R.layout.activity_lockscreen);
init();
button1=(Button)findViewById(R.id.button1);
button2=(Button)findViewById(R.id.button2);
button3=(Button)findViewById(R.id.button3);
button4=(Button)findViewById(R.id.button4);
button5=(Button)findViewById(R.id.button5);
button6=(Button)findViewById(R.id.button6);
button7=(Button)findViewById(R.id.button7);
button8=(Button)findViewById(R.id.button8);
button9=(Button)findViewById(R.id.button9);
button10=(ImageButton)findViewById(R.id.button10);
textView=(TextView)findViewById(R.id.textView1);
myView=(RelativeLayout)findViewById(R.id.layout);
// Ask the System Bar to hide
myView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_HIDE_NAVIGATION);
button1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"1");
}
});
button2.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"8");
}
});
button3.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"5");
}
});
button4.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"2");
}
});
button5.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"7");
}
});
button6.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"4");
}
});
button7.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"9");
}
});
button8.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"3");
}
});
button9.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
textView.setText(textView.getText().toString()+"6");
}
});
button10.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(textView.getText().toString().length()>0)
// TODO Auto-generated method stub
textView.setText(textView.getText().toString().substring(0, textView.getText().toString().length()-1));
}
});
// unlock screen in case of app get killed by system
if (getIntent() != null && getIntent().hasExtra("kill")
&& getIntent().getExtras().getInt("kill") == 1) {
enableKeyguard();
unlockHomeButton();
} else {
try {
// disable keyguard
disableKeyguard();
// lock home button
lockHomeButton();
// start service for observing intents
startService(new Intent(this, LockscreenService.class));
// listen the events get fired during the call
StateListener phoneStateListener = new StateListener();
TelephonyManager telephonyManager = (TelephonyManager) getSystemService(TELEPHONY_SERVICE);
telephonyManager.listen(phoneStateListener,
PhoneStateListener.LISTEN_CALL_STATE);
} catch (Exception e) {
}
}
}
private void init() {
mLockscreenUtils = new LockscreenUtils();
btnUnlock = (Button) findViewById(R.id.btnUnlock);
btnUnlock.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// unlock home button and then screen on button press
if(textView.getText().toString().equals("1234"))
unlockHomeButton();
}
});
}
// Handle events of calls and unlock screen if necessary
private class StateListener extends PhoneStateListener {
#Override
public void onCallStateChanged(int state, String incomingNumber) {
super.onCallStateChanged(state, incomingNumber);
switch (state) {
case TelephonyManager.CALL_STATE_RINGING:
unlockHomeButton();
break;
case TelephonyManager.CALL_STATE_OFFHOOK:
break;
case TelephonyManager.CALL_STATE_IDLE:
break;
}
}
};
// Don't finish Activity on Back press
#Override
public void onBackPressed() {
return;
}
// Handle button clicks
#Override
public boolean onKeyDown(int keyCode, android.view.KeyEvent event) {
if ((keyCode == KeyEvent.KEYCODE_VOLUME_DOWN)
|| (keyCode == KeyEvent.KEYCODE_POWER)
|| (keyCode == KeyEvent.KEYCODE_VOLUME_UP)
|| (keyCode == KeyEvent.KEYCODE_CAMERA)) {
return true;
}
if ((keyCode == KeyEvent.KEYCODE_HOME)) {
return false;
}
return true;
}
// handle the key press events here itself
public boolean dispatchKeyEvent(KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_UP
|| (event.getKeyCode() == KeyEvent.KEYCODE_VOLUME_DOWN)
|| (event.getKeyCode() == KeyEvent.KEYCODE_POWER)) {
return false;
}
if ((event.getKeyCode() == KeyEvent.KEYCODE_HOME)) {
return false;
}
return false;
}
// Lock home button
public void lockHomeButton() {
mLockscreenUtils.lock(LockScreenActivity.this);
}
// Unlock home button and wait for its callback
public void unlockHomeButton() {
mLockscreenUtils.unlock();
}
// Simply unlock device when home button is successfully unlocked
#Override
public void onLockStatusChanged(boolean isLocked) {
if (!isLocked) {
unlockDevice();
}
}
#Override
protected void onStop() {
super.onStop();
unlockHomeButton();
}
#SuppressWarnings("deprecation")
private void disableKeyguard() {
KeyguardManager mKM = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock mKL = mKM.newKeyguardLock("IN");
mKL.disableKeyguard();
}
#SuppressWarnings("deprecation")
private void enableKeyguard() {
KeyguardManager mKM = (KeyguardManager) getSystemService(KEYGUARD_SERVICE);
KeyguardManager.KeyguardLock mKL = mKM.newKeyguardLock("IN");
mKL.reenableKeyguard();
}
//Simply unlock device by finishing the activity
private void unlockDevice()
{
finish();
}
}
and here is my LockscreenIntentReceiver.java
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.view.View;
import android.widget.RelativeLayout;
import com.mehuljoisar.lockscreen.LockScreenActivity;
import com.mehuljoisar.lockscreen.R;
public class LockscreenIntentReceiver extends BroadcastReceiver {
// Handle actions and display Lockscreen
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction().equals(Intent.ACTION_SCREEN_OFF)
|| intent.getAction().equals(Intent.ACTION_SCREEN_ON)
|| intent.getAction().equals(Intent.ACTION_BOOT_COMPLETED)) {
start_lockscreen(context);
}
}
// Display lock screen
private void start_lockscreen(Context context) {
Intent mIntent = new Intent(context, LockScreenActivity.class);
mIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(mIntent);
}
}
and here is my LockscreenService.java
import android.app.Notification;
import android.app.Service;
import android.content.BroadcastReceiver;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.os.IBinder;
import android.provider.SyncStateContract.Constants;
import android.support.v4.app.NotificationCompat;
import com.mehuljoisar.lockscreen.R;
public class LockscreenService extends Service {
private BroadcastReceiver mReceiver;
#Override
public IBinder onBind(Intent intent) {
return null;
}
#Override
public void onCreate() {
super.onCreate();
}
// Register for Lockscreen event intents
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
IntentFilter filter = new IntentFilter(Intent.ACTION_SCREEN_ON);
filter.addAction(Intent.ACTION_SCREEN_OFF);
mReceiver = new LockscreenIntentReceiver();
registerReceiver(mReceiver, filter);
startForeground();
return START_STICKY;
}
// Run service in foreground so it is less likely to be killed by system
private void startForeground() {
Notification notification = new NotificationCompat.Builder(this)
.setContentTitle(getResources().getString(R.string.app_name))
.setTicker(getResources().getString(R.string.app_name))
.setContentText("Running")
.setSmallIcon(R.drawable.ic_launcher)
.setContentIntent(null)
.setOngoing(true)
.build();
startForeground(9999,notification);
}
// Unregister receiver
#Override
public void onDestroy() {
super.onDestroy();
unregisterReceiver(mReceiver);
}
}
and here is my LockscreenUtils.java
import android.app.ActionBar;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.KeyguardManager;
import android.content.Context;
import android.support.v4.widget.DrawerLayout;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.view.WindowManager.LayoutParams;
import android.widget.RelativeLayout;
import com.mehuljoisar.lockscreen.R;
public class LockscreenUtils {
// Member variables
private OverlayDialog mOverlayDialog;
private OnLockStatusChangedListener mLockStatusChangedListener;
// Interface to communicate with owner activity
public interface OnLockStatusChangedListener
{
public void onLockStatusChanged(boolean isLocked);
}
// Reset the variables
public LockscreenUtils() {
reset();
}
// Display overlay dialog with a view to prevent home button click
public void lock(Activity activity) {
if (mOverlayDialog == null) {
mOverlayDialog = new OverlayDialog(activity);
mOverlayDialog.show();
mLockStatusChangedListener = (OnLockStatusChangedListener) activity;
}
}
// Reset variables
public void reset() {
if (mOverlayDialog != null) {
mOverlayDialog.dismiss();
mOverlayDialog = null;
}
}
// Unlock the home button and give callback to unlock the screen
public void unlock() {
if (mOverlayDialog != null) {
mOverlayDialog.dismiss();
mOverlayDialog = null;
if(mLockStatusChangedListener!=null)
{
mLockStatusChangedListener.onLockStatusChanged(false);
}
}
}
// Create overlay dialog for lockedscreen to disable hardware buttons
private static class OverlayDialog extends AlertDialog {
public OverlayDialog(Activity activity) {
super(activity, R.style.OverlayDialog);
WindowManager.LayoutParams params = getWindow().getAttributes();
getActionBar().setDisplayHomeAsUpEnabled(false);
params.type = LayoutParams.TYPE_SYSTEM_ERROR;
params.dimAmount = 0.0F;
params.width = 0;
params.height = 0;
params.gravity = Gravity.BOTTOM;
getWindow().setAttributes(params);
getWindow().setFlags(LayoutParams.FLAG_SHOW_WHEN_LOCKED | LayoutParams.FLAG_NOT_TOUCH_MODAL,
0xffffff);
setOwnerActivity(activity);
setCancelable(false);
}
// consume touch events
public final boolean dispatchTouchEvent(MotionEvent motionevent) {
return true;
}
}
}
last but not least .. here is my manifest
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.mehuljoisar.lockscreen"
android:versionCode="3"
android:versionName="1.2" >
<uses-sdk android:minSdkVersion="11" />
<uses-permission android:name="android.permission.DISABLE_KEYGUARD" />
<uses-permission android:name="android.permission.WAKE_LOCK" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.READ_PHONE_STATE" />
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
<application
android:icon="#drawable/ic_launcher"
android:label="#string/app_name" >
<activity
android:name="com.mehuljoisar.lockscreen.LockScreenActivity"
android:excludeFromRecents="true"
android:label="#string/app_name"
android:launchMode="singleTask"
android:screenOrientation="portrait"
android:theme="#android:style/Theme.Holo.NoActionBar.Fullscreen" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
<service android:name=".utils.LockscreenService" >
</service>
<receiver
android:name=".utils.LockscreenIntentReceiver"
android:enabled="true" >
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED" />
</intent-filter>
</receiver>
</application>
</manifest>
Use below method for hiding home/menu button:
getActionBar().setDisplayHomeAsUpEnabled(false)
Or use
getActionBar().setHomeButtonEnabled (false)
to disable interaction with the home/up affordance.
I am trying to create my first android game (in eclipse) and I cannot seem to get OnTouchListner to work, mostly because I don't know how or where to create it. I am trying to figure out where someone taps the screen. Can someone please tell me how and where to create the OnTouchListner!
Activity class:
package com.gregsapps.fallingbird;
import android.app.Activity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class Game extends Activity implements OnTouchListener{
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(new GameView(this));
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.){
System.out.println("TOUCH");
}
return false;
}
}
View class:
package com.gregsapps.fallingbird;
import android.R;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.view.MotionEvent;
import android.view.View;
public class GameView extends View{
private Bird bird;
private boolean runOnce = false;
private Context context;
public GameView(Context context) {
super(context);
this.context = context;
this.setDrawingCacheEnabled(true);
// TODO add setup code
}
protected void onDraw(Canvas canvas){
update(canvas);
//TODO add drawing code
this.buildDrawingCache();
//bird.canvasImage = this.getDrawingCache(true);
canvas.drawBitmap(bird.image, bird.x, bird.y, null);
System.out.println("drawing");
invalidate();
}
private void update(Canvas canvas){
//TODO add code to update stuff
if(runOnce == false){
bird = new Bird(canvas, com.gregsapps.fallingbird.R.drawable.bird, context);
runOnce = true;
}
bird.move();
}
}
Implement it like this :-
public class Game extends Activity implements OnTouchListener{
GameView gv;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
gv = new GameView(this);
setContentView(gv);
gv.setOnTouchListener(this);
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
if(event.getAction() == MotionEvent.ACTION_DOWN){
int x = event.getX();
int y = event.getY();
System.out.println("Touched view at X: " + X + " Y: " + Y );
}
return false;
}
}
You should just be able to set it on the view you create:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
GameView gv = new GameView(this);
setContentView(gv);
// set the touch listener for the view
gv.setOnTouchListener(this);
}
i made three activities for a game i want to go from 1st to 2nd to 3rd and then go 1st 2nd 3rd again but i got confused with the whole intent thing tried all kind of combinations but for some reason i stuck always with a problem currently it goes from 1st to 2nd to 3rd to 1st and when it supposed to lunch 2nd it exits from the whole app
//1st activity
Intent discoverintent = new Intent(getBaseContext(), discoverstring.class);
//discoverintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(discoverintent);
//2nd activity
Intent MainIntent = new Intent(getBaseContext(), learningword.class);
//MainIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
MainIntent.putExtra("text", text);
MainIntent.putExtra("speakeronoff", Integer.toString(speakeronoff));
MainIntent.putExtra("previous", Integer.toString(previous));
startActivity(MainIntent);
and the 3rd activity just uses finish
package self.yanfaingold.talkgame;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.view.View.OnTouchListener;
import android.view.Window;
import android.view.WindowManager;
#SuppressLint("NewApi") public class savewords extends Activity implements OnTouchListener {
OurView v;
//Intent secondintent;
Canvas c;
int cheight,cwidth,loop=0;
Bitmap notalk,notalkscaled,bittalk;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
v=new OurView(this);
v.setOnTouchListener(this);
//Remove title bar
requestWindowFeature(Window.FEATURE_NO_TITLE);
//Remove notification bar
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(v);
notalk=BitmapFactory.decodeResource(getResources(), R.drawable.nottalk);
// bittalk=BitmapFactory.decodeResource(getResources(), R.drawable.talkmid);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
v.pause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
v.resume();
}
public class OurView extends SurfaceView implements Runnable {
Thread t=null;
SurfaceHolder holder;
boolean isItOK=false;
public OurView(Context context) {
super(context);
// TODO Auto-generated constructor stub
holder=getHolder();
}
public void run(){
while(isItOK){
if(!holder.getSurface().isValid()){
continue;
}
c=holder.lockCanvas();
cheight=c.getHeight();
cwidth=c.getWidth();
scale();
drawing(c);
holder.unlockCanvasAndPost(c);
}
}
private void scale() {
// TODO Auto-generated method stub
if(loop==0)
notalkscaled=Bitmap.createScaledBitmap(notalk,(int)(cwidth),(int)(cheight), false);
}
protected void drawing(Canvas canvas){
//canvas.drawARGB(255, 255, 255, 255);
canvas.drawBitmap(notalkscaled,0,0, null);
if(loop>500){
loop=0;
wannalearnaword();
}
loop++;
}
private void wannalearnaword() {
// TODO Auto-generated method stub
//1st activity
Intent secondintent = new Intent(getApplicationContext(), discoverstring.class);
secondintent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(secondintent);
}
public void pause(){
isItOK=false;
while(true){
try {
t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
t=null;
}
public void resume(){
isItOK=true;
t=new Thread(this);
t.start();
}
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
switch(event.getAction())
{
case MotionEvent.ACTION_DOWN:
break;
case MotionEvent.ACTION_UP:
break;
case MotionEvent.ACTION_MOVE:
break;
}
return true;
}
}
I don't know whats going wrong with my app i followed so many tutorials, any hint/help/advise would be appreciated, I am new on android. i am getting error as in onserviceregistrationfailed function of listner.
package com.example.ravinetworkapplication;
import java.io.IOException;
import java.net.ServerSocket;
import java.security.PublicKey;
import java.util.ArrayList;
import java.util.List;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.app.ActionBar;
import android.support.v4.app.Fragment;
import android.content.Context;
import android.content.pm.ServiceInfo;
import android.net.nsd.NsdManager;
import android.net.nsd.NsdManager.DiscoveryListener;
import android.net.nsd.NsdServiceInfo;
import android.net.nsd.NsdManager.RegistrationListener;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.Toast;
import android.os.Build;
public class MainActivity extends ActionBarActivity {
NsdManager mNsdManager;
Context context;
NsdManager.DiscoveryListener mDiscoveryListner=null;
NsdManager.RegistrationListener mRegistrationListener=null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
if (savedInstanceState == null) {
getSupportFragmentManager().beginTransaction()
.add(R.id.container, new PlaceholderFragment()).commit();
}
mNsdManager= (NsdManager) this.getSystemService(Context.NSD_SERVICE);
final ServerSocket mServerSocket;
final ArrayList<String> listName = new ArrayList<String>();
Integer localPort = 0;
final ListView list = (ListView) findViewById(R.id.listView1);
listName.add("arunima");
listName.add("abhishek");
final ArrayAdapter<String> adapter = new ArrayAdapter<String>(this , android.R.layout.simple_list_item_1,listName);
list.setAdapter(adapter);
try {
mServerSocket = new ServerSocket(0);
localPort = mServerSocket.getLocalPort();
mServerSocket.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
mRegistrationListener = new NsdManager.RegistrationListener() {
#Override
public void onUnregistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
// TODO Auto-generated method stub
}
#Override
public void onServiceUnregistered(NsdServiceInfo serviceInfo) {
// TODO Auto-generated method stub
}
#Override
public void onServiceRegistered(NsdServiceInfo serviceInfo) {
// TODO Auto-generated method stub
Log.v("service registrd", "i am on folks");
Toast.makeText(getApplicationContext(), "Registerd", Toast.LENGTH_LONG).show();
}
#Override
public void onRegistrationFailed(NsdServiceInfo serviceInfo, int errorCode) {
// TODO Auto-generated method stub
Log.v("service registration fail", "can not register service kumar ravi");
}
};
mDiscoveryListner = new NsdManager.DiscoveryListener() {
#Override
public void onStopDiscoveryFailed(String serviceType, int errorCode) {
// TODO Auto-generated method stub
Log.v("cannot stop service", "service discovery failed");
}
#Override
public void onStartDiscoveryFailed(String serviceType, int errorCode) {
// TODO Auto-generated method stub
Log.v("can not start", "Can not start discovery kumar ravi "+errorCode);
}
#Override
public void onServiceLost(NsdServiceInfo service) {
// TODO Auto-generated method stub
}
#Override
public void onServiceFound(NsdServiceInfo service) {
// TODO Auto-generated method stub
Log.v("service found", "we found the service");
if(!service.getServiceType().equals("_myapp.tcp.")){
}
else if(service.getServiceName().equals("kumar")){
}
else {
listName.add(service.getServiceName());
adapter.notifyDataSetChanged();
list.setAdapter(adapter);
Toast.makeText(getApplicationContext(), "Finally found the service "+service.getServiceName(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onDiscoveryStopped(String serviceType) {
// TODO Auto-generated method stub
}
#Override
public void onDiscoveryStarted(String serviceType) {
// TODO Auto-generated method stub
Log.v("Service Discovery Started", "Searching of Service Discovery");
}
};
Log.v("registerd port", localPort.toString());
final NsdServiceInfo serviceInfo = new NsdServiceInfo();
serviceInfo.setPort(localPort);
serviceInfo.setServiceName("kumar");
serviceInfo.setServiceType("_myapp.tcp.");
//mNsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
Button startBroadcast = (Button) findViewById(R.id.button1);
Button startListen = (Button) findViewById(R.id.button2);
startBroadcast.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mNsdManager.registerService(serviceInfo, NsdManager.PROTOCOL_DNS_SD, mRegistrationListener);
}
});
startListen.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
mNsdManager.discoverServices("_myapp.tcp.", NsdManager.PROTOCOL_DNS_SD, mDiscoveryListner);
}
});
}
#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;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
try{
mNsdManager.unregisterService(mRegistrationListener);
mNsdManager.stopServiceDiscovery(mDiscoveryListner);
Log.v("Stopped", "Scanning stopped"); }
catch(Exception e){
Log.v("some error in unregistring service", e.toString());
}
}
/**
* A placeholder fragment containing a simple view.
*/
public static class PlaceholderFragment extends Fragment {
public PlaceholderFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container,
false);
return rootView;
}
}
}
I am using a custom view to draw a game content and i use a button from xml layout to enable or disable the drawing of a specific content(rectangle) using separate thread.I managed to have the thread running but postInvalidate() method that i use is being ignored.I tried using setWillNotDraw(false) too.It isn't working.I've condensed my code,to be specific on which part of the code i have this problem.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/frm"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.temp.Cview
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent" >
<Button
android:id="#+id/bMineDetector"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:text="Lock" />
</RelativeLayout>
</FrameLayout>
And this is my MainActivity.java
package com.example.temp;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
public class MainActivity extends Activity implements OnClickListener{
Button b;
Boolean lock=false;
Cview v;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
v=new Cview(this,null);
setContentView(R.layout.activity_main);
initialize();
}
private void initialize() {
// TODO Auto-generated method stub
b=(Button) findViewById(R.id.bMineDetector);
lock=false;
b.setOnClickListener(this);
}
public void updateViewStart(){
v.onStart();
}
public void updateViewStop(){
v.onPause();
}
#Override
protected void onPause() {
// TODO Auto-generated method stub
super.onPause();
if(v.isRunning==true)
v.onPause();
}
#Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.bMineDetector:
if(lock==false){
lock=true;
updateViewStart();
b.setText("UnLock");
}else{
lock=false;
updateViewStop();
b.setText("lock");
}
break;
}
}
}
In the above class i set a onClickListener that helps to start or stop a separate thread based on the state of the button.Here is my custom view where i handle touch events and also create this thread.
Cview.java
package com.example.temp;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.util.AttributeSet;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
public class Cview extends View implements OnTouchListener,Runnable{
Boolean isRunning=false,isLockMode=false;
Context gameContext;
Thread myThread=null;
public Cview(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
gameContext=context;
}
#Override
protected void onDraw(Canvas canvas) {
// TODO Auto-generated method stub
super.onDraw(canvas);
Log.d("INVALIDATE", "Invalidating");
isLockMode=((MainActivity)gameContext).lock;
if(isLockMode==true){
canvas.drawRect(100, 100, 300, 300, null);
//invalidate();
}
}
#Override
public void run() {
// TODO Auto-generated method stub
while(isRunning){
try {
Thread.sleep(50);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
isLockMode=((MainActivity)gameContext).lock;
this.postInvalidate();
Log.d("THREAD", "isRunning="+isRunning+";;isLockMode="+isLockMode);
}
}
void onStart(){
isRunning=true;
myThread=new Thread(this);
myThread.start();
//Log.d("INVALIDATE", "onStart");
//postInvalidate();
}
void onPause(){
isRunning=false;
while(true){
try {
myThread.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
break;
}
myThread=null;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return true;
}
}
Please anyone help me with this.I need the canvas to be redrawn once the run method is being executed.Ive been thinking about this for months and I'm new to programming too.So please guide me and suggest me if there is any other better method to do what i need.Thank you.
As explained in What is the difference between Android's invalidate() and postInvalidate() methods?, there might be some problems when postInvalidate is used from other threads.
I haven't tested this and it's not really nice, but it could help you (instead of this.postInvalidate();)
((MainActivity) gameContext).runOnUiThread(new Runnable() {
#Override
public void run() {
Cview.this.invalidate();
}
});
I just ran into the exact same issue.
The fix for me was to assign the custom view using
findViewById() in onCreate(), instead of calling the constructor.
Add
android:id="#+id/custom_view"
to your XML, and
v = (Cview) findViewById(R.id.custom_view);
to your onCreate() function (and remove the constructor call).
Do this after calling setContentView().
Android has gazillions of silent failure modes like this.