Skip to content

Instantly share code, notes, and snippets.

Created January 6, 2016 05:35
Show Gist options
  • Select an option

  • Save anonymous/23a806b7627dfbb85cdf to your computer and use it in GitHub Desktop.

Select an option

Save anonymous/23a806b7627dfbb85cdf to your computer and use it in GitHub Desktop.
devcontrolでAdMobを呼び出すときに、int型のパラメータを1つ渡せることが分かったので、devcontrol "AdMob", 0 でバナー広告を、devcontrol "AdMob", 1 で全面広告を表示できるようにしてみるテスト
package tv.hsp;
import android.app.NativeActivity;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.pm.ActivityInfo;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.content.pm.ResolveInfo;
import android.content.DialogInterface;
import android.content.ComponentName;
import android.net.Uri;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Paint.FontMetrics;
import android.graphics.Paint.Style;
import android.graphics.Typeface;
import android.os.AsyncTask;
import android.os.Vibrator;
import android.os.Bundle;
import android.util.Log;
import android.view.Display;
import android.view.Surface;
import android.view.WindowManager;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.view.ViewGroup.MarginLayoutParams;
import android.view.Gravity;
import android.view.View.OnClickListener;
import android.widget.Toast;
import android.widget.PopupWindow;
import android.widget.LinearLayout;
import android.widget.Button;
import android.widget.TextView;
import java.util.List;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Random;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import org.apache.http.Header;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.HttpVersion;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.apache.http.params.HttpProtocolParams;
import org.apache.http.util.EntityUtils;
import com.google.android.gms.ads.*;
public class HspActivity extends NativeActivity {
// string code
// public static final String CHAR_CODE = "Shift-JIS";
public static final String CHAR_CODE = "UTF8";
public String hello() {
return "JNITest";
}
public String getInfo_Device() {
return android.os.Build.DEVICE;
}
public String getInfo_Version() {
return android.os.Build.VERSION.RELEASE;
}
public String getInfo_Locale() {
return Locale.getDefault().getISO3Language();
}
public String getInfo_FilesDir() {
File f = this.getApplicationContext().getFilesDir();
String path = f.toString();
return path;
}
// Nativeへの通知
public native void nativepoke(int val, int val2);
public int callVibrator(int val) {
Vibrator vibrator = (Vibrator) getSystemService(VIBRATOR_SERVICE);
if (vibrator != null)
vibrator.vibrate(val);
return 0;
}
public int callNamedActivity(String msg1, String msg2, int mode) {
Intent shareIntent = new Intent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");
shareIntent.putExtra(Intent.EXTRA_TEXT, msg2);
String appName = msg1; // "twitter";
int res = -1;
PackageManager pm = getPackageManager();
List<?> activityList = pm.queryIntentActivities(shareIntent, 0);
int len = activityList.size();
for (int i = 0; i < len; i++) {
ResolveInfo app = (ResolveInfo) activityList.get(i);
if ((app.activityInfo.name.contains(appName))) {
if (mode > 0) {
ActivityInfo activity = app.activityInfo;
ComponentName name = new ComponentName(activity.applicationInfo.packageName, activity.name);
shareIntent.setComponent(name);
startActivity(shareIntent);
}
res = 0;
break;
}
}
return res;
}
public int callActivity(String msg1, String msg2, int type) {
if (type == 16) {
Uri uri = Uri.parse(msg1);
Intent i = new Intent();
i.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
i.setAction(Intent.ACTION_VIEW);
i.setData(uri);
startActivity(i);
return 0;
}
if (type == 48) {
return callNamedActivity(msg1, msg2, 1);
}
Intent intent = new Intent();
intent.setClassName(msg1, msg2);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
return 0;
}
public int ui_dispDialog(String msg1, String msg2, int type) {
// OKダイアログ
final int addtype;
final String s_msg1;
final String s_msg2;
final HspActivity myActivity;
addtype = type;
myActivity = this;
s_msg1 = msg1;
s_msg2 = msg2;
this.runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog.Builder alert = new AlertDialog.Builder(myActivity);
alert.setMessage(s_msg1);
alert.setTitle(s_msg2);
if ((addtype & 1) > 0) {
alert.setIcon(android.R.drawable.ic_dialog_alert);
} else {
alert.setIcon(android.R.drawable.ic_dialog_info);
}
alert.setPositiveButton("OK", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
nativepoke(0, 0);
}
});
alert.create().show();
}
});
return 0;
}
public int ui_dispDialogYN(String msg1, String msg2, int type) {
// YES/NOダイアログ
final int addtype;
final String s_msg1;
final String s_msg2;
final HspActivity myActivity;
addtype = type;
myActivity = this;
s_msg1 = msg1;
s_msg2 = msg2;
this.runOnUiThread(new Runnable() {
@Override
public void run() {
AlertDialog.Builder alert = new AlertDialog.Builder(myActivity);
alert.setMessage(s_msg1);
alert.setTitle(s_msg2);
if ((addtype & 1) > 0) {
alert.setIcon(android.R.drawable.ic_dialog_alert);
} else {
alert.setIcon(android.R.drawable.ic_dialog_info);
}
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
nativepoke(0, 6);
}
});
alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
nativepoke(0, 7);
}
});
alert.create().show();
}
});
return 0;
}
public int dispDialog(String msg1, String msg2, int type) {
if (type >= 4)
return -1;
if ((type & 2) > 0) {
return ui_dispDialogYN(msg1, msg2, type);
}
return ui_dispDialog(msg1, msg2, type);
}
public int addWindowFlag(int type) {
final int addtype;
if (type == 1) {
addtype = WindowManager.LayoutParams.FLAG_FULLSCREEN;
} else {
addtype = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
}
this.runOnUiThread(new Runnable() {
public void run() {
getWindow().addFlags(addtype);
}
});
return 0;
}
public int clearWindowFlag(int type) {
final int clrtype;
if (type == 1) {
clrtype = WindowManager.LayoutParams.FLAG_FULLSCREEN;
} else {
clrtype = WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON;
}
this.runOnUiThread(new Runnable() {
public void run() {
getWindow().clearFlags(clrtype);
}
});
return 0;
}
// conversion ByteText->String
public String ByteTextToString(byte[] byteText) {
try {
if (byteText == null)
return "";
return new String(byteText, CHAR_CODE);
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
return "";
}
}
// retrieve font text by bitmap data
public Bitmap getFontBitmap(byte[] byteText, int fontsize, boolean bBold) {
String text = ByteTextToString(byteText);
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
paint.setColor(Color.WHITE);
paint.setTextSize(fontsize);
paint.setAntiAlias(true);
paint.setSubpixelText(true);
paint.setTypeface(Typeface.create(Typeface.SANS_SERIF, (bBold) ? Typeface.BOLD : Typeface.NORMAL));
FontMetrics fontMetrics = paint.getFontMetrics();
int width = (int) Math.round(paint.measureText(text));
if (width <= 0) {
width = (int) Math.round(paint.measureText("0"));
}
int offsetY = (int) Math.ceil(-fontMetrics.top);
int height = offsetY + (int) (Math.ceil(fontMetrics.bottom));
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ALPHA_8);
Canvas canvas = new Canvas(bitmap);
canvas.drawText(text, 0, offsetY, paint);
return bitmap;
}
// http network task
private String _httpResult;
private ArrayList<NameValuePair> _httpParams;
public String getHttpResult() {
return _httpResult;
}
public int httpParamSet(String prm1, String prm2, int type) {
if (type < 0) {
return -1;
}
if (type == 0) {
_httpParams = new ArrayList<NameValuePair>();
return 0;
}
_httpParams.add(new BasicNameValuePair(prm1, prm2));
return 0;
}
public int httpRequestGET(String url, String optstr, int type) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 3000);
StringBuilder uri = new StringBuilder(url);
HttpGet request = new HttpGet(uri.toString());
HttpResponse httpResponse;
_httpResult = "";
try {
httpResponse = httpClient.execute(request);
} catch (Exception e) {
return -1;
}
int status = httpResponse.getStatusLine().getStatusCode();
try {
_httpResult = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (Exception e) {
return -1;
}
httpClient.getConnectionManager().shutdown();
if (status != HttpStatus.SC_OK) {
return status;
}
return 0;
}
public int httpRequestPOST(String url, String optstr, int type) {
DefaultHttpClient httpClient = new DefaultHttpClient();
HttpParams params = httpClient.getParams();
HttpConnectionParams.setConnectionTimeout(params, 5000);
HttpConnectionParams.setSoTimeout(params, 3000);
StringBuilder uri = new StringBuilder(url);
HttpPost request = new HttpPost(uri.toString());
HttpResponse httpResponse;
_httpResult = "";
try {
request.setEntity(new UrlEncodedFormEntity(_httpParams, "UTF-8"));
httpResponse = httpClient.execute(request);
} catch (Exception e) {
return -1;
}
int status = httpResponse.getStatusLine().getStatusCode();
try {
// _httpResult = EntityUtils.toString( httpResponse.getEntity(),
// "SHIFT-JIS" );
_httpResult = EntityUtils.toString(httpResponse.getEntity(), "UTF-8");
} catch (Exception e) {
return -1;
}
httpClient.getConnectionManager().shutdown();
if (status != HttpStatus.SC_OK) {
return status;
}
return 0;
}
// }
// for AdMob
private static AdView adView;
private static AdRequest.Builder _request;
private static PopupWindow popUp;
private static HspActivity _activity;
private static LinearLayout layout;
private static LinearLayout mainLayout;
private static boolean adsinited = false;
private static int disp_width = 0;
private static int disp_height = 0;
public static InterstitialAd interstitialAd;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Make your custom init here
//getWindow().addFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
_activity = this;
WindowManager windowmanager = (WindowManager)getSystemService(WINDOW_SERVICE);
Display disp = windowmanager.getDefaultDisplay();
disp_width = disp.getWidth();
disp_height = disp.getHeight();
Log.i("HspActivity","size"+disp_width+"x"+disp_height);
// Create our ad view here
adView = new AdView(_activity);
// バナー広告用のAd Unit IDを設定する。
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
adView.setAdSize(AdSize.BANNER);
//adView = new AdView(_activity, AdSize.BANNER, "publisherID");
if(adView!=null) {
Log.i("HspActivity","done adView initalizing.");
_request = new AdRequest.Builder();
_request.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
adView.loadAd( _request.build() );
}
Log.i("HspActivity","adView initalized.");
prepareInterstitial();
}
public int callAdMob(int val) {
if (val == 0) {
return __callAdMob(val);
} else {
showInterstitial();
return 0;
}
}
// InterstitialAdの初期化
private void prepareInterstitial() {
interstitialAd = new InterstitialAd(this);
// 全面広告用のAd Unit IDを設定する。
interstitialAd.setAdUnitId("ca-app-pub-3940256099942544/1033173712");
interstitialAd.setAdListener(new AdListener() {
public void onAdLoaded() { Log.i("HspActivity", "Interstitial Ad loaded."); }
public void onAdFailedToLoad() { Log.i("HspActivity", "Interstitial Ad failed to load."); }
public void onAdClosed() { Log.i("HspActivity", "Interstitial Ad closed.");
prepareInterstitial(); }
});
if (interstitialAd != null) {
_request = new AdRequest.Builder();
_request.addTestDevice(AdRequest.DEVICE_ID_EMULATOR);
interstitialAd.loadAd(_request.build());
Log.i("HspActivity", "InterstitialAd init success");
} else {
Log.i("HspActivity", "InterstitialAd init failed");
}
}
// Shows the interstitial ad.
private void showInterstitial() {
if (interstitialAd != null) {
_activity.runOnUiThread(new Runnable() {
public void run() {
while (!interstitialAd.isLoaded()) {}
interstitialAd.show();
}
});
}
}
// Our popup window, you will call it from your C/C++ code later
private int __callAdMob( int val ) {
if(adsinited) {
return -1;
}
if(adView!=null) {
Log.i("HspActivity","callAdMob.");
_activity.runOnUiThread(new Runnable() {
@Override
public void run() {
adsinited = true;
// Out popup window
popUp = new PopupWindow(_activity);
// This is the minimum size for AdMob, we need to set this in case our target device run at 320x480 resolution (Otherwise no ad will be shown, see the padding kill below)
//popUp.setWidth(484);
popUp.setWidth(disp_width+4);
popUp.setHeight(77);
popUp.setWindowLayoutMode(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
popUp.setClippingEnabled(false);
layout = new LinearLayout(_activity);
mainLayout = new LinearLayout(_activity);
// The layout system for the PopupWindow will kill some pixels due to margins/paddings etc(No way to remove it), so padd it to adjust
layout.setPadding(-5, -5, -5, -5);
MarginLayoutParams params = new MarginLayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params.setMargins(0, 0, 0, 0);
layout.setOrientation(LinearLayout.VERTICAL);
layout.addView(adView, params);
popUp.setContentView(layout);
_activity.setContentView(mainLayout, params);
//AdRequest adRequest = new AdRequest();
// Enable this if your are testing AdMob, otherwise you'll risk to be banned!
//adRequest.addTestDevice(AdRequest.TEST_EMULATOR);
//adRequest.addTestDevice("********************************");
//_activity.adView.loadAd(_request);
Log.i("HspActivity","loadAd.");
// Show our popup window
popUp.showAtLocation(mainLayout, Gravity.BOTTOM, 0, 0);
popUp.update();
}});
} else {
Log.i("HspActivity","callAdMob failed.");
}
return 0;
}
// Do some cleanup
@Override
public void onDestroy() {
if (adView != null) {
adView.destroy();
}
super.onDestroy();
}
}
/*
サンプルのブロック崩し(block3_ad.hsp)を微修正した版。
開始直後にバナー広告を表示し、
ゲーム終了後に全面広告を表示する。
*/
#include "hsp3dish.as"
;
; ブロック崩し
; (AdMob対応テスト版)
;
#cmpopt varname 1
x1=0:y1=0 ; 画面左上の座標
x2=ginfo_winx:y2=ginfo_winy ; 画面右下の座標
screen 0,x2,y2
title "ブロック崩し"
// もし開始直後にdevcontrolで全面広告を表示したければ、repeatを100回くらい繰り返して待機することが必要?
repeat 10
redraw 0
redraw 1
await 33
loop
// 0 でバナー広告
devcontrol "AdMob", 0 ; AdMobを有効にする
;cls 4
*gstart
clrflag=0 ; クリアフラグ
blsize=16 ; ボールのサイズ
blspd=10 ; ボールのスピード
blx=200:bly=200 ; ボールの座標
bpx=4:bpy=4 ; XY方向のボール座標加算値
bk=0 ; ブロックを崩すフラグ(1=崩す)
mblsize=-blsize
barsize=64 ; バーのサイズ
barx=240:bary=540 ; バーの座標
barhalf=barsize/2
blhalf=blsize/2
wx=0:wy=80 ; ブロックの表示開始位置(左上)
wsx=10:wsy=6 ; ブロックの配置数(X,Y)
wpx=x2/wsx:wpy=16 ; ブロック1個あたりのサイズ
dim wall,wsx,wsy ; ブロックを表示するフラグ
; 0=表示、1=表示しない
score = 0
gameflag = 0
*main
redraw 0
color 0,0,128:boxf
color 0,255,255:pos 8,8:mes "SCORE:"+score
;gradf 0,0,x2,y2,1,0,128 ; 画面クリア
; バー : マウス座標から位置を決定
barx=mousex-barsize/2
color 255,255,255
boxf barx,bary,barx+barsize,bary+16
if gameflag {
gosub *gameover
stick key
if key&256 {
if mousey<300 : goto *gstart
}
goto *main2
}
; ボール : X方向の移動
blx=blx+bpx
if blx<=x1 : blx=x1 : bpx=-bpx
if blx>=(x2-blsize) : blx=x2-blsize : bpx=-bpx
; ボール : Y方向の移動
bly=bly+bpy
if bly<=y1 : bly=y1 : bpy=blspd : bk=1 : blspd=16
if bly>=(y2-blsize) : gameflag = 1
; ボールとバーがぶつかったかどうか調べます
coly=bly+blsize
if (coly>=bary)&(bly<(bary+16)) { ; ボールY座標のチェック
; ボールX座標のチェック
colx=blx+blhalf
x=barx+barhalf
if abs(colx-x)<(barhalf+blhalf) {
bly=bary-blsize : bpy=-blspd
i=(colx-x)/4
if i!=0 : bpx=i
bk=1
if clrflag {
dim wall,wsx,wsy ; ブロックを復活させる
clrflag=0
}
}
}
*main2
; ブロックの処理
colx=wpx+bsize
coly=wpy+bsize
left=0
repeat wsy
cy=cnt
y=cnt*wpy+wy
hsvcolor cnt*10,255,255
repeat wsx
cx=cnt
x=cnt*wpx+wx
if wall(cx,cy)=0 {
; ブロックを表示
left++
boxf x,y,x+wpx-2,y+wpy-2
i=blx-x:j=bly-y
if (i>=mblsize)&(i<colx)&(j>=mblsize)&(j<coly)&(bk) {
wall(cx,cy)=1
bpy=-bpy
bk=0
score+=wsy-cy
}
}
loop
loop
; ボールを表示
pos blx,bly:color 255,255,255
circle blx,bly,blx+blsize,bly+blsize
;font msgothic,blsize
;mes "●"
redraw 1
await 33
if left=0 : clrflag=1
goto *main
*gameover
color 255,255,255
pos 160,380:mes "GAME OVER"
// 1 で全面広告
devcontrol "AdMob", 1 // 全面広告を呼び出してみる
return
;objsize 180,32
;pos 150,330:button "終わり",*owari
;stop
*owari
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment