GVKun编程网logo

为什么Spring Data存储库上的getOne(...)不会抛出EntityNotFoundException?(springdatajpa为什么没什么人用)

7

如果您对为什么SpringData存储库上的getOne感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于为什么SpringData存储库上的getOne的详细内容,我们还将为

如果您对为什么Spring Data存储库上的getOne感兴趣,那么本文将是一篇不错的选择,我们将为您详在本文中,您将会了解到关于为什么Spring Data存储库上的getOne的详细内容,我们还将为您解答...不会抛出EntityNotFoundException?的相关问题,并且为您提供关于android.content.ActivityNotFoundException: No Activity found to handle Intent、android.content.ActivityNotFoundException的实例源码、android.content.ActivityNotFoundException:找不到处理Intent的Activity、c# – 为什么我得到SecurityTokenSignatureKeyNotFoundException?的有价值信息。

本文目录一览:

为什么Spring Data存储库上的getOne(...)不会抛出EntityNotFoundException?(springdatajpa为什么没什么人用)

为什么Spring Data存储库上的getOne(...)不会抛出EntityNotFoundException?(springdatajpa为什么没什么人用)

我正在处理一个奇怪的问题,正在进行集成测试,调用控制器从不存在的数据库中获取对象。

public Optional<T> get(Long id) {  try {    return Optional.ofNullable(repository.getOne(id));  } catch(EntityNotFoundException e) {    return Optional.empty();  }}

getOne(…)什么都找不到的时候,我期待的EntityNotFoundException却是一无所获。如果检查结果,我可以看到我有一个空实体,并带有指向它的处理程序链接“
throw EntityNotFoundException”,但是我们没有进入陷阱,而是返回了这个怪异实体的可选要素。

我无法理解这种行为。

答案1

小编典典

这是由于JPA指定EntityManager.getReference(…)的工作方式。它应该返回一个代理,该代理将解析第一次访问属性时要返回的对象,或者最终抛出所包含的异常。

解决此问题的最简单方法是改为使用findOne(…),例如this
Optional.ofNullable(repository.findOne(…))。如果找不到结果,findOne(…)将返回null

解决此问题的一种更高级的方法是使存储库Optional直接返回实例。这可以通过使用-
methods的Optional<T>返回类型创建一个自定义的基本存储库接口来实现find…

interface BaseRepository<T, ID extends Serializable> extends Repository<T, ID> {  Optional<T> findOne(ID id);  // declare additional methods if needed}interface YourRepository extends BaseRepository<DomainClass, Long> { … }

在Spring Data示例库中找到一个完整的示例。

android.content.ActivityNotFoundException: No Activity found to handle Intent

android.content.ActivityNotFoundException: No Activity found to handle Intent

log:

12-07 14:35:20.541: I/System.out(272): 1:00
12-07 14:35:20.561: D/AndroidRuntime(272): Shutting down VM
12-07 14:35:20.561: W/dalvikvm(272): threadid=1: thread exiting with uncaught exception (group=0x4001d800)
12-07 14:35:20.581: E/AndroidRuntime(272): FATAL EXCEPTION: main
12-07 14:35:20.581: E/AndroidRuntime(272): android.content.ActivityNotFoundException: No Activity found to handle Intent { act=com.iStudy.Studying (has extras) }
12-07 14:35:20.581: E/AndroidRuntime(272): at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1408)
12-07 14:35:20.581: E/AndroidRuntime(272): at android.app.Instrumentation.execStartActivity(Instrumentation.java:1378)
12-07 14:35:20.581: E/AndroidRuntime(272): at android.app.Activity.startActivityForResult(Activity.java:2817)
12-07 14:35:20.581: E/AndroidRuntime(272): at android.app.Activity.startActivity(Activity.java:2923)
12-07 14:35:20.581: E/AndroidRuntime(272): at com.iStudy.Study.Main$1.onClick(Main.java:77)
12-07 14:35:20.581: E/AndroidRuntime(272): at android.view.View.performClick(View.java:2408)
12-07 14:35:20.581: E/AndroidRuntime(272): at android.view.View$PerformClick.run(View.java:8816)
12-07 14:35:20.581: E/AndroidRuntime(272): at android.os.Handler.handleCallback(Handler.java:587)
12-07 14:35:20.581: E/AndroidRuntime(272): at android.os.Handler.dispatchMessage(Handler.java:92)
12-07 14:35:20.581: E/AndroidRuntime(272): at android.os.Looper.loop(Looper.java:123)
12-07 14:35:20.581: E/AndroidRuntime(272): at android.app.ActivityThread.main(ActivityThread.java:4627)
12-07 14:35:20.581: E/AndroidRuntime(272): at java.lang.reflect.Method.invokeNative(Native Method)
12-07 14:35:20.581: E/AndroidRuntime(272): at java.lang.reflect.Method.invoke(Method.java:521)
12-07 14:35:20.581: E/AndroidRuntime(272): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-07 14:35:20.581: E/AndroidRuntime(272): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
12-07 14:35:20.581: E/AndroidRuntime(272): at dalvik.system.NativeStart.main(Native Method)

MainFest:


<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.iStudy.Study"
    android:versionCode="1"
    android:versionName="0.1 beta" >
    <uses-sdk android:minSdkVersion="8" 
        android:targetSdkVersion="17"/>
        <application android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/AppName" >
        <activity android:name=".Main">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
        
        <activity android:name=".Studying"
            android:exported="false">
            <intent-filter>
                <action android:name="com.iStudy.Study.Studying" />
                <category android:name="android.intent.category.DEFAULT" />
            </intent-filter>
        </activity>       
    </application>
</manifest>

出错的JAVA文件:

package com.iStudy.Study;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.Window;
import android.widget.TextView;

public class Studying extends Activity{

	static int minute = -1;
	static int second = -1;
	
	final static String tag = "tag";
	
	TextView timeview;
	Timer timer;
	TimerTask  timertask;
	
	Handler handler = new Handler(){
		public void handleMessage(Message msg) {
			System.out.println("Handle!");
			
			if (minute == 0) {
				if (second == 0) {
					timeview.setText("学习成功!");
					if (timer != null) {
						timer.cancel();
						timer = null;
					}
					if (timertask != null) {
						timertask = null;
					}
				}else {
					second--;
					if (second >= 10) {
						timeview.setText("0"+minute + ":" + second);
					}else {
						timeview.setText("0"+minute + ":0" + second);
					}
				}
			}else {
				if (second == 0) {
					second =59;
					minute--;
					if (minute >= 10) {
						timeview.setText(minute + ":" + second);
					}else {
						timeview.setText("0"+minute + ":" + second);
					}
				}else {
					second--;
					if (second >= 10) {
						if (minute >= 10) {
							timeview.setText(minute + ":" + second);
						}else {
							timeview.setText("0"+minute + ":" + second);
						}
					}else {
						if (minute >= 10) {
							timeview.setText(minute + ":0" + second);
						}else {
							timeview.setText("0"+minute + ":0" + second);
						}
					}
				}
			}
		};
	};
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		Log.v(tag, "log---------->onCreate!");
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		setContentView(R.layout.studying);
		timeview = (TextView)findViewById(R.id.Time);
		
		if (minute == -1 && second == -1) {
			Intent intent = getIntent();
			ArrayList<Integer> times = intent.getIntegerArrayListExtra("times");
			minute = times.get(0);
			second = times.get(1);
		}
		
		timeview.setText(minute + ":" + second);
		
		timertask = new TimerTask() {
			@Override
			public void run() {
				Message msg = new Message();
				msg.what = 0;
				handler.sendMessage(msg);
			}
		};
		
