RelativeLayout layout = new RelativeLayout(this);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
View gameView = initializeForView(new MainGame(), config);
layout.addView(gameView);
adView = new AdView(this);
adView.setAdListener(new AdListener() {
#Override
public void onAdLoaded() {
System.out.println("LOAD");
}
});
adView.setAdSize(AdSize.SMART_BANNER);
adView.setAdUnitId("ca-app-xxx-xxxxxxxxxx/xxxxxxxxxx");
AdRequest.Builder builder = new AdRequest.Builder();
RelativeLayout.LayoutParams adParams = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.WRAP_CONTENT,
RelativeLayout.LayoutParams.WRAP_CONTENT
);
layout.addView(adView, adParams);
adView.loadAd(builder.build());
setContentView(layout);
Nothing is shown, no ad, why,
I added also in build.gradle (Project:projectN)
compile "com.google.android.gms:play-services-ads:$admobVersion"
Using ubuntu 16.04, android-studio
Add AdMob Ads without Firebase :
Put these lines inside build.gradle of android module.
dependencies {
compile 'com.google.android.gms:play-services-ads:10.2.4'
}
Add permission in AndoidManifest.xml file
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
Inside <application tag add Activity if want to use Interstitial Ads
<meta-data android:name="com.google.android.gms.version"
android:value="#integer/google_play_services_version" />
<activity android:name="com.google.android.gms.ads.AdActivity"
android:configChanges="keyboard|keyboardHidden|orientation|screenLayout|uiMode|screenSize|smallestScreenSize"
android:theme="#android:style/Theme.Translucent" />
AndroidLauncher class.
public class AndroidLauncher extends AndroidApplication {
private static final String adUnitId="ca-app-pub-xxxxxxxxxxxxxxxxxxxxx";
private AdView adView;
#Override
protected void onCreate (Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
AndroidApplicationConfiguration config = new AndroidApplicationConfiguration();
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
layout.setLayoutParams(params);
View gameView=initializeForView(new MyGdxGame(), config);
RelativeLayout.LayoutParams gameViewParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
gameViewParams.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
gameViewParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
gameView.setLayoutParams(gameViewParams);
layout.addView(gameView);
adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId(adUnitId);
AdRequest.Builder adRequestBuilder = new AdRequest.Builder();
adRequestBuilder.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
adView.loadAd(adRequestBuilder.build());
RelativeLayout.LayoutParams topParams = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
topParams.addRule(RelativeLayout.ALIGN_PARENT_TOP,RelativeLayout.TRUE);
topParams.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
layout.addView(adView, topParams);
adView.setBackgroundColor(android.graphics.Color.TRANSPARENT);
setContentView(layout);
}
#Override
protected void onResume() {
super.onResume();
adView.resume();
}
#Override
protected void onPause() {
super.onPause();
adView.pause();
}
#Override
protected void onDestroy() {
super.onDestroy();
adView.destroy();
}
}
Related
Right now, I'm using the following permission to show a dialog over another app :
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
Dialog :
dialogBuilder = new AlertDialog.Builder(activity);
LayoutInflater inflater2 = (LayoutInflater) AppController.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View dialogView = inflater2.inflate(R.layout.dialog_view, null);
dialogBuilder.setView(dialogView);
dialog = dialogBuilder.create();
dialog.setCancelable(true);
final WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams();
layoutParams.width = WindowManager.LayoutParams.MATCH_PARENT;
layoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
final Window dialogWindow = dialog.getWindow();
if (dialogWindow != null) {
dialogWindow.setAttributes(layoutParams);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
dialogWindow.setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY);
} else {
dialogWindow.setType(WindowManager.LayoutParams.TYPE_PHONE);
}
}
dialog.show();
Snaptube app, shows a dialog over the YouTube app without asking for any permission :
How I can achieve that?
In my application I want to use service and in this service I should show layout.
I want when click on button show dialog, I write below codes!
But after click on button, show this dialog back of layout and not show any dialog!
My service codes :
public class FloatingLayoutService extends Service implements StepperFormListener {
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
//Inflate the layout using LayoutInflater
layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
floatingLayout = (ConstraintLayout) layoutInflater.inflate(R.layout.service_floating_layout, null);
floatingLay_root = floatingLayout.findViewById(R.id.floatingLay_root);
floatingLay_main = floatingLayout.findViewById(R.id.floatingLay_main);
floatingLay_emptyImg = floatingLayout.findViewById(R.id.floatingLay_emptyImg);
...
//Set layout params to display the controls over any screen.
int LAYOUT_FLAG;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
} else {
LAYOUT_FLAG = WindowManager.LayoutParams.TYPE_PHONE;
}
final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
LAYOUT_FLAG,
0,
PixelFormat.TRANSLUCENT);
// From API26, TYPE_PHONE deprecated. Use TYPE_APPLICATION_OVERLAY for O
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.O)
params.type = WindowManager.LayoutParams.TYPE_PHONE;
//Initial position of the floating controls
params.gravity = Gravity.BOTTOM | Gravity.START;
params.x = 0;
params.y = 0;
//Add the controls view to windowManager
windowManager.addView(floatingLayout, params);
//Task page btn
floatingLay_infoContentNextPage.setOnClickListener(v -> {
AlertDialog alertDialog = new AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("Are you sure?")
.create();
alertDialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT);
alertDialog.show();
});
return START_STICKY;
}
How can I show dialog, front of layout ?
You can make an activity without a layout just to show the Alert dialog.
public class MyAlertDialog extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
new AlertDialog.Builder(this)
.setTitle("Title")
.setMessage("Message")
...
...
.show()
}
}
Remember to finish the activity.
You can set the title and message dynamically by passing them through intent.
Service
Intent intent = new Intent(this, MyAlertDialog.class);
intent.putExtra("titleKey", "title");
intent.putExtra("messageKey", "messge");
startActivity(intent);
And inside the activity, read it as:
getIntent().getStringExtra("titleKey")
getIntent().getStringExtra("messageKey")
I'm new to Android, I got this error :
E/AndroidRuntime: FATAL EXCEPTION: main
Process: com.example.wmaddviewtest, PID: 6104
java.lang.RuntimeException: Unable to start service com.example.wmaddviewtest.WmNewViewService#345022b with Intent { cmp=com.example.wmaddviewtest/.WmNewViewService }: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?<br/>
...... <br/>
*Caused by: android.view.WindowManager$BadTokenException: Unable to add window -- token null is not valid; is your activity running?
at android.view.ViewRootImpl.setView(ViewRootImpl.java:774)*
at android.view.WindowManagerGlobal.addView(WindowManagerGlobal.java:373)
at android.view.WindowManagerImpl.addView(WindowManagerImpl.java:93)
at com.example.wma<ddviewtest.WmNewViewService.createWindowManagerView(WmNewViewService.java:64)
at com.example.wmaddviewtest.WmNewViewService.onStartCommand(WmNewViewService.java:31)
I do add user-permission at AndroidManifest.xml.
My AndroidManifest is following:
<?xml version="1.0" encoding="UTF-8"?>
-<manifest tools:ignore="GoogleAppIndexingWarning" package="com.example.wmaddviewtest" xmlns:tools="http://schemas.android.com/tools" xmlns:android="http://schemas.android.com/apk/res/android">
-<application android:fullBackupContent="#xml/backup_descriptor" android:theme="#style/AppTheme" android:supportsRtl="true" android:roundIcon="#mipmap/ic_launcher_round" android:label="#string/app_name" android:icon="#mipmap/ic_launcher" android:allowBackup="true">
<service android:permission="" android:exported="true" android:enabled="true" android:name="com.example.wmaddviewtest.WmNewViewService"/>
-<activity android:name=".MainActivity">
-<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
</application>
<uses-permission tools:ignore="ManifestOrder" android:name="android.permission.SYSTEM_ALERT_WINDOW"/>
</manifest>
In MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showViewBtn = findViewById(R.id.showViewBtn);
showViewBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setClass(MainActivity.this, WmNewViewService.class);
startService(intent);
}
});
}
I add a Custom Service named WmNewViewService.java, following is it's code:
private MyView myView;
private WindowManager mWindowManager;
private WindowManager.LayoutParams mParams;
private final static String TAG = "WmNewViewService";
public WmNewViewService() {
}
#Override
public void onCreate() {
super.onCreate();
myView = new MyView(this);
mWindowManager = (WindowManager) getApplicationContext().getSystemService(Context.WINDOW_SERVICE);
}
#Override
public int onStartCommand(Intent intent, int flags, int startId) {
createWindowManagerView();
return super.onStartCommand(intent, flags, startId);
}
#Override
public void onDestroy() {
super.onDestroy();
if (myView != null) {
mWindowManager.removeViewImmediate(myView);
myView = null;
}
}
/**
* set Parameters ,and AddView
*/
public void createWindowManagerView() {
mParams = new WindowManager.LayoutParams();
mParams.width = mWindowManager.getDefaultDisplay().getWidth();
mParams.height = mWindowManager.getDefaultDisplay().getHeight();
mParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_PANEL;
mParams.format = PixelFormat.RGBX_8888;
mParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
mParams.x = 0;
mParams.y = 0;
myView.requestLayout();
mWindowManager.addView(myView, mParams);
}
also, you can see I new a MyView, and MyView.java is:
private View myView;
private Button newViewBtn;
public MyView(Context context) {
super(context);
init();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init();
}
private void init() {
myView = LayoutInflater.from(getContext()).inflate(R.layout.myview, null, false);
newViewBtn = myView.findViewById(R.id.newViewBtn);
}
In addition, I new a myview.xml, myview.xml just a LinearLayout, include a Button, the Button text is "this is a view".
In my activity_main.xml, I only set a button which is clickable.
I just want when I click the button which is in activity_main.xml, then start service, and the service make the button which text "this is a view" show.
I do try postdelay.
Try specifying the full package location in AndroidManifest.xml and see if that helps. IE:
<service android:enabled="true" android:name="com.exercise.AndroidClient.services.WmNewViewService" />
instead of
<service android:enabled="true" android:name=".services.WmNewViewService" />
(replacing with the correct package location obviously)
I have a web app (secured via SSL) that has an access to camera.It shows camera captures in a canvas. It worked perfectly in the browser. However, I want the camera content to show in the Webview in my app.
Here is my code in the method onCreate:
final WebView myWebView = (WebView) findViewById(R.id.webView);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.getSettings().setAllowFileAccessFromFileURLs(true);
myWebView.getSettings().setAllowUniversalAccessFromFileURLs(true);
myWebView.loadUrl("https://myvideoapp.me");
myWebView.setWebViewClient(new WebViewClient());
Here is permissions i used in my manifest.XML
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />
<uses-permission android:name="android.permission.RECORD_AUDIO" />
<uses-permission android:name="android.permission.MODIFY_AUDIO_SETTINGS" />
You'll need to ask permission if you're coding android +4.4
Into your MainActivity, inside your class, use this if you want to ask for CAMERA permission:
private static final int REQUEST_ID_MULTIPLE_PERMISSIONS = 0;
private boolean checkAndRequestPermissions() {
int permission = ContextCompat.checkSelfPermission(this, android.Manifest.permission.CAMERA);
List listPermissionsNeeded = new ArrayList();
if (permission != PackageManager.PERMISSION_GRANTED) {
listPermissionsNeeded.add(android.Manifest.permission.CAMERA);
}
if (!listPermissionsNeeded.isEmpty()) {
ActivityCompat.requestPermissions(this, (String[]) listPermissionsNeeded.toArray(new String[listPermissionsNeeded.size()]), REQUEST_ID_MULTIPLE_PERMISSIONS);
return false;
}
return true;
}
And also you have to check it inside your onCreate void function like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if (!checkAndRequestPermissions()) {
return;
}
.........
I just started writing my first Android game and now I also want to try out AdMob. But I cant get it to show ads...
I followed this tutorial to create the game: http://www.kilobolt.com/day-7-creating-an-android-game-from-start-to-finish.html
It uses a canvas to draw everything.
This is the important code I guess:
public abstract class AndroidGame extends Activity implements Game {
AndroidFastRenderView renderView;
Graphics graphics;
Audio audio;
Input input;
FileIO fileIO;
Screen screen;
WakeLock wakeLock;
AdView adView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
boolean isPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
DisplayMetrics metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
int frameBufferWidth = metrics.widthPixels;
int frameBufferHeight = metrics.heightPixels;
Bitmap frameBuffer = Bitmap.createBitmap(frameBufferWidth,
frameBufferHeight, Config.RGB_565);
float scaleX = (float) frameBufferWidth
/ getWindowManager().getDefaultDisplay().getWidth();
float scaleY = (float) frameBufferHeight
/ getWindowManager().getDefaultDisplay().getHeight();
renderView = new AndroidFastRenderView(this, frameBuffer);
graphics = new AndroidGraphics(getAssets(), frameBuffer);
fileIO = new AndroidFileIO(this);
audio = new AndroidAudio(this);
input = new AndroidInput(this, renderView, scaleX, scaleY);
screen = getInitScreen();
//setContentView(renderView);
PowerManager powerManager = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = powerManager.newWakeLock(PowerManager.FULL_WAKE_LOCK, "MyGame");
RelativeLayout layout = new RelativeLayout(this);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT,
RelativeLayout.LayoutParams.MATCH_PARENT);
layout.setLayoutParams(params);
adView = createAdView();
layout.addView(adView);
View gameView =renderView;
layout.addView(gameView);
setContentView(layout);
startAdvertising(adView);
}
private AdView createAdView() {
adView = new AdView(this);
adView.setAdSize(AdSize.BANNER);
adView.setAdUnitId("ca-app-pub-number/number");
adView.setId(12345);
RelativeLayout.LayoutParams params = new RelativeLayout.LayoutParams(
RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.WRAP_CONTENT);
params.addRule(RelativeLayout.ALIGN_PARENT_BOTTOM, RelativeLayout.TRUE);
params.addRule(RelativeLayout.CENTER_HORIZONTAL, RelativeLayout.TRUE);
adView.setLayoutParams(params);
adView.setBackgroundColor(Color.BLACK);
return adView;
}
private void startAdvertising(AdView adView) {
AdRequest adRequest = new AdRequest.Builder().build();
adView.loadAd(adRequest);
}
What am I doing wrong?
Update:
Use "Ads" as a filter in logcat.
You need to use a test device like this:
private void startAdvertising(AdView adView) {
AdRequest adRequest = new AdRequest.Builder()
.addTestDevice("your ID")
.build();
adView.loadAd(adRequest);
}
Further more I changed the adUnitId to the one given here: https://developers.google.com/admob/android/quick-start
And then I changed the order in which the Views get added (it seemed like the gameView was overlaying the adView):
View gameView =renderView;
layout.addView(gameView);
adView = createAdView();
layout.addView(adView);
With these changes it worked.