标签: android-strictmode

使用StrictMode的MapActivity不起作用 - 帮助

在Android开发者博客上阅读Tim Bray的帖子"New Gingerbread API:StrictMode"后,我决定开始在我的项目中使用它.我希望在出现问题之前帮助解决性能问题.

我的问题是,每次我尝试加载我的MapActivity时,应用程序都会死掉,但只有在启用了StrictMode时.即使使用简单的代码活动,它也会消亡.

有没有人成功使用StrictMode和MapActivity?如果是这样,诀窍是什么?

LogCat的输出是:

TestActivity - onCreate
TestActivity - onStart
TestActivity - onResume
Handling network change notification:CONNECTED
Couldn't get connection factory client
StrictMode policy violation; ~duration=344 ms: android.os.StrictMode$StrictModeDiskReadViolation: policy=343 violation=2
    at android.os.StrictMode$AndroidBlockGuardPolicy.onReadFromDisk(StrictMode.java:745)
    at android.database.sqlite.SQLiteDatabase.rawQueryWithFactory(SQLiteDatabase.java:1345)
    at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:330)
    at android.database.sqlite.SQLiteQueryBuilder.query(SQLiteQueryBuilder.java:280)
    at com.google.android.gsf.settings.GoogleSettingsProvider.query(GoogleSettingsProvider.java:142)
    at android.content.ContentProvider$Transport.bulkQuery(ContentProvider.java:174)
    at android.content.ContentProviderNative.onTransact(ContentProviderNative.java:111)
    at android.os.Binder.execTransact(Binder.java:320)
    at dalvik.system.NativeStart.run(Native Method)
# via Binder call with stack:
android.os.StrictMode$LogStackTrace
    at android.os.StrictMode.readAndHandleBinderCallViolations(StrictMode.java:1059)
    at android.os.Parcel.readExceptionCode(Parcel.java:1304)
    at android.database.DatabaseUtils.readExceptionFromParcel(DatabaseUtils.java:111)
    at android.content.ContentProviderProxy.bulkQueryInternal(ContentProviderNative.java:330)
    at android.content.ContentProviderProxy.query(ContentProviderNative.java:366)
    at android.content.ContentResolver.query(ContentResolver.java:262)
    at android_maps_conflict_avoidance.com.google.common.android.AndroidConfig.getSetting(AndroidConfig.java:216)
    at android_maps_conflict_avoidance.com.google.common.android.AndroidConfig.getDistributionChannelInternal(AndroidConfig.java:195)
    at android_maps_conflict_avoidance.com.google.common.Config.init(Config.java:273)
    at …
Run Code Online (Sandbox Code Playgroud)

android google-maps android-strictmode

5
推荐指数
1
解决办法
2970
查看次数

Android WebView导致StrictMode违规

我注意到StrictMode正在大声抱怨WebView的创建.有没有办法提高WebView对象的启动性能?我在onCreate()方法中实例化XML.