		timer = new Timer();
		timer.schedule(timertask,0,1000);
		
	}
	
	@Override
	protected void onDestroy() {
		Log.v(tag, "log---------->onDestroy!");
		if (timer != null) {
			timer.cancel();
			timer = null;
		}
		if (timertask != null) {
			timertask = null;
		}
		minute = -1;
		second = -1;
		super.onDestroy();
	}
	
	@Override
	protected void onStart() {
		Log.v(tag, "log---------->onStart!");
		super.onStart();
	}
	
	@Override
	protected void onStop() {
		Log.v(tag, "log---------->onStop!");
		super.onStop();
	}

	@Override
	protected void onResume() {
		Log.v(tag, "log---------->onResume!");
		super.onResume();
	}
	
	@Override
	protected void onRestart() {
		Log.v(tag, "log---------->onRestart!");
		super.onRestart();
	}
	
	@Override
	protected void onPause() {
		Log.v(tag, "log---------->onPause!");
		super.onPause();
	}
	
}
源码下载地址: http://www.kuaipan.cn/file/id_47491729724613150.htm

android.content.ActivityNotFoundException的实例源码

android.content.ActivityNotFoundException的实例源码

项目:Camera-Roll-Android-App    文件:ItemActivity.java   
public void setPhotoAs() {
    if (!(albumItem instanceof Photo)) {
        return;
    }

    Uri uri = albumItem.getUri(this);

    Intent intent = new Intent(Intent.ACTION_ATTACH_DATA);
    intent.setDataAndType(uri,MediaType.getMimeType(this,uri));
    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);

    try {
        startActivityForResult(Intent.createChooser(intent,getString(R.string.set_as)),13);
    } catch (SecurityException se) {
        Toast.makeText(this,"Error (SecurityException)",Toast.LENGTH_SHORT).show();
        se.printstacktrace();
    } catch (ActivityNotFoundException anfe) {
        Toast.makeText(this,"No App found",Toast.LENGTH_SHORT).show();
        anfe.printstacktrace();
    }
}
项目:PicShow-zhaipin    文件:DeviceUtils.java   
/**
 * 发送邮件
 *
 * @param context
 * @param subject 主题
 * @param content 内容
 * @param emails  邮件地址
 */
public static void sendEmail(Context context,String subject,String content,String... emails) {
    try {
        Intent intent = new Intent(Intent.ACTION_SEND);
        // 模拟器
        // intent.setType("text/plain");
        intent.setType("message/rfc822"); // 真机
        intent.putExtra(Intent.EXTRA_EMAIL,emails);
        intent.putExtra(Intent.EXTRA_SUBJECT,subject);
        intent.putExtra(Intent.EXTRA_TEXT,content);
        context.startActivity(intent);
    } catch (ActivityNotFoundException e) {
        e.printstacktrace();
    }
}
项目:MVPArms_Fragment-fragment    文件:DeviceUtils.java   
/**
 * 发送邮件
 *
 * @param context
 * @param subject 主题
 * @param content 内容
 * @param emails  邮件地址
 */
public static void sendEmail(Context context,content);
        context.startActivity(intent);
    } catch (ActivityNotFoundException e) {
        e.printstacktrace();
    }
}
项目:GitHub    文件:DeviceUtils.java   
/**
 * 发送邮件
 *
 * @param context
 * @param subject 主题
 * @param content 内容
 * @param emails  邮件地址
 */
public static void sendEmail(Context context,content);
        context.startActivity(intent);
    } catch (ActivityNotFoundException e) {
        e.printstacktrace();
    }
}
项目:VirtualAPK    文件:VAInstrumentation.java   
private ActivityResult realExecStartActivity(
        Context who,IBinder contextThread,IBinder token,Activity target,Intent intent,int requestCode,Bundle options) {
    ActivityResult result = null;
    try {
        Class[] parameterTypes = {Context.class,IBinder.class,Activity.class,Intent.class,int.class,Bundle.class};
        result = (ActivityResult)ReflectUtil.invoke(Instrumentation.class,mBase,"execStartActivity",parameterTypes,who,contextThread,token,target,intent,requestCode,options);
    } catch (Exception e) {
        if (e.getCause() instanceof ActivityNotFoundException) {
            throw (ActivityNotFoundException) e.getCause();
        }
        e.printstacktrace();
    }

    return result;
}
项目:GitHub    文件:CameraPickerHelper.java   
private void startCameraIntent(final Activity activity,final Fragment fragment,String subFolder,final String action,final int requestCode) {
    final String cameraOutDir = @R_301_6253@ingFileHelper.getExternalDCIM(subFolder);
    try {
        if (@R_301_6253@ingFileHelper.createFile(cameraOutDir)) {
            mOutputFile = new File(cameraOutDir,String.valueOf(System.currentTimeMillis()) + ".jpg");
            mSourceFilePath = mOutputFile.getPath();
            Intent intent = new Intent(action);
            Uri uri = getFileUri(activity.getApplicationContext(),mOutputFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT,uri);
            try {
                startActivityForResult(activity,fragment,requestCode);
            } catch (ActivityNotFoundException ignore) {
                callbackerror();
            }

        }
    } catch (ExecutionException | InterruptedException e) {
        @R_301_6253@ingLog.d("create file" + cameraOutDir + " error.");
    }

}
项目:kognitivo    文件:LoginManager.java   
private boolean tryFacebookActivity(
        StartActivityDelegate startActivityDelegate,LoginClient.Request request) {

    Intent intent = getFacebookActivityIntent(request);

    if (!resolveIntent(intent)) {
        return false;
    }

    try {
        startActivityDelegate.startActivityForResult(
                intent,LoginClient.getLoginRequestCode());
    } catch (ActivityNotFoundException e) {
        return false;
    }

    return true;
}
项目:aurora    文件:DeviceUtils.java   
/**
 * 发送邮件
 *
 * @param context
 * @param subject 主题
 * @param content 内容
 * @param emails  邮件地址
 */
public static void sendEmail(Context context,content);
        context.startActivity(intent);
    } catch (ActivityNotFoundException e) {
        e.printstacktrace();
    }
}
项目:LaunchEnr    文件:Launcher.java   
public boolean startActivitySafely(View v,ItemInfo item) {
    if (mIsSafeModeEnabled && !Utilities.isSystemApp(this,intent)) {
        Toast.makeText(this,R.string.safemode_shortcut_error,Toast.LENGTH_SHORT).show();
        return false;
    }
    // Only launch using the new animation if the shortcut has not opted out (this is a
    // private contract between launcher and may be ignored in the future).
    boolean useLaunchAnimation = (v != null) &&
            !intent.hasExtra(INTENT_EXTRA_IGnorE_LAUNCH_ANIMATION);
    Bundle optsBundle = useLaunchAnimation ? getActivityLaunchOptions(v) : null;

    UserHandle user = item == null ? null : item.user;

    // Prepare intent
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    if (v != null) {
        intent.setSourceBounds(getViewBounds(v));
    }
    try {
        if (AndroidVersion.isAtLeastMarshmallow
                && (item instanceof ShortcutInfo)
                && (item.itemType == Favorites.ITEM_TYPE_SHORTCUT
                 || item.itemType == Favorites.ITEM_TYPE_DEEP_SHORTCUT)
                && !((ShortcutInfo) item).isPromise()) {
            // Shortcuts need some special checks due to legacy reasons.
            startShortcutIntentSafely(intent,optsBundle,item);
        } else if (user == null || user.equals(Process.myUserHandle())) {
            // Could be launching some bookkeeping activity
            startActivity(intent,optsBundle);
        } else {
            LauncherAppsCompat.getInstance(this).startActivityForProfile(
                    intent.getComponent(),user,intent.getSourceBounds(),optsBundle);
        }
        return true;
    } catch (ActivityNotFoundException|SecurityException e) {
        Toast.makeText(this,R.string.activity_not_found,Toast.LENGTH_SHORT).show();
        e.printstacktrace();
    }
    return false;
}
项目:Kids-Portal-Android    文件:helper_main.java   
private static void openFile(Activity activity,File file,String string,View view) {

        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_VIEW);
        intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            intent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
            Uri contentUri = FileProvider.getUriForFile(activity,activity.getApplicationContext().getPackageName() + ".provider",file);
            intent.setDataAndType(contentUri,string);

        } else {
            intent.setDataAndType(Uri.fromFile(file),string);
        }

        try {
            activity.startActivity (intent);
        } catch (ActivityNotFoundException e) {
            Snackbar.make(view,R.string.toast_install_app,Snackbar.LENGTH_LONG).show();
        }
    }
