微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

java-在其中添加Google Ads后,应用程序意外关闭

我创建了一个手电筒应用程序,它可以完美运行,而无需在其中添加任何广告单元.
但是在代码添加广告单元后,当我下次运行时,应用程序在我的模拟器和android设备上也会意外关闭.
这是我上面提到的应用程序的来源.
activity_main.xml

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:id="@+id/rellayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@layout/radial_background"
tools:context=".MainActivity"
tools:ignore="Overdraw" >
...
...
<com.google.ads.AdView
    android:id="@+id/adView"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@+id/textView1"
    android:layout_alignParentLeft="true"
    ads:adSize="BANNER"
    ads:adUnitId="xxxxxxx"
    ads:loadAdOnCreate="true"
    ads:testDevices="TEST_EMULATOR" >
</com.google.ads.AdView>

对于上述活动,我在AndroidManifest.xml中进行了更改

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.jdev.itorch"
android:versionCode="1"
android:versionName="1.1.2" android:installLocation="auto" xmlns:tools="http://schemas.android.com/tools">

<uses-sdk
    android:minSdkVersion="8"
    android:targetSdkVersion="17" tools:ignore="OldTargetApi"/>

<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.WAKE_LOCK"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>

<application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
    <activity 
        android:name="com.google.ads.AdActivity"
        android:configChanges="keyboard|keyboardHidden|orientation"
        ></activity>
    <activity
        android:name="com.jdev.itorch.TorchActivity"
        android:label="@string/app_name"
        android:screenorientation="portrait">
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
</application>

附言代码在编译时没有显示错误.
我也检查了logCat,它在主要活动开始时显示一些NullPointerException错误.
我不知道该如何处理我的代码,这就是为什么我在这里寻求帮助.

这是全长代码

import android.media.MediaPlayer;
import android.media.MediaPlayer.OnCompletionListener;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.pm.PackageManager;
import android.hardware.Camera;
import android.hardware.Camera.Parameters;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.ImageButton;


public class TorchActivity extends Activity {

ImageButton btnSwitch;

private Camera camera;
private boolean isFlashOn;
private boolean hasFlash;
private Parameters params;
MediaPlayer mp;


@SuppressWarnings("deprecation")
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_torch);    




    btnSwitch = (ImageButton) findViewById(R.id.btnSwitch);



    hasFlash = getApplicationContext().getPackageManager()
            .hasSystemFeature(PackageManager.FEATURE_CAMERA_FLASH);

    if (!hasFlash) {
        AlertDialog alert = new AlertDialog.Builder(TorchActivity.this)
                .create();
        alert.setTitle("Error");
        alert.setMessage("Sorry, your device doesn't support flash light!");
        alert.setButton("OK", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {

                finish();
            }
        });
        alert.show();
        return;
    }


    getCamera();


    toggleButtonImage();



    btnSwitch.setonClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            if (isFlashOn) {

                turnOffFlash();
            } else {

                turnOnFlash();
            }
        }
    });
}



private void getCamera() {
    if (camera == null) {
        try {
            camera = Camera.open();
            params = camera.getParameters();
        } catch (RuntimeException e) {
            Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
        }
    }
}



private void turnOnFlash() {
    if (!isFlashOn) {
        if (camera == null || params == null) {
            return;
        }

        playSound();

        params = camera.getParameters();
        params.setFlashMode(Parameters.FLASH_MODE_TORCH);
        camera.setParameters(params);
        camera.startPreview();
        isFlashOn = true;


        toggleButtonImage();
    }

}



private void turnOffFlash() {
    if (isFlashOn) {
        if (camera == null || params == null) {
            return;
        }

        playSound();

        params = camera.getParameters();
        params.setFlashMode(Parameters.FLASH_MODE_OFF);
        camera.setParameters(params);
        camera.stopPreview();
        isFlashOn = false;


        toggleButtonImage();
    }
}



private void playSound(){
    if(isFlashOn){
        mp = MediaPlayer.create(TorchActivity.this, R.raw.light_switch_off);
    }else{
        mp = MediaPlayer.create(TorchActivity.this, R.raw.light_switch_on);
    }
    mp.setonCompletionListener(new OnCompletionListener() {

        @Override
        public void onCompletion(MediaPlayer mp) {
            // Todo Auto-generated method stub
            mp.release();
        }
    }); 
    mp.start();
}