webView = (WebView) findViewById(R.id.webview);
webView.clearCache(true);
webView.getSettings().setDefaultFontSize(20);
webView.getSettings().setPluginsEnabled(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebViewClient(new MyWebViewClient());

WebSettings wb = webView.getSettings();
wb.setRenderPriority(WebSettings.RenderPriority.HIGH);
webView.setWebChromeClient(new MyWebChromeClient(this));
Run Code Online (Sandbox Code Playgroud)

这是许多StrictMode警告中的第一个:

D/StrictMode(22781): StrictMode policy violation; ~duration=1869 ms: android.os.StrictMode$StrictModeDiskReadViolation: policy=23 violation=2
D/StrictMode(22781):    at android.os.StrictMode$AndroidBlockGuardPolicy.onReadFromDisk(StrictMode.java:745)
D/StrictMode(22781):    at android.database.sqlite.SQLiteStatement.simpleQueryForLong(SQLiteStatement.java:106)
D/StrictMode(22781):    at android.database.sqlite.SQLiteDatabase.getVersion(SQLiteDatabase.java:928)
D/StrictMode(22781):    at android.webkit.WebViewDatabase.getInstance(WebViewDatabase.java:196)
D/StrictMode(22781):    at android.webkit.WebView.<init>(WebView.java:1002)
D/StrictMode(22781):    at android.webkit.WebView.<init>(WebView.java:979)
D/StrictMode(22781):    at android.webkit.WebView.<init>(WebView.java:969)
D/StrictMode(22781):    at java.lang.reflect.Constructor.constructNative(Native Method)
D/StrictMode(22781):    at java.lang.reflect.Constructor.newInstance(Constructor.java:415)
D/StrictMode(22781):    at android.view.LayoutInflater.createView(LayoutInflater.java:505)
D/StrictMode(22781):    at com.android.internal.policy.impl.PhoneLayoutInflater.onCreateView(PhoneLayoutInflater.java:56)
D/StrictMode(22781):    at android.view.LayoutInflater.createViewFromTag(LayoutInflater.java:568)
D/StrictMode(22781):    at android.view.LayoutInflater.rInflate(LayoutInflater.java:623)
D/StrictMode(22781):    at android.view.LayoutInflater.rInflate(LayoutInflater.java:626)
D/StrictMode(22781):    at android.view.LayoutInflater.inflate(LayoutInflater.java:408)
D/StrictMode(22781):    at android.view.LayoutInflater.inflate(LayoutInflater.java:320)
D/StrictMode(22781):    at android.view.LayoutInflater.inflate(LayoutInflater.java:276) …
Run Code Online (Sandbox Code Playgroud)

performance android webview android-strictmode

5
推荐指数
1
解决办法
2221
查看次数

StrictMode java.lang.Throwable:检测到未标记的套接字

在启用StrictMode的情况下,我刚刚开始遇到此异常:

java.lang.Throwable:检测到未标记的套接字;使用TrafficStats.setThreadSocketTag()跟踪所有网络使用情况

android android-trafficstats android-strictmode

5
推荐指数
2
解决办法
5912
查看次数

Android的StrictMode的生命周期是什么?

我正在尝试最小化我需要设置StrictMode的代码中的位置数.但我不确定我是否对以下内容有所帮助.

Android的StrictMode文档说您可以将它用于应用程序,活动和其他组件.我已经读过扩展Application类是不可取的,我不想仅仅为了启用StrictMode而扩展Application.但我不认为我必须这样做.

您可以使用两种策略:ThreadPolicy(用于线程)和VmPolicy(用于所有线程).所以看起来如果我在一个线程上设置一次StrictMode,那么我从哪里开始并不重要,并且此后将在该线程上报告违规,而不管StrictMode上是否有其他调用.我只需要在我想要检测到的违规行为之前从某个地方调用它.并且需要为我想要检查的应用程序中创建的任何新线程设置它.

我认为我想避免的是调用build()方法而不是我需要的.将StrictMode放在onCreate()我所有活动的开头,意味着build()将在该线程上被多次调用.如果我的应用程序中有一个Launcher活动,那么在该活动中设置StrictMode onCreate()应该足以满足应用程序的其余部分.真的吗?

其次,如果我的主要活动重新启动,即使应用程序没有死亡,技术上是否需要再次调用StrictMode?或者我的线程仍设置为报告违规?我认为在StrictMode周围做一个包装类的类可能有一些价值,如下所示:

public class MyStrictModeSettings {
    static private List<Long> setThreads = new ArrayList<Long>();

    // Prevent instantiation of this class
    private MyStrictModeSettings() {}

    static public synchronized void init() {
        try {
            Long tid = Thread.currentThread().getId();
            if(!setThreads.contains(tid)) {
                setThreads.add(tid);
                Class sMode = Class.forName("android.os.StrictMode");
                Method enableDefaults = sMode.getMethod("enableDefaults");
                enableDefaults.invoke(null);
            }
        }
        catch(Exception e) {
            // StrictMode not supported on this device, punt
            Log.v("StrictMode", "... not supported. Skipping...");
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

这样,在我的主要活动的onCreate()中,我可以简单地调用MyStrictModeSettings.init()并完成它.它也适用于2.3之前的Android版本.但它可能不值得.布拉德,你呢?谢谢.

编辑:由于VmPolicy适用于所有线程,从技术上讲,我只需要为每个应用程序设置一次,对吧?因此,当调用第二,第三等时间时,enableDefaults()会浪费精力重做VmPolicy吗?再一次,也许比试图避免额外呼叫更值得麻烦.

android android-strictmode

4
推荐指数
1
解决办法
1358
查看次数

严格模式抱怨资源泄漏

严格模式会引发以下情况:在附加的堆栈跟踪中获取资源但从未释放.有关避免资源泄漏的信息,请参阅java.io.Closeable:

**response = httpclient.execute(httpPost);**
Run Code Online (Sandbox Code Playgroud)

以下是我的代码:

    HttpClient httpclient = new DefaultHttpClient();

    String url = "example";
    HttpPost httpPost = new HttpPost(url);

    HttpResponse response;
    String responseString = "";
    try {
        httpPost.setHeader("Content-Type", "application/json");

**response = httpclient.execute(httpPost);**

        StatusLine statusLine = response.getStatusLine();
        if (statusLine.getStatusCode() == HttpStatus.SC_OK) {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            response.getEntity().writeTo(out);
            out.close();
            responseString = out.toString();
        } else {
            response.getEntity().getContent().close();
            throw new IOException(statusLine.getReasonPhrase());
        }
    } catch (ClientProtocolException e) {
    } catch (IOException e) {
    }

    return responseString;
Run Code Online (Sandbox Code Playgroud)

提前致谢.

java android inputstream bytearrayoutputstream android-strictmode

4
推荐指数
1
解决办法
6410
查看次数

StrictMode AndroidBlockGuardPolicy.onReadFromDisk

我面临下一个问题:

StrictMode policy violation; ~duration=2235 ms: android.os.StrictMode$StrictModeDiskReadViolation: policy=65567 violation=2
                                                                   at android.os.StrictMode$AndroidBlockGuardPolicy.onReadFromDisk(StrictMode.java:1278)
                                                                   at libcore.io.BlockGuardOs.lseek(BlockGuardOs.java:162)
                                                                   at java.io.RandomAccessFile.seek(RandomAccessFile.java:603)
                                                                   at java.util.zip.Zip64.parseZip64EocdRecordLocator(Zip64.java:98)
                                                                   at java.util.zip.ZipFile.readCentralDir(ZipFile.java:419)
                                                                   at java.util.zip.ZipFile.<init>(ZipFile.java:175)
                                                                   at java.util.zip.ZipFile.<init>(ZipFile.java:131)
                                                                   at dalvik.system.DexPathList$Element.maybeInit(DexPathList.java:452)
                                                                   at dalvik.system.DexPathList$Element.findResource(DexPathList.java:499)
                                                                   at dalvik.system.DexPathList.findResource(DexPathList.java:360)
                                                                   at dalvik.system.BaseDexClassLoader.findResource(BaseDexClassLoader.java:67)
                                                                   at java.lang.ClassLoader.getResource(ClassLoader.java:403)
                                                                   at java.lang.ClassLoader.getResourceAsStream(ClassLoader.java:442)
                                                                   at ch.qos.logback.classic.util.ContextInitializer.getResource(Unknown Source)
                                                                   at ch.qos.logback.classic.util.ContextInitializer.findConfigFileURLFromAssets(Unknown Source)
                                                                   at ch.qos.logback.classic.util.ContextInitializer.autoConfig(Unknown Source)
                                                                   at org.slf4j.impl.StaticLoggerBinder.init(Unknown Source)
                                                                   at org.slf4j.impl.StaticLoggerBinder.<clinit>(Unknown Source)
                                                                   at org.slf4j.LoggerFactory.bind(LoggerFactory.java:150)
                                                                   at org.slf4j.LoggerFactory.performInitialization(LoggerFactory.java:124)
                                                                   at org.slf4j.LoggerFactory.getILoggerFactory(LoggerFactory.java:412)
                                                                   at org.slf4j.LoggerFactory.getLogger(LoggerFactory.java:357)
                                                                   at com.my.utils.x.c(LogUtils.java:164)
                                                                   at com.my.utils.x.b(LogUtils.java:65)
                                                                   at com.my.Application.onCreate(Application.java:148)
                                                                   at android.app.Instrumentation.callApplicationOnCreate(Instrumentation.java:1018)
                                                                   at android.app.ActivityThread.handleBindApplication(ActivityThread.java:4970)
                                                                   at android.app.ActivityThread.-wrap1(ActivityThread.java)
                                                                   at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1560)
                                                                   at android.os.Handler.dispatchMessage(Handler.java:111)
                                                                   at android.os.Looper.loop(Looper.java:207)
                                                                   at android.app.ActivityThread.main(ActivityThread.java:5765)
                                                                   at java.lang.reflect.Method.invoke(Native …
Run Code Online (Sandbox Code Playgroud)

android android-strictmode

4
推荐指数
1
解决办法
2806
查看次数

使用严格模式最新找不到 Powershell 对象

我正在尝试在下面工作set-strictmode -version latest,它在没有严格模式的情况下完全可以正常工作,不幸的是,在我的环境中需要有最新的严格模式。

它的作用:通过注册表查找带有 EEELinkAdvertisement 的条目并将其分配给 $findEeeLinkAd

$findEeeLinkAd = Get-ChildItem -LiteralPath 'hklm:\SYSTEM\ControlSet001\Control\Class' -Recurse -ErrorAction SilentlyContinue | `
   % {Get-ItemProperty -Path $_.pspath -ErrorAction SilentlyContinue | `
  ? {$_.EeeLinkAdvertisement} -ErrorAction SilentlyContinue }
Run Code Online (Sandbox Code Playgroud)

尽管在管理员中运行,我还是收到了一堆以下错误:

The property 'EEELinkAdvertisement' cannot be found on this object. Verify that the property exists.
At line:3 char:12
+         ? {$_.EEELinkAdvertisement} }
+            ~~~~~~~~~~~~~~~~~~~~~~~
    + CategoryInfo          : NotSpecified: (:) [], PropertyNotFoundException
    + FullyQualifiedErrorId : PropertyNotFoundStrict
Run Code Online (Sandbox Code Playgroud)

任何帮助,将不胜感激!

powershell android-strictmode

4
推荐指数
1
解决办法
1046
查看次数

Android 的 StrictMode 惩罚监听器给出 NoClassDefFoundError

我正在将 StrictMode 添加到我的应用程序中,并且在我添加自定义 ViolationListener 之前效果很好。

它似乎无法找到我提供的回调并将其检测为错误。

你能帮我一下吗?

以下代码工作得很好:

StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                    .detectAll()
                    .penaltyLog()
                    .build());
Run Code Online (Sandbox Code Playgroud)

以下代码不起作用:

StrictMode.setVmPolicy(new StrictMode.VmPolicy.Builder()
                .detectAll()
                .penaltyListener(Executors.newSingleThreadExecutor(), new StrictMode.OnVmViolationListener() {
                    @Override
                    public void onVmViolation(Violation v) {
                        //DO MY CUSTOM STUFF LIKE LOG IT TO CRASHLYTICS
                        Crashlytics.logException(v);
                    }
                })
                .penaltyLog()
                .build());
Run Code Online (Sandbox Code Playgroud)

这是 logcat 参考(对不起 Xs。这些涵盖了包名称......)

02-20 19:02:43.682 28793-28793/? W/System: ClassLoader referenced unknown path: /data/app/and.XXXXX.XXXXX.ib.qua-1/lib/arm64
02-20 19:02:43.696 28793-28793/? I/art: Rejecting re-init on previously-failed class java.lang.Class<and.XXXXX.XXXXX.ib.app.MyApp$CrashlyticsViolationListener>: java.lang.NoClassDefFoundError: Failed resolution of: Landroid/os/StrictMode$OnVmViolationListener;
Run Code Online (Sandbox Code Playgroud)

提前致谢!

顺便说一句:已经做了一个干净/构建/重建/禁用即时运行....

android crashlytics crashlytics-android android-strictmode

3
推荐指数
1
解决办法
731
查看次数

android 2.2中的严格模式

我的目标sdk设置为3.2,min sdk设置为2.2,我如何在我的应用程序中使用strictmode,因为据我所知它已经介绍但无法真正理解如何开始使用它.

android android-strictmode

2
推荐指数
2
解决办法
2万
查看次数

启用 StrictMode(检测全部)的 Crashlytics 给出“检测到未标记的套接字”

我已经尝试添加Crashlytics到我的应用程序中,该应用程序已经StrictMode启用了detectAll(). 结果是Untagged socket detected; use TrafficStats.setThreadSocketTag() to track all network usage

全栈:

E/StrictMode: null
java.lang.Throwable: Untagged socket detected; use TrafficStats.setThreadSocketTag() to track all network usage
    at android.os.StrictMode.onUntaggedSocket(StrictMode.java:2012)
    at com.android.server.NetworkManagementSocketTagger.tag(NetworkManagementSocketTagger.java:78)
    at libcore.io.BlockGuardOs.tagSocket(BlockGuardOs.java:47)
    at libcore.io.BlockGuardOs.socket(BlockGuardOs.java:310)
    at libcore.io.IoBridge.socket(IoBridge.java:667)
    at java.net.PlainSocketImpl.socketCreate(PlainSocketImpl.java:116)
    at java.net.AbstractPlainSocketImpl.create(AbstractPlainSocketImpl.java:98)
    at java.net.Socket.createImpl(Socket.java:484)
    at java.net.Socket.getImpl(Socket.java:547)
    at java.net.Socket.setSoTimeout(Socket.java:1175)
    at com.android.okhttp.internal.io.RealConnection.connectSocket(RealConnection.java:139)
    at com.android.okhttp.internal.io.RealConnection.connect(RealConnection.java:112)
    at com.android.okhttp.internal.http.StreamAllocation.findConnection(StreamAllocation.java:184)
    at com.android.okhttp.internal.http.StreamAllocation.findHealthyConnection(StreamAllocation.java:126)
    at com.android.okhttp.internal.http.StreamAllocation.newStream(StreamAllocation.java:95)
    at com.android.okhttp.internal.http.HttpEngine.connect(HttpEngine.java:281)
    at com.android.okhttp.internal.http.HttpEngine.sendRequest(HttpEngine.java:224)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.execute(HttpURLConnectionImpl.java:461)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponse(HttpURLConnectionImpl.java:407)
    at com.android.okhttp.internal.huc.HttpURLConnectionImpl.getResponseCode(HttpURLConnectionImpl.java:538)
    at com.android.okhttp.internal.huc.DelegatingHttpsURLConnection.getResponseCode(DelegatingHttpsURLConnection.java:105)
    at com.android.okhttp.internal.huc.HttpsURLConnectionImpl.getResponseCode(Unknown Source:0)
    at io.fabric.sdk.android.services.network.HttpRequest.code(HttpRequest.java:1357) …
Run Code Online (Sandbox Code Playgroud)

android crashlytics-android android-strictmode

2
推荐指数
1
解决办法
1828
查看次数

StrictMode:创建SharedPreference时的StrictModeDiskReadViolation

我有一个带有匕首设置的项目,具有以下提供者方法:

@Module(...)
abstract class AppModule {

  @Module
  companion object {
    ...
    @Provides
    @Singleton
    @JvmStatic
    fun provideSharedPreferences(@AppContext context: Context): SharedPreferences = PreferenceManager.getDefaultSharedPreferences(context)
  }

  @Binds
  @AppContext
  @Singleton
  abstract fun provideAppContext(application: Application): Context

}
Run Code Online (Sandbox Code Playgroud)

这是来自应用程序的代码onCreate():

override fun onCreate() {
  if (BuildConfig.DEBUG) {
    StrictMode.setThreadPolicy(StrictMode.ThreadPolicy.Builder()
        .detectAll()
        .penaltyLog()
        .penaltyDialog()
        .build())

    StrictMode.setVmPolicy(StrictMode.VmPolicy.Builder()
        .detectAll()
        .penaltyLog()
        .build())

    Timber.plant(Timber.DebugTree())
  }
  ...
  super.onCreate()
}
Run Code Online (Sandbox Code Playgroud)

在API 27模拟器上运行项目会导致以下行为:

使用以下日志:

D/StrictMode:StrictMode策略违规; 〜duration = 275 ms:android.os.StrictMode $ StrictModeDiskReadViolation:policy = 196671 violation = 2 at android.os.StrictMode $ AndroidBlockGuardPolicy.onReadFromDisk(StrictMode.java:1440)at java.io.UnixFileSystem.checkAccess(UnixFileSystem.java: 251)在java.io.File.exists(File.java:807)的android.app.ContextImpl.getDataDir(ContextImpl.java:2197)在Android上的android.app.ContextImpl.getPreferencesDir(ContextImpl.java:517).在Android.pretent.PreferenceManager.getDefaultSharedPreferences的android.content.ContextWrapper.getSharedPreferences(ContextWrapper.java:167)的android.app.ContextImpl.getSharedPreferences(ContextImpl.java:368)上的app.ContextImpl.getSharedPreferencesPath(ContextImpl.java:714) (PreferenceManager.java:526)com.some.package.di.module.AppModule $ Companion.provideSharedPreferences(AppModule.kt:112)...

这意味着,是 …

android disk-io kotlin android-sharedpreferences android-strictmode

1
推荐指数
1
解决办法
1622
查看次数

在android中使用StrictMode是否可以避免ANR?

我在某处读到,通过使用 StrictMode 我们可以避免 android 中的 ANR。我尝试过,下面是代码

public class MyApplication extends Application {

@Override
public void onCreate() {


        StrictMode.setThreadPolicy(new StrictMode.ThreadPolicy.Builder()
                .detectAll()
                .penaltyLog()
                .penaltyFlashScreen()
                .penaltyDeath()
                .detectDiskReads()
                .detectDiskWrites()
                .detectNetwork()
                .build());

    super.onCreate();
}
Run Code Online (Sandbox Code Playgroud)

我尝试生成 ANR 以用于测试目的,如下所示:

 @Override
public boolean onTouchEvent(MotionEvent event) {
    Log.d("kishan","onTouchEvent");
    while(true) {}
}
Run Code Online (Sandbox Code Playgroud)

但屏幕上仍然出现了 ANR。如何使用StrictMode避免ANR?是否可以?

android android-anr-dialog android-strictmode

1
推荐指数
1
解决办法
5218
查看次数