项目:simple-share-android    文件:StandaloneActivity.java   
@Override
public void onDocumentPicked(DocumentInfo doc) {
    final FragmentManager fm = getFragmentManager();
    if (doc.isDirectory()) {
        mState.stack.push(doc);
        mState.stackTouched = true;
        onCurrentDirectoryChanged(ANIM_DOWN);
    } else {
        // Fall back to viewing
        final Intent view = new Intent(Intent.ACTION_VIEW);
        view.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        view.setData(doc.derivedUri);
        try {
            startActivity(view);
        } catch (ActivityNotFoundException ex2) {
            Toast.makeText(this,R.string.toast_no_application,Toast.LENGTH_SHORT).show();
        }
    }
}
项目:Paper-Launcher    文件:IntentUtil.java   
public static void startGoogleSearchActivity(View view) {
    final Context context = view.getContext();

    final SearchManager searchManager =
            (SearchManager) context.getSystemService(Context.SEARCH_SERVICE);
    if (searchManager == null) {
        return;
    }

    ComponentName globalSearchActivity = searchManager.getGlobalSearchActivity();
    if (globalSearchActivity == null) {
        return;
    }

    Intent intent = new Intent(SearchManager.INTENT_ACTION_GLOBAL_SEARCH);
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    intent.setComponent(globalSearchActivity);

    Bundle appSearchData = new Bundle();
    appSearchData.putString("source",context.getPackageName());

    intent.putExtra(SearchManager.APP_DATA,appSearchData);
    intent.setSourceBounds(getViewBounds(view));
    try {
        context.startActivity(intent);
    } catch (ActivityNotFoundException ex) {
        ex.printstacktrace();
    }
}
项目:okwallet    文件:RequestCoinsFragment.java   
private void handleLocalApp() {
    final ComponentName component = new ComponentName(activity,SendCoinsActivity.class);
    final PackageManager pm = activity.getPackageManager();
    final Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(determineBitcoinRequestStr(false)));

    try {
        // launch intent chooser with ourselves excluded
        pm.setComponentEnabledSetting(component,PackageManager.COMPONENT_ENABLED_STATE_disABLED,PackageManager.DONT_KILL_APP);
        startActivity(intent);
    } catch (final ActivityNotFoundException x) {
        new Toast(activity).longToast(R.string.request_coins_no_local_app_msg);
    } finally {
        pm.setComponentEnabledSetting(component,PackageManager.COMPONENT_ENABLED_STATE_ENABLED,PackageManager.DONT_KILL_APP);
    }

    activity.finish();
}
项目:amap    文件:OsUtils.java   
public static void gotoWchat(Activity activity)
{
    try
    {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        ComponentName cmp = new ComponentName("com.tencent.mm","com.tencent.mm.ui.LauncherUI");

        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setComponent(cmp);
        activity.startActivity(intent);
    }
    catch (ActivityNotFoundException e)
    {
        Toast.makeText(activity,"检查到您手机没有安装微信,请安装后使用该功能",Toast.LENGTH_LONG).show();
    }
}
项目:GxIconAndroid    文件:ExtraUtil.java   
public static void shareText(Context context,String hint) {
    if (context == null || TextUtils.isEmpty(content)) {
        return;
    }

    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("text/plain");
    intent.putExtra(Intent.EXTRA_TEXT,content);
    try {
        if (TextUtils.isEmpty(hint)) {
            context.startActivity(intent);
        } else {
            context.startActivity(Intent.createChooser(intent,hint));
        }
    } catch (ActivityNotFoundException e) {
        e.printstacktrace();
    }
}
项目:chromium-for-android-56-debug-video    文件:UpdateMenuItemHelper.java   
/**
 * Handles a click on the update menu item.
 * @param activity The current {@link ChromeActivity}.
 */
public void onMenuItemClicked(ChromeActivity activity) {
    if (mUpdateUrl == null) return;

    // If the update menu item is showing because it was forced on through about://flags
    // then mLatestVersion may be null.
    if (mLatestVersion != null) {
        PrefServiceBridge.getInstance().setLatestVersionWhenClickedUpdateMenuItem(
                mLatestVersion);
    }

    // Fire an intent to open the URL.
    try {
        Intent launchIntent = new Intent(Intent.ACTION_VIEW,Uri.parse(mUpdateUrl));
        activity.startActivity(launchIntent);
        recordItemClickedHistogram(ITEM_CLICKED_INTENT_LAUNCHED);
        PrefServiceBridge.getInstance().setClickedUpdateMenuItem(true);
    } catch (ActivityNotFoundException e) {
        Log.e(TAG,"Failed to launch Activity for: %s",mUpdateUrl);
        recordItemClickedHistogram(ITEM_CLICKED_INTENT_Failed);
    }
}
项目:Floo    文件:OpenDirectlyHandler.java   
@Override
public boolean onTargetNotFound(
    @NonNull Context context,@NonNull Uri uri,@NonNull Bundle bundle,@Nullable Integer intentFlags) {

    Intent intent = new Intent(Intent.ACTION_VIEW,uri);
    intent.putExtras(bundle);
    if (intentFlags != null) {
        intent.setFlags(intentFlags);
    }
    try {
        context.startActivity(intent);
    } catch (ActivityNotFoundException exception) {
        exception.printstacktrace();
        return false;
    }
    return true;
}
项目:RLibrary    文件:RUtils.java   
/**
 * qq咨询
 */
public static boolean chatQQ(Context context,String qq) {
    try {
        if (CmdUtil.checkApkExist(context,"com.tencent.mobileqq")) {
            String url = "mqqwpa://im/chat?chat_type=wpa&uin=" + qq;
            Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
            intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            context.startActivity(intent);
            return true;
        } else {
            T_.error("您没有安装腾讯QQ");
        }
    } catch (ActivityNotFoundException e) {
        e.printstacktrace();
        T_.error("您没有安装腾讯QQ");
    }
    return false;
}
项目:LoggingInterceptor    文件:MainActivity.java   
private void downloadFile(ResponseBody body) throws IOException {
    int count;
    byte data[] = new byte[1024 * 4];
    InputStream bis = new BufferedInputStream(body.byteStream(),1024 * 8);
    outputFile = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"file.zip");
    OutputStream output = new FileOutputStream(outputFile);
    while ((count = bis.read(data)) != -1) {
        output.write(data,count);
    }

    output.flush();
    output.close();
    bis.close();

    Intent target = new Intent(Intent.ACTION_VIEW);
    target.setDataAndType(Uri.fromFile(outputFile),"application/pdf");
    target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

    Intent intent = Intent.createChooser(target,"Open File");
    try {
        startActivity(intent);
    } catch (ActivityNotFoundException e) {
        e.printstacktrace();
    }
}
项目:CSI-KJSCEOfficial    文件:Utils.java   
public static void onShareClick(Context context,String message,String appName) {

        Intent sendIntent = new Intent(Intent.ACTION_SEND);
        sendIntent.setType("text/plain");

        // message might be in html form,so convert back to plain text
        message = Html.fromHtml(message).toString();
        sendIntent.putExtra(Intent.EXTRA_TEXT,message);
        if(!appName.isEmpty())
            sendIntent.setPackage(appName);
       try {
           context.startActivity(sendIntent);
       } catch(ActivityNotFoundException e){
           Log.e("Social Share","package does not exist");
           Toast.makeText(context,"Action not supported",Toast.LENGTH_SHORT).show();
       }

    }
项目:appinventor-extensions    文件:BarcodeScanner.java   
/**
 * Begins a barcode scan,using the camera. When the scan is complete,the
 * AfterScan event will be raised.
 */
