zoukankan      html  css  js  c++  java
  • android看不见main函数怎么办?程序异常了,能够不提示“xxx软件停止执行”吗?

    今天遇到了这个问题,分享一下解决方式。

    android没有main 函数,自然也就不存在main里面加入异常处理来实现全局异常捕获的方案。那android程序有全局异常补货的解决方式吗?

    答案是有的:

    那就是你得继承androidproject里面的application,如:

    public class ReaderApplication extends Application implements Thread.UncaughtExceptionHandler{......}

    并实现线程异常补货接口:Thread.UncaughtExceptionHandler

    这样你的程序,仅仅要有没有处理的异常,都会在以下的uncaughtException函数中被捕获了。我的做法是重新启动应用程序。

    	@Override
    	public void uncaughtException(Thread thread, Throwable ex) {
    		// TODO Auto-generated method stub
    		//System.exit(0);
    		
    		Intent intent = getBaseContext().getPackageManager()  
    	            .getLaunchIntentForPackage(getBaseContext().getPackageName());  
    	    		
    
            
            PendingIntent restartIntent = PendingIntent.getActivity(    
                    getApplicationContext(), 0, intent,    
                    Intent.FLAG_ACTIVITY_NEW_TASK);                                                 
            //退出程序                                          
            AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE);    
            mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000,    
                    restartIntent); // 1秒钟后重新启动应用   
            
            System.exit(0);
            
    	}


    但不得不说的是,你得在application的oncreate函数中加上异常回调接口的注冊:

    Thread.setDefaultUncaughtExceptionHandler(this);

    最后是,你得在AndroidManifest.xml中,将这句话改动为自己的Application:

     <application
            android:name="com.founder.reader.ReaderApplication"

    好了,有了上面的全局异常处理,也就不用所谓的main函数才干实现的了。同一时候,程序也不会再提示“xxx软件停止执行”了。

    最后:程序重新启动得用系统时钟来重新启动,否则程序都退出了,谁来运行重新启动任务:

    AlarmManager mgr = (AlarmManager)getSystemService(Context.ALARM_SERVICE); mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒钟后重新启动应用

    最最后,不忘给自己的小站点打个广告:程序猿必备软件:www.uhdesk.com

  • 相关阅读:
    证明欧几里得算法的正确性
    基础练习 十六进制转换八进制
    算法训练 关联矩阵
    寻找数组中最大值
    Torry的困惑(基本型)
    最小乘积(基本型)
    矩阵乘法
    SaltStack Char02 组件
    SaltStack Char01
    Python 学习手册, char 14
  • 原文地址:https://www.cnblogs.com/hrhguanli/p/4511130.html
Copyright © 2011-2022 走看看