private void toggleButtonImage(){
    if(isFlashOn){
        btnSwitch.setimageResource(R.drawable.btn_switch_on);
    }else{
        btnSwitch.setimageResource(R.drawable.btn_switch_off);
    }
}

@Override
protected void onDestroy() {
    super.onDestroy();
}

@Override
protected void onPause() {
    super.onPause();


    turnOffFlash();
}

@Override
protected void onRestart() {
    super.onRestart();
}

@Override
protected void onResume() {
    super.onResume();


    if(hasFlash)
        turnOnFlash();
}

@Override
protected void onStart() {
    super.onStart();


    getCamera();
}

@Override
protected void onStop() {
    super.onStop();


    if (camera != null) {
        camera.release();
        camera = null;
    }
}





@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.torch, menu);
    return true;
}

}

更新
这是LogCat数据

03-18 09:11:43.572: D/dalvikvm(1052): GC_FOR_ALLOC freed 80K, 5% free 3068K/3224K, paused 32ms, total 34ms
03-18 09:11:43.582: I/dalvikvm-heap(1052): Grow heap (frag case) to 3.673MB for 635812-byte allocation
03-18 09:11:43.622: D/dalvikvm(1052): GC_FOR_ALLOC freed 4K, 5% free 3684K/3848K, paused 37ms, total 37ms
03-18 09:11:43.792: D/AndroidRuntime(1052): Shutting down VM
03-18 09:11:43.792: W/dalvikvm(1052): threadid=1: thread exiting with uncaught exception (group=0xb3aa7b90)
03-18 09:11:43.832: E/AndroidRuntime(1052): FATAL EXCEPTION: main
03-18 09:11:43.832: E/AndroidRuntime(1052): Process: com.jdev.itorch, PID: 1052
03-18 09:11:43.832: E/AndroidRuntime(1052): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.jdev.itorch/com.jdev.itorch.TorchActivity}: java.lang.NullPointerException: println needs a message
03-18 09:11:43.832: E/AndroidRuntime(1052):     at android.app.ActivityThread.performlaunchActivity(ActivityThread.java:2176)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2226)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at android.app.ActivityThread.access$700(ActivityThread.java:135)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1397)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at android.os.Handler.dispatchMessage(Handler.java:102)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at android.os.Looper.loop(Looper.java:137)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at   android.app.ActivityThread.main(ActivityThread.java:4998)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at java.lang.reflect.Method.invokeNative(Native Method)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at java.lang.reflect.Method.invoke(Method.java:515)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:777)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:593)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at dalvik.system.NativeStart.main(Native Method)
03-18 09:11:43.832: E/AndroidRuntime(1052): Caused by: java.lang.NullPointerException: println needs a message
03-18 09:11:43.832: E/AndroidRuntime(1052):     at android.util.Log.println_native(Native Method)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at android.util.Log.e(Log.java:232)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at com.jdev.itorch.TorchActivity.getCamera(TorchActivity.java:91)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at com.jdev.itorch.TorchActivity.onStart(TorchActivity.java:199)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at android.app.Instrumentation.callActivityOnStart(Instrumentation.java:1171)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at android.app.Activity.performStart(Activity.java:5253)
03-18 09:11:43.832: E/AndroidRuntime(1052):     at android.app.ActivityThread.performlaunchActivity(ActivityThread.java:2149)
03-18 09:11:43.832: E/AndroidRuntime(1052):     ... 11 more
03-18 09:16:44.422: I/Process(1052): Sending signal. PID: 1052 SIG: 9

解决方法:

我猜我明白@Tyler提到的这段代码中的实际问题是什么,e.getMessage()可能为null
但是,他所举的例子有点让人误解.
我曾经宣布
public volatile字符串errorMessage =“”;

我这样实现:

private void getCamera() {
    if (camera == null) {
        try {
            camera = Camera.open();
            params = camera.getParameters();
        } catch (RuntimeException e) {
            Log.e("Camera Error. Failed to Open. Error: ", e.getMessage());
            if(e.getMessage() == null) {
                errorMessage = "Camera Error.  Failed to Open.  Error message is null"; //here//
            }

            else {
                Log.e("Camera Error.  Failed to Open.  Error: ", e.getMessage());
            }
        }
    }
}

谢谢您的支持
关于杰伊·夏尔马.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