@SimpleFunction(description = "Begins a barcode scan,using the camera. When the scan " +
    "is complete,the AfterScan event will be raised.")
public void DoScan() {
  Intent intent = new Intent(SCAN_INTENT);
  if (!useExternalScanner && (SdkLevel.getLevel() >= SdkLevel.LEVEL_ECLAIR)) {  // Should we attempt to use an internal scanner?
    String packageName = container.$form().getPackageName();
    intent.setComponent(new ComponentName(packageName,"com.google.zxing.client.android.AppInvCaptureActivity"));
  }
  if (requestCode == 0) {
    requestCode = form.registerForActivityResult(this);
  }
  try {
    container.$context().startActivityForResult(intent,requestCode);
  } catch (ActivityNotFoundException e) {
    e.printstacktrace();
    container.$form().dispatchErrorOccurredEvent(this,"BarcodeScanner",ErrorMessages.ERROR_NO_SCANNER_FOUND,"");
  }
}
项目:Perfect-Day    文件:CreateTaskBySpeech.java   
@OnClick(R.id.btnSpeak)
public void onSpeakButtonClick() {
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE,Locale.getDefault());
    intent.putExtra(RecognizerIntent.EXTRA_PROMPT,getString(R.string.speech_prompt));
    try {
        startActivityForResult(intent,REQ_CODE_SPEECH_INPUT);
    } catch (ActivityNotFoundException a) {
        Toast.makeText(getApplicationContext(),getString(R.string.speech_not_supported),Toast.LENGTH_SHORT).show();
    }
}
项目:MVPArmsTest1    文件:DeviceUtils.java   
/**
 * 发送邮件
 *
 * @param context
 * @param subject 主题
 * @param content 内容
 * @param emails  邮件地址
 */
public static void sendEmail(Context context,content);
        context.startActivity(intent);
    } catch (ActivityNotFoundException e) {
        e.printstacktrace();
    }
}
项目:FicsaveMiddleware    文件:FicsaveDownloadListener.java   
private void openFileOnDevice(Uri mostRecentDownload) {
    Intent fileIntent = new Intent(Intent.ACTION_VIEW);
    // DownloadManager stores the Mime Type. Makes it really easy for us.
    String mimeType =
            mDownloadManager.getMimeTypeForDownloadedFile(fileDownloadId);
    fileIntent.setDataAndType(mostRecentDownload,mimeType);
    fileIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    try {
        mContext.startActivity(fileIntent);
    } catch (ActivityNotFoundException e) {
        Log.d("ficsaveM/cantOpenFile",fileName);
        trackFileCannotopen();
        Toast.makeText(mContext,"You don't have a supported ebook reader",Toast.LENGTH_LONG).show();
    }
}
项目:Say_it    文件:SearchActivity.java   
/**
 * Showing google speech input dialog
 */
private void promptSpeechinput() {
    Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
    intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,Toast.LENGTH_SHORT).show();
    }
}
项目:android-about-@R_301_6253@    文件:About@R_301_6253@Utils.java   
public static void openApplication(Activity context,String appURI,String webURI) {
    try {
        context.startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(appURI)));
    } catch (ActivityNotFoundException e1) {
        try {
            openHTMLPage(context,webURI);
        } catch (ActivityNotFoundException e2) {
            Toast.makeText(context,R.string.egab_can_not_open,Toast.LENGTH_SHORT).show();
        }
    }
}
项目:https-github.com-hyb1996-norootScriptDroid    文件:IntentUtil.java   
public static boolean browse(Context context,String link) {
    try {
        Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(link)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(intent);
        return true;
    } catch (ActivityNotFoundException ignored) {
        return false;
    }

}
项目:decoy    文件:VideoMessageHelper.java   
/**
 * API19 之前选择视频
 */
protected void chooseVideoFromLocalBeforeKitKat() {
    Intent mIntent = new Intent(Intent.ACTION_GET_CONTENT);
    mIntent.setType(C.MimeType.MIME_VIDEO_ALL);
    mIntent.putExtra(Intent.EXTRA_LOCAL_ONLY,true);
    try {
        activity.startActivityForResult(mIntent,localRequestCode);
    } catch (ActivityNotFoundException e) {
        Toast.makeText(activity,R.string.gallery_invalid,Toast.LENGTH_SHORT).show();
    }
}
项目:SimpleAvatarPicker    文件:AbstractAvatarPicker.java   
private void startActivityToCropImage() {
    mIntentBuilder.outputUri(mUri);
    Intent intent = mIntentBuilder.buildCropApp();
    try {
        startActivityForResult(intent,REQ_CODE_CROP_AVATAR);
    } catch (ActivityNotFoundException e) {
        showToastMsg("Your device is not support to crop image.");
    }
}
项目:tvConnect_android    文件:ResultHandler.java   
final void openURL(String url) {
  // Strangely,some Android browsers don't seem to register to handle HTTP:// or HTTPS://.
  // Lower-case these as it should always be OK to lower-case these schemes.
  if (url.startsWith("HTTP://")) {
    url = "http" + url.substring(4);
  } else if (url.startsWith("HTTPS://")) {
    url = "https" + url.substring(5);
  }
  Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse(url));
  try {
    launchIntent(intent);
  } catch (ActivityNotFoundException ignored) {
    Log.w(TAG,"nothing available to handle " + intent);
  }
}
项目:OpenHub    文件:AppOpener.java   
public static void launchEmail(@NonNull Context context,@NonNull String email){
    Intent intent = new Intent(Intent.ACTION_SEND);
    intent.setType("message/rfc822");
    intent.putExtra(Intent.EXTRA_EMAIL,new String[]{email});
    intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    try{
        context.startActivity(Intent.createChooser(intent,context.getString(R.string.send_email)));
    }catch (ActivityNotFoundException e){
        Toasty.warning(context,context.getString(R.string.no_email_clients)).show();
    }
}
项目:decoy    文件:PreviewImageFromCameraActivity.java   
/**
 * 获取本地图片
 */
protected void choosePictureFromLocal() {
    if (!StorageUtil.hasEnoughSpaceForWrite(PreviewImageFromCameraActivity.this,StorageType.TYPE_IMAGE,true)) {
        return;
    }

    new AsyncTask<String,Integer,Boolean>() {

        @Override
        protected void onPreExecute() {
            Toast.makeText(PreviewImageFromCameraActivity.this,R.string.waitfor_image_local,Toast.LENGTH_LONG).show();
        }

        @Override
        protected Boolean doInBackground(String... params) {
            return true;
        }

        @Override
        protected void onPostExecute(Boolean result) {
            Intent intent = new Intent(Intent.ACTION_PICK,MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
            if (Build.VERSION.SDK_INT >= 11) {
                intent.putExtra(Intent.EXTRA_LOCAL_ONLY,true);
            }
            try {
                PreviewImageFromCameraActivity.this.startActivityForResult(intent,RequestCode.GET_LOCAL_IMAGE);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(PreviewImageFromCameraActivity.this,Toast.LENGTH_LONG).show();
            }
        }
    }.execute();
}
项目:Bigbang    文件:AppItem.java   
@Override
public boolean openUI(Context context) {
    try {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.addCategory(Intent.CATEGORY_LAUNCHER);
        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
        intent.setComponent(mName);
        mContext.startActivity(intent);
    } catch (ActivityNotFoundException e) {
    }
    return true;
}
项目:chilly    文件:SearchFragment.java   
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    mSpinnerFragment = new SpinnerFragment();
    mRowsAdapter = new ArrayObjectAdapter(new ListRowPresenter());
    mVideoCursorAdapter.setMapper(new VideoCursorMapper());
    setSearchResultProvider(this);
    setonItemViewClickedListener(new ItemViewClickedListener());
    if (DEBUG) {
        Log.d(TAG,"User is initiating a search. Do we have RECORD_AUdio permission? " +
            hasPermission(Manifest.permission.RECORD_AUdio));
    }
    if (!hasPermission(Manifest.permission.RECORD_AUdio)) {
        if (DEBUG) {
            Log.d(TAG,"Does not have RECORD_AUdio,using SpeechRecognitionCallback");
        }
        // SpeechRecognitionCallback is not required and if not provided recognition will be
        // handled using internal speech recognizer,in which case you must have RECORD_AUdio
        // permission
        setSpeechRecognitionCallback(new SpeechRecognitionCallback() {
            @Override
            public void recognizeSpeech() {
                try {
                    startActivityForResult(getRecognizerIntent(),REQUEST_SPEECH);
                } catch (ActivityNotFoundException e) {
                    Log.e(TAG,"Cannot find activity for speech recognizer",e);
                }
            }
        });
    } else if (DEBUG) {
        Log.d(TAG,"We DO have RECORD_AUdio");
    }
}
项目:AndiCar    文件:StatisticsActivity.java   
private void share() {
    try {
        Intent shareIntent = new Intent(Intent.ACTION_SENDTO);
        shareIntent.setData(Uri.parse("mailto:"));
        shareIntent.putExtra(Intent.EXTRA_SUBJECT," AndiCar - " + getTitle());
        shareIntent.putExtra(Intent.EXTRA_TEXT,mEmailText_Filters.toString().replace("\t","    ") + "\n\n" +
                        "Data:\n" +
                        mEmailText_Values.toString().replace("\t","    ") + "\n\nSent by AndiCar (http://www.andicar.org)");
        startActivity(shareIntent);
    }
    catch (ActivityNotFoundException e) {
        Utils.showNotReportableErrorDialog(this,e.getMessage(),null);
    }
}
项目:three-things-today    文件:MainActivity.java   
@Override
public boolean onoptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.mi_export_database:
            new DatabaseExportTask(this,mThreeThingsDatabase).execute();
            return true;
        case R.id.mi_import_database:
            Intent intent = new Intent(Intent.ACTION_GET_CONTENT);
            intent.setType("*/*");
            intent.addCategory(Intent.CATEGORY_OPENABLE);
            try {
                startActivityForResult(Intent.createChooser(intent,"Select a file to open"),DATABASE_IMPORT_CODE);
            } catch (ActivityNotFoundException e) {
                Toast.makeText(getApplicationContext(),"Please install a File Manager",Toast.LENGTH_LONG).show();
            }
            return true;
        case R.id.mi_sign_in_sign_out:
            if (FirebaseAuth.getInstance().getCurrentUser() == null) {
                Intent signInIntent = AuthUI.getInstance().createSignInIntentBuilder()
                        .setProviders(Arrays.asList(new AuthUI.IdpConfig.Builder(AuthUI.GOOGLE_PROVIDER).build()))
                        .build();
                startActivityForResult(signInIntent,FIREBASE_SIGN_IN_CODE);
            } else {
                FirebaseAuth.getInstance().signOut();
                Toast.makeText(this,"Signed out",Toast.LENGTH_SHORT).show();
            }
            return true;
        case R.id.mi_test_notification:
            Intent notificationIntent = new Intent(this,NotificationIntentService.class);
            startService(notificationIntent);
            return true;
        default:
            return super.onoptionsItemSelected(item);
    }
}
项目:NoticeDog    文件:AppManager.java   
void safeStartActivity(Intent intent) {
    try {
        this.context.startActivity(intent);
    } catch (ActivityNotFoundException e) {
        Log.d(TAG,"Failed to start activity");
    }
}
项目:MBEStyle    文件:AboutFragment.java   
private void openUrl(String url) {
    try {
        startActivity(new Intent(Intent.ACTION_VIEW,Uri.parse(url)).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK));
    } catch (ActivityNotFoundException e) {
        e.printstacktrace();
    }
}
项目:android-banklink    文件:RequestTest.java   
@Test
public void createIntentWithOldSwedbankAppThrows() {
  try {
    installApp("com.swedbank",1,SWEDBANK_SIGNATURE);
    final Intent banklinkIntent = eeClient.createBanklinkIntent(SIGNED_PACKET_MAP);
    fail();
  } catch (ActivityNotFoundException e) {
    assertthat(e.getMessage()).isEqualTo("Swedbank app is not installed on this device.");
  }
}
项目:Cable-Android    文件:ConversationActivity.java   
private void handleAddToContacts() {
  try {
    final Intent intent = new Intent(Intent.ACTION_INSERT_OR_EDIT);
    intent.putExtra(ContactsContract.Intents.Insert.PHONE,recipients.getPrimaryRecipient().getNumber());
    intent.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
    startActivityForResult(intent,ADD_CONTACT);
  } catch (ActivityNotFoundException e) {
    Log.w(TAG,e);
  }
}

android.content.ActivityNotFoundException:找不到处理Intent的Activity

android.content.ActivityNotFoundException:找不到处理Intent的Activity

我是 Android的新手.我正在尝试使用谷歌位置API,当在模拟器中运行它显示不幸的是你的应用程序停止工作.
我做了一个adb logcat,这是我的stacktrace
10-31 23:43:02.010  2370  2370 D AndroidRuntime: >>>>>> START     com.android.internal.os.RuntimeInit uid 0 <<<<<<
10-31 23:43:02.011  2370  2370 D AndroidRuntime: CheckJNI is ON
10-31 23:43:02.026  2370  2370 I art     : JIT created with code_cache_capacity=2MB compile_threshold=1000
10-31 23:43:02.030  2370  2370 D ICU     : No timezone override file found: /data/misc/zoneinfo/current/icu/icu_tzdata.dat
10-31 23:43:02.044  2370  2370 E memtrack: Couldn't load memtrack module (No such file or directory)
10-31 23:43:02.044  2370  2370 E android.os.Debug: Failed to load memtrack module: -2
10-31 23:43:02.045  2370  2370 I Radio-JNI: register_android_hardware_Radio DONE
10-31 23:43:02.062  2370  2370 D AndroidRuntime: Calling main entry com.android.commands.pm.Pm
10-31 23:43:02.073  2228  2240 I art     : CollectorTransition marksweep + semispace GC freed 125(-7KB) AllocSpace objects,0(0B) LOS objects,57% free,379KB/891KB,paused 5.591ms total 5.591ms
10-31 23:43:02.080  2228  2242 D DefContainer: copying /data/local/tmp/HighwayMechanic.apk to base.apk
10-31 23:43:02.181  1138  1177 I PackageManager.DexOptimizer: Running dexopt (dex2oat) on: /data/app/vmdl931695514.tmp/base.apk pkg=com.highway.highwaymechanic isa=x86 vmSafeMode=false debuggable=true oatDir = /data/app/vmdl931695514.tmp/oat
10-31 23:43:02.190  2382  2382 W dex2oat : Unexpected cpu variant for X86 using defaults: x86
10-31 23:43:02.190  2382  2382 W dex2oat : Mismatch between dex2oat instruction set features (ISA: X86 Feature string: smp,-ssse3,-sse4.1,-sse4.2,-avx,-avx2) and those of dex2oat executable (ISA: X86 Feature string: smp,ssse3,-avx2) for the command line:
10-31 23:43:02.190  2382  2382 W dex2oat : /system/bin/dex2oat --zip-fd=6 --zip-location=base.apk --oat-fd=7 --oat-location=/data/app/vmdl931695514.tmp/oat/x86/base.odex --instruction-set=x86 --instruction-set-variant=x86 --instruction-set-features=default --runtime-arg -xms64m --runtime-arg -Xmx512m --swap-fd=8 --debuggable
10-31 23:43:02.190  2382  2382 I dex2oat : /system/bin/dex2oat --debuggable
10-31 23:43:08.200  2382  2382 I dex2oat : dex2oat took 6.009s (threads: 1) arena alloc=2MB java alloc=6MB native alloc=32MB free=2MB
10-31 23:43:08.276  1138  1162 I ActivityManager: Force stopping com.highway.highwaymechanic appid=10053 user=-1: uninstall pkg
10-31 23:43:08.294  1138  1177 I PackageManager: Package com.highway.highwaymechanic codePath changed from /data/app/com.highway.highwaymechanic-2 to /data/app/com.highway.highwaymechanic-1; Retaining data and using new
10-31 23:43:08.295  1138  1162 I ActivityManager: Force stopping com.highway.highwaymechanic appid=10053 user=-1: replace pkg
10-31 23:43:08.296  1138  1177 W PackageManager: Code path for com.highway.highwaymechanic changing from /data/app/com.highway.highwaymechanic-2 to /data/app/com.highway.highwaymechanic-1
10-31 23:43:08.296  1138  1177 W PackageManager: Resource path for com.highway.highwaymechanic changing from /data/app/com.highway.highwaymechanic-2 to /data/app/com.highway.highwaymechanic-1
10-31 23:43:08.333  1138  1177 W Settings: Setting install_non_market_apps has moved from android.provider.Settings.Global to android.provider.Settings.Secure,returning read-only value.
10-31 23:43:08.333  1138  1177 I art     : Starting a blocking GC Explicit
10-31 23:43:08.353  1138  1177 I art     : Explicit concurrent mark sweep GC freed 10787(756KB) AllocSpace objects,11(220KB) LOS objects,19% free,5MB/6MB,paused 517us total 13.651ms
10-31 23:43:08.357  1138  1177 W PackageManager: Couldn't remove dex file for package:  at location /data/app/com.highway.highwaymechanic-2/base.apk,retcode=-1
10-31 23:43:08.359  1138  1177 I ActivityManager: Force stopping com.highway.highwaymechanic appid=10053 user=0: pkg removed
10-31 23:43:08.360  2370  2370 I art     : System.exit called,status: 0
10-31 23:43:08.360  2370  2370 I AndroidRuntime: VM exiting with result code 0.
10-31 23:43:08.400  1138  1138 D JobSchedulerService: Receieved: android.intent.action.PACKAGE_REMOVED
10-31 23:43:08.403  1566  1566 D CarrierServiceBindHelper: Receive action: android.intent.action.PACKAGE_REMOVED
10-31 23:43:08.404  1566  1566 D CarrierServiceBindHelper: mHandler: 3
10-31 23:43:08.404  1138  1255 I InputReader: Reconfiguring input devices.  changes=0x00000010
10-31 23:43:08.414  1925  1925 W ContextImpl: Calling a method in the system process without a qualified user:  android.app.ContextImpl.startService:1221  android.content.Contextwrapper.startService:581 android.content.Contextwrapper.startService:581 com.android.keychain.KeyChainbroadcastReceiver.onReceive:12 android.app.ActivityThread.handleReceiver:2725 
10-31 23:43:08.418  1138  1641 I broadcastQueue: Delay finish: com.android.keychain/.KeyChainbroadcastReceiver
10-31 23:43:08.514  1138  1255 I InputReader: Reconfiguring input devices.  changes=0x00000010
10-31 23:43:08.515  1138  2212 I broadcastQueue: Resuming delayed broadcast
10-31 23:43:08.516  1566  1566 D CarrierServiceBindHelper: Receive action: android.intent.action.PACKAGE_ADDED
10-31 23:43:08.516  1566  1566 D CarrierServiceBindHelper: mHandler: 3
10-31 23:43:08.602  1138  1255 I InputReader: Reconfiguring input devices.  changes=0x00000010
10-31 23:43:08.602  1566  1566 D CarrierServiceBindHelper: Receive action: android.intent.action.PACKAGE_REPLACED
10-31 23:43:08.602  1566  1566 D CarrierServiceBindHelper: mHandler: 3
10-31 23:43:08.602  1566  1566 D CarrierConfigLoader: mHandler: 9 phoneId: 0
10-31 23:43:08.617  2390  2390 D AndroidRuntime: >>>>>> START com.android.internal.os.RuntimeInit uid 0 <<<<<<
10-31 23:43:08.619  2390  2390 D AndroidRuntime: CheckJNI is ON
10-31 23:43:08.635  2390  2390 I art     : JIT created with code_cache_capacity=2MB compile_threshold=1000
10-31 23:43:08.640  2390  2390 D ICU     : No timezone override file found: /data/misc/zoneinfo/current/icu/icu_tzdata.dat
10-31 23:43:08.654  2390  2390 E memtrack: Couldn't load memtrack module (No such file or directory)
10-31 23:43:08.654  2390  2390 E android.os.Debug: Failed to load memtrack module: -2
10-31 23:43:08.655  2390  2390 I Radio-JNI: register_android_hardware_Radio DONE
10-31 23:43:08.667  2390  2390 D AndroidRuntime: Calling main entry com.android.commands.am.Am
10-31 23:43:08.669  1138  2212 I ActivityManager: START u0 {act=android.intent.action.MAIN cat=[android.intent.category.LAUNCHER] flg=0x10000000 cmp=com.highway.highwaymechanic/.MainActivity} from uid 0 on display 0
10-31 23:43:08.691  2390  2390 D AndroidRuntime: Shutting down VM
10-31 23:43:08.695  2390  2395 I art     : Debugger is no longer active
10-31 23:43:08.695  2390  2401 E art     : Thread attaching while runtime is shutting down: Binder_2
10-31 23:43:08.695  2390  2401 I AndroidRuntime: NOTE: attach of thread 'Binder_2' Failed
10-31 23:43:08.697  2402  2402 I art     : Not late-enabling -Xcheck:jni (already on)
10-31 23:43:08.697  2402  2402 I art     : Late-enabling JIT
10-31 23:43:08.702  2402  2402 I art     : JIT created with code_cache_capacity=2MB compile_threshold=1000
10-31 23:43:08.708  1138  1712 I ActivityManager: Start proc 2402:com.highway.highwaymechanic/u0a53 for activity com.highway.highwaymechanic/.MainActivity
10-31 23:43:08.717  2402  2409 E art     : Failed sending reply to debugger: broken pipe
10-31 23:43:08.717  2402  2409 I art     : Debugger is no longer active
10-31 23:43:08.728  2402  2402 W System  : ClassLoader referenced unkNown path: /data/app/com.highway.highwaymechanic-1/lib/x86
10-31 23:43:08.747  2402  2402 W GooglePlayServicesUtil: Google Play services is missing.
10-31 23:43:08.747  2402  2402 W GooglePlayServicesUtil: Google Play services is missing.
10-31 23:43:08.747  2402  2402 W GooglePlayServicesUtil: Google Play services is missing.
10-31 23:43:08.747  2402  2402 W GooglePlayServicesUtil: Google Play services is missing.
10-31 23:43:08.748  2402  2402 W GooglePlayServicesUtil: Google Play services is missing. 
10-31 23:43:08.748  2402  2402 W GooglePlayServicesUtil: Google Play services is missing.
10-31 23:43:08.755  2402  2402 W GooglePlayServicesUtil: Google Play services is missing.
10-31 23:43:08.755  2402  2402 W GooglePlayServicesUtil: Google Play services is missing.
10-31 23:43:08.755  2402  2402 W GooglePlayServicesUtil: Google Play services is missing.
10-31 23:43:08.764  2402  2402 W GooglePlayServicesUtil: Google Play services is missing.
10-31 23:43:08.764  2402  2402 W GooglePlayServicesUtil: Google Play services is missing.
10-31 23:43:08.797  2402  2402 D gralloc_goldfish: Emulator without GPU emulation detected.
10-31 23:43:08.818  1138  1170 I ActivityManager: displayed com.highway.highwaymechanic/.MainActivity: +129ms
10-31 23:43:10.932  1138  1429 I ActivityManager: START u0 {act=android.intent.action.VIEW dat=market://details?id=com.google.android.gms&pcampaignid=gcore_8115000--- flg=0x80000 pkg=com.android.vending} from uid 10053 on display 0
10-31 23:43:10.933  2402  2402 D AndroidRuntime: Shutting down VM
10-31 23:43:10.933  2402  2402 E AndroidRuntime: FATAL EXCEPTION: main
10-31 23:43:10.933  2402  2402 E AndroidRuntime: Process: com.highway.highwaymechanic,PID: 2402
10-31 23:43:10.933  2402  2402 E AndroidRuntime: android.content.ActivityNotFoundException: No Activity found to handle Intent { act=android.intent.action.VIEW dat=market://details?id=com.google.android.gms&pcampaignid=gcore_8115000--- flg=0x80000 pkg=com.android.vending }
10-31 23:43:10.933  2402  2402 E AndroidRuntime:    at android.app.Instrumentation.checkStartActivityResult(Instrumentation.java:1798)
10-31 23:43:10.933  2402  2402 E AndroidRuntime:    at android.app.Instrumentation.execStartActivity(Instrumentation.java:1512)
10-31 23:43:10.933  2402  2402 E AndroidRuntime:    at android.app.Activity.startActivityForResult(Activity.java:3917)
10-31 23:43:10.933  2402  2402 E AndroidRuntime:    at android.app.Activity.startActivityForResult(Activity.java:3877)
10-31 23:43:10.933  2402  2402 E AndroidRuntime:    at android.support.v4.app.FragmentActivity.startActivityForResult(FragmentActivity.java:748)
10-31 23:43:10.933  2402  2402 E AndroidRuntime:    at android.app.Activity.startActivity(Activity.java:4200)
10-31 23:43:10.933  2402  2402 E AndroidRuntime:    at android.app.Activity.startActivity(Activity.java:4168)
10-31 23:43:10.933  2402  2402 E AndroidRuntime:    at com.google.android.gms.dynamic.zza$5.onClick(UnkNown Source)
10-31 23:43:10.933  2402  2402 E AndroidRuntime:    at android.view.View.performClick(View.java:5198)
10-31 23:43:10.933  2402  2402 E AndroidRuntime:    at android.view.View$PerformClick.run(View.java:21147)
10-31 23:43:10.933  2402  2402 E AndroidRuntime:    at android.os.Handler.handleCallback(Handler.java:739)
10-31 23:43:10.933  2402  2402 E AndroidRuntime:    at android.os.Handler.dispatchMessage(Handler.java:95)
10-31 23:43:10.933  2402  2402 E AndroidRuntime:    at android.os.Looper.loop(Looper.java:148)
10-31 23:43:10.933  2402  2402 E AndroidRuntime:    at android.app.ActivityThread.main(ActivityThread.java:5417)
10-31 23:43:10.933  2402  2402 E AndroidRuntime:    at java.lang.reflect.Method.invoke(Native Method)
10-31 23:43:10.933  2402  2402 E AndroidRuntime:    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:726)
10-31 23:43:10.933  2402  2402 E AndroidRuntime:    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:616)
10-31 23:43:10.934  1138  1712 W ActivityManager:   Force finishing activity com.highway.highwaymechanic/.MainActivity
10-31 23:43:10.935   943   943 D gralloc : Registering a buffer in the process that created it. This may cause memory ordering problems.
10-31 23:43:10.935   943   943 E libEGL  : called unimplemented OpenGL ES API
10-31 23:43:10.935   943   943 E SurfaceFlinger: glCheckFramebufferStatusOES error 1711643839
10-31 23:43:10.935   943   943 E SurfaceFlinger: got GL_FRAMEBUFFER_COMPLETE_OES error while taking screenshot
10-31 23:43:11.448  1138  1162 W ActivityManager: Activity pause timeout for ActivityRecord{40e8f1c u0 com.highway.highwaymechanic/.MainActivity t11 f}
10-31 23:43:21.478  1138  1162 W ActivityManager: Activity destroy timeout for ActivityRecord{40e8f1c u0 com.highway.highwaymechanic/.MainActivity t11 f}

这是我的Android_manifest.xml

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.highway.highwaymechanic"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
    android:minSdkVersion="14"
    android:targetSdkVersion="23" />

    <application
    android:allowBackup="true"
    android:icon="@drawable/ic_launcher"
    android:label="@string/app_name"
    android:theme="@style/AppTheme" >
     <Meta-data 
         android:name="com.google.android.gms.version" 
         android:value="@integer/google_play_services_version" />
     <activity
        android:name=".MainActivity"
        android:label="@string/app_name" >
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />

            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
      </activity>
      <activity
        android:name="com.highway.highwaymechanic.Map"
        android:label="@string/title_activity_map" >
     </activity>
   </application>
</manifest>

这是我的MainActivity.java文件

package com.highway.highwaymechanic;


import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;

public class MainActivity extends FragmentActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
}

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

@Override
public boolean onoptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button,so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onoptionsItemSelected(item);
  }
}

这是我的MapsActivity.java文件

package com.highway.highwaymechanic;

     import android.os.Bundle;
     import android.support.v4.app.FragmentActivity;
     import com.google.android.gms.maps.CameraUpdateFactory;
     import com.google.android.gms.maps.GoogleMap;
     import com.google.android.gms.maps.OnMapReadyCallback;
     import com.google.android.gms.maps.SupportMapFragment;
     import com.google.android.gms.maps.model.LatLng;
     import com.google.android.gms.maps.model.MarkerOptions;


     public class MapsActivity extends FragmentActivity implements OnMapReadyCallback {
    @Override
     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_map);
        SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
                .findFragmentById(R.id.map);
        mapFragment.getMapAsync(this);
    }

    @Override
    public void onMapReady(GoogleMap map) {

        LatLng sydney = new LatLng(-34,151);
        map.addMarker(new MarkerOptions().position(sydney).title("Marker in Sydney"));
        map.moveCamera(CameraUpdateFactory.newLatLng(sydney));
     }
   }

当在模拟器中运行它崩溃时不幸的是应用程序停止工作.

请帮帮我.
提前致谢

解决方法

我相信这应该是最新版本的Google Play服务客户端库修复的.请注意,这是客户端库中的修复,因此您必须使用SDK管理器将库更新为最新版本并重新编译应用程序.

有关详细信息,请查看此链接

https://code.google.com/p/gmaps-api-issues/issues/detail?id=4862

c# – 为什么我得到SecurityTokenSignatureKeyNotFoundException?

c# – 为什么我得到SecurityTokenSignatureKeyNotFoundException?

当我尝试将此JWT(由Azure移动服务发布)作为HTTP标头/授权/承载令牌传递时:
Header:
{
    "alg": "HS256","typ": "JWT","kid": "0"
}
Claims:
{
    "ver": 2,"aud": "Facebook","iss": "urn:microsoft:windows-azure:zumo","urn:microsoft:credentials": "pYK8b5...","exp": 1436730730,"uid": "Facebook:10000xxxxxxxxxx"
}

进入我的ASP.NET WEB API配置:

const string issuer = "urn:microsoft:windows-azure:zumo";
byte[] mobileServicesSecret = TextEncodings.Base64Url.Decode(ConfigurationManager.AppSettings["as:SecretKey"]);

app.UseJwtBearerAuthentication(
    new JwtBearerAuthenticationoptions
    {
      AuthenticationMode = AuthenticationMode.Active,AllowedAudiences = new[] { "Facebook" },IssuerSecurityTokenProviders = new IIssuerSecurityTokenProvider[]
              {
                  new SymmetricKeyIssuerSecurityTokenProvider(issuer,mobileServicesSecret)
              }
    });

我明白了:

A first chance exception of type
‘System.IdentityModel.Tokens.SecurityTokenSignatureKeyNotFoundException’
occurred in System.IdentityModel.Tokens.Jwt.dll

我怀疑这是因为“孩子”财产的存在?

编辑:使用这个https://github.com/Magenic/JWTvalidator/tree/master/JwtValidator/JwtValidator,可以验证JWT,所以它没有错.但我真的想用OWIN / Katana.

解决方法

Google建议如下 –
Calling the tokeninfo endpoint

Rather than writing your own code to perform these verification steps,we strongly recommend using a Google Api client library for your platform,or calling our tokeninfo validation endpoint.

To validate an ID token using the tokeninfo endpoint,make an HTTPS POST or GET request to the endpoint,and pass your ID token in the id_token parameter. For example,to validate the token “XYZ123”,make the following GET request:

CustomJwtHandler.cs

using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens;
using System.Linq;
using System.Net.Http;
using System.Web;
using System.Web.Configuration;
using Newtonsoft.Json;
using System.Net;
using System.Threading.Tasks;
using System.Threading;
using Services.Models;
using System.Security.Claims;

namespace Services
{
    /// <summary>
    ///  This is an implementation of Google JWT verification that
    ///  demonstrates:
    ///    - JWT validation
    /// </summary>
    /// @author kunal.bajpai@gmail.com (Kunal Bajpai)


    public class CustomJwtHandler : DelegatingHandler
    {
        private const string URL_GOOGLE_TOKEN_INFO = "https://www.googleapis.com/oauth2/v3/tokeninfo";

        /// <summary>
        /// 
        /// </summary>
        /// <param name="request"></param>
        /// <param name="cancellationToken"></param>
        /// <returns></returns>
        protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request,CancellationToken cancellationToken)
        {
            HttpStatusCode statusCode;
            string token;

            var authHeader = request.Headers.Authorization;
            if (authHeader == null)
            {
                // Missing authorization header
                return base.SendAsync(request,cancellationToken);
            }

            if (!TryRetrievetoken(request,out token))
            {
                return Task<HttpResponseMessage>.Factory.StartNew(() => new HttpResponseMessage(HttpStatusCode.Unauthorized));
            }

            try
            {
                Validatetoken(token);
                return base.SendAsync(request,cancellationToken);
            }
            catch (SecurityTokenInvalidAudienceException)
            {
                statusCode = HttpStatusCode.Unauthorized;
            }
            catch (SecurityTokenValidationException)
            {
                statusCode = HttpStatusCode.Unauthorized;
            }
            catch (Exception)
            {
                statusCode = HttpStatusCode.InternalServerError;
            }

            return Task<HttpResponseMessage>.Factory.StartNew(() => new HttpResponseMessage(statusCode));
        }
        /// <summary>
        /// Validates JWT Token
        /// </summary>
        /// <param name="JwtToken"></param>
        private void Validatetoken(string JwtToken)
        {
            try
            {
                using (WebClient wc = new WebClient())
                {
                    TokenInfo tokenInfo = JsonConvert.DeserializeObject<TokenInfo>(wc.DownloadString(URL_GOOGLE_TOKEN_INFO + "?id_token=" + JwtToken));

                    ClaimsPrincipal claimsPrincipal = new ClaimsPrincipal(new ClaimsIdentity(ExtractClaims(tokenInfo),tokenInfo.Issuer));

                    Thread.CurrentPrincipal = claimsPrincipal;
                    HttpContext.Current.User = claimsPrincipal;
                }
            }
            catch (WebException e)
            {
                HttpStatusCode statusCode = ((HttpWebResponse)e.Response).StatusCode;
                if (statusCode == HttpStatusCode.BadRequest)
                {
                    throw new SecurityTokenValidationException();
                }
                else
                {
                    throw new Exception();
                }
            }
        }

        /// <summary>
        /// Tries to retrieve Token
        /// </summary>
        /// <param name="request"></param>
        /// <param name="token"></param>
        /// <returns></returns>
        private static bool TryRetrievetoken(HttpRequestMessage request,out string token)
        {
            token = null;
            IEnumerable<string> authorizationHeaders;

            if (!request.Headers.TryGetValues("Authorization",out authorizationHeaders) ||
            authorizationHeaders.Count() > 1)
            {
                return false;
            }

            var bearerToken = authorizationHeaders.ElementAt(0);
            token = bearerToken.StartsWith("Bearer ") ? bearerToken.Substring(7) : bearerToken;
            return true;
        }

        private List<Claim> ExtractClaims(TokenInfo tokenInfo)
        {
            List<Claim> claims = new List<Claim> {
                new Claim(ClaimTypes.Name,tokenInfo.Name),new Claim(ClaimTypes.Email,tokenInfo.Email),new Claim(ClaimTypes.Givenname,tokenInfo.Givenname),new Claim(ClaimTypes.Surname,tokenInfo.FamilyName),new Claim(ApplicationUser.CLaim_TYPE_LOCALE,tokenInfo.Locale),new Claim(ClaimTypes.NameIdentifier,tokenInfo.ProviderKey,ClaimValueTypes.String,tokenInfo.Issuer),new Claim(ApplicationUser.CLaim_TYPE_EMAIL_CONFIRMED,tokenInfo.IsEmailVerifed.ToString(),ClaimValueTypes.Boolean)
            };

            return claims;
        }
    }
}

TokenInfo.cs

using Microsoft.AspNet.Identity.EntityFramework;
using Newtonsoft.Json;

namespace Services.Models
{
    public class TokenInfo
    {
        [JsonProperty("iss")]
        public string Issuer { get; set; }

        [JsonProperty("aud")]
        public string AudienceClientId { get; set; }

        [JsonProperty("sub")]
        public string ProviderKey { get; set; }

        [JsonProperty("email_verified")]
        public bool IsEmailVerifed { get; set; }

        [JsonProperty("azp")]
        public string AndroidClientId { get; set; }

        [JsonProperty("email")]
        public string Email { get; set; }

        [JsonProperty("iat")]
        public long IssuedAt { get; set; }

        [JsonProperty("exp")]
        public long ExpiresAt { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; }

        [JsonProperty("picture")]
        public string Picture { get; set; }

        [JsonProperty("given_name")]
        public string Givenname { get; set; }

        [JsonProperty("family_name")]
        public string FamilyName { get; set; }

        [JsonProperty("locale")]
        public string Locale { get; set; }

        [JsonProperty("alg")]
        public string Algorithm { get; set; }

        [JsonProperty("kid")]
        public string kid { get; set; }

        public override bool Equals(object obj)
        {
            if (obj.GetType() != typeof(ApplicationUser))
            {
                return false;
            }

            ApplicationUser user = (ApplicationUser)obj;
            bool hasLogin = false;

            foreach (IdentityUserLogin login in user.Logins)
            {
                if (login.ProviderKey == ProviderKey)
                {
                    hasLogin = true;
                    break;
                }
            }
            if (!hasLogin) { return false; }

            if (user.FirstName != Givenname) { return false; }
            if (user.LastName != FamilyName) { return false; }
            if (user.Locale != Locale) { return false; }

            return base.Equals(obj);
        }
    }
}

WebApiConfig.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http;
using System.Web.Http;
using Microsoft.Owin.Security.OAuth;
using Newtonsoft.Json.Serialization;

namespace Services
{
    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {
            // Web API configuration and services
            // Configure Web API to use only bearer token authentication.
            config.SuppressDefaultHostAuthentication();
            config.Filters.Add(new HostAuthenticationFilter(OAuthDefaults.AuthenticationType));

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",routeTemplate: "api/{controller}/{id}",defaults: new { id = RouteParameter.Optional }
            );
            config.MessageHandlers.Add(new CustomJwtHandler());
        }
    }
}

关于为什么Spring Data存储库上的getOne...不会抛出EntityNotFoundException?的介绍现已完结,谢谢您的耐心阅读,如果想了解更多关于android.content.ActivityNotFoundException: No Activity found to handle Intent、android.content.ActivityNotFoundException的实例源码、android.content.ActivityNotFoundException:找不到处理Intent的Activity、c# – 为什么我得到SecurityTokenSignatureKeyNotFoundException?的相关知识,请在本站寻找。

本文标